source: trunk/src/uvmat.m @ 745

Last change on this file since 745 was 745, checked in by sommeria, 10 years ago

set_slice installed

File size: 248.6 KB
Line 
1%'uvmat': function associated with the GUI 'uvmat.fig' for images and data field visualization
2%------------------------------------------------------------------------
3% function huvmat=uvmat(input)
4%
5%OUTPUT
6% huvmat=current handles of the GUI uvmat.fig
7%%
8%
9%INPUT:
10% input: input file name (if character chain), or input image matrix to
11% visualize, or Matlab structure representing  netcdf fieldname (with fieldname
12% ListVarName....)
13%
14%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
15%  Copyright Joel Sommeria,  2008, LEGI / CNRS-UJF-INPG, joel.sommeria@legi.grenoble-inp.fr.
16%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
17%     This open is part of the toolbox UVMAT.
18%
19%     UVMAT is free software; you can redistribute it and/or modify
20%     it under the terms of the GNU General Public License as published by
21%     the Free Software Foundation; either version 2 of the License, or
22%     (at your option) any later version.
23%
24%     UVMAT is distributed in the hope that it will be useful,
25%     but WITHOUT ANY WARRANTY; without even the implied warranty of
26%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27%     GNU General Public License (open UVMAT/COPYING.txt) for more details.
28%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
29%
30% Information stored on the interface:(use 'Export/field in workspace' in
31% the menu bar of uvmat to retrieve it)
32%          .OpenParam: structure containing parameters defined when uvmat is opened
33%                       .PosColorbar: position (1x4 vector)of the colorbar (relative to the fig uvmat)
34%                       .PosGeometryCalib: size of set_object
35%                       .NbBuiltin: nbre of functions always displayed in TransformName menu
36%          .ProjObject: cell array of structures representing the current projection objects, as produced by 'set_object.m'={[]} by default
37%          .NewSeries: =0/1 flag telling whether a new field series has been opened
38%          .FileName_1: name of the current second field (used to detect a  constant field during file scanning)
39%          .FileType: current file type, as defined by the fct  get_file_type.m)
40%          .i1_series,.i2_series,.j1_series,.j1_series: series of i1,i2,j1,j2 indices detected in the input dir,set by  the fct find_file_series
41%          .MovieObject: current movie object
42%          .TimeUnit: unit for time
43%          .XmlData: cell array of 1 or 2 structures representing the xml files associated with the input fieldname (containing timing  and geometry calibration)
44%          .Field: cell array of 1 or 2 structures representing the current  input field(s)
45%          .PlotAxes: field structure representing the current field plotted  on the main axes  (used for mouse operations)
46%          .HistoAxes: idem for histogram axes
47
48% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   DATA FLOW  (for REFRESH_Callback) %%%%%%%%%%%%%%%%%%%%:
49%
50%
51% 1) Input filenames are determined by MenuBrowse (first field), MenuBrowseCampaign
52% (second field), or by the stored file name .FileName_1, or as an input of uvmat.
53% 2) These functions call 'uvmat/display_file_name.m' which detects the file series, and fills the file index boxes
54% 3) Then 'uvmat/update_rootinfo.m' Updates information about a new field series (indices to scan, timing, calibration from an xml file)
55% 4) Then fieldname are opened and visualised by the main sub-function 'uvmat/refresh_field.m'
56% The function first reads the name of the input file(s) (one or two) from the edit boxes  of the GUI
57% It then reads the input file(s) with the function read_field.m and perform the following list of operations:
58%
59%    %%%%%%%%  structure of uvmat/refresh_field.m %%%%%%%%
60%
61%           Main input open       second input open_1       
62%                    |                   | 
63%             read_field.m            read_field.m
64%                    |                   |
65%                 Field{1}            Field{2}               
66%                    |                   |                                 
67%                    --->transform fct<---             transform (e.g. phys.m) and combine input fieldname 
68%                            |                                   
69%                        (tps_coeff_field.m)               calculate tps coefficients (for filter projection or spatial derivatives).
70%                            |
71%                       UvData.Field-------------->histogram
72%               _____________|____________
73%              |                          |                   
74%        proj_field.m               proj_field.m       project the field on the projection objects (use set_field_list.m)           
75%              |                          |
76%         UvData.PlotAxes          ViewData.PlotAxes (on view_field)
77%              |                          |
78%       plot_field.m (uvmat)       plot_field.m (view_field)      plot the projected fieldname
79%
80%
81%%%%%%%%%%%%%%    SCALARS: %%%%%%%%%%%%??%%%
82% scalars are displayed either as an image or countour plot, either as a color of
83% velocity vectors. The scalar values in the first case is represented by
84% UvData.Field.A, and by UvData.Field.C in the second case. The corresponding set of X
85% and Y coordinates are represented by UvData.Field.AX and UvData.Field.AY, and .X and
86% .Y for C (the same as velocity vectors). If A is a nxxny matrix (scalar
87% on a regtular grid), then .AX andf.AY contains only two elements, represneting the
88% coordinates of the four image corners. The scalar name is represented by
89% the strings .AName and/or .CName.
90% If the scalar exists in an input open (image or scalar stored under its
91% name in a netcdf open), it is directly read at the level of Field{1}or Field{2}.
92% Else only its name AName is recorded in Field{i}, and its field is then calculated
93%by the fuction calc_scal after the coordinate transform or after projection on an CheckEditObject
94     
95% Properties attached to plotting figures (standard Matlab properties):
96%    'CurrentAxes'= gca or get(gcf,'CurrentAxes');
97%    'CurrentPoint'=get(gcf,'CurrentPoint'): figure coordinates of the point over which the mouse is positioned
98%    'CurrentCharacter'=get(gcf,'CurrentCharacter'): last character typed  over the figure where the mouse is positioned
99%    'WindowButtonMotionFcn': function permanently called by mouse motion over the figure
100%    'KeyPressFcn': function called by pressing a key on the key board
101%    'WindowButtonDownFcn':  function called by pressing the mouse over the  figure
102%    'WindowButtonUpFcn': function called by releasing  the mouse pressure over the  figure
103
104% Properties attached to plotting axes:
105%    'CurrentPoint'=get(gca,'CurrentPoint'); (standard Matlab) same as for the figure, but position in plot coordinates.
106%     AxeData:=get(gca,'UserData');
107%     AxeData.Drawing  = create: create a new object
108%                       = deform: modify an existing object by moving its defining create
109%                      = off: no current drawing action
110%                     = translate: translate an existing object
111%                    = calibration: move a calibration point
112%                    = CheckZoom: isolate a subregion for CheckZoom in=1 if an object is being currently drawn, 0 else (set to 0 by releasing mouse button)
113%            .CurrentOrigin: Origin of a curently drawn CheckEditObject
114%            .CurrentLine: currently drawn menuline (A REVOIR)
115%            .CurrentObject: handle of the currently drawn CheckEditObject
116%            .CurrentRectZoom: current rectangle used for CheckZoom
117
118% Properties attached to projection objects (create, menuline, menuplane...):
119%    'Tag'='proj_object': for all projection objects
120%    ObjectData.Type=...: style of projection object:
121%              .ProjMode
122%              .Coord: defines the position of the object
123%              .XMin,YMin....
124%              .XMax,YMax....
125%              .DX,DY,DZ
126%              .Phi, .Theta, .Psi : Euler angles
127%              .X,.Y,.U,.V.... : field data projected on the object
128%              .IndexObj: index in the list of UvData.ProjObject
129           %during plotting
130%               .plotaxes: handles of the current axes used to plot the  result of field projection on the object
131%               .plothandle: vector of handle(s) of the object graphic represnetation in all the opened plotting axes
132% To each projection object #iobj, corresponds an axis
133% Object{iobj}.plotaxes and nbobj representation graphs  Object{iobj}.plothandles(:) (where nbobj is the
134% nbre of current objects opened in uvmat. Note that Object{iobj}.plothandles(iobj)=[] : an object is not represented in its own projection field;
135
136%------------------------------------------------------------------------
137%------------------------------------------------------------------------
138%  I - MAIN FUNCTION uvmat
139%------------------------------------------------------------------------
140%------------------------------------------------------------------------
141function varargout = uvmat(varargin)
142
143% Begin initialization code - DO NOT EDIT
144gui_Singleton = 1;
145gui_State = struct('gui_Name',          mfilename, ...
146                   'gui_Singleton',     gui_Singleton, ...
147                   'gui_OpeningFcn',    @uvmat_OpeningFcn, ...
148                   'gui_OutputFcn',     @uvmat_OutputFcn, ...
149                   'gui_LayoutFcn',     [], ...
150                   'gui_Callback',      []);
151if nargin && ischar(varargin{1})&& ~isempty(regexp(varargin{1},'_Callback','once'))
152    gui_State.gui_Callback = str2func(varargin{1});
153end
154
155if nargout
156    varargout{1:nargout} = gui_mainfcn(gui_State, varargin{:});
157else
158    gui_mainfcn(gui_State, varargin{:});
159end
160% End initialization code - DO NOT EDIT
161
162%------------------------------------------------------------------------
163% --- Executes just before the GUI uvmat is made visible.
164function uvmat_OpeningFcn(hObject, eventdata, handles, input )
165%------------------------------------------------------------------------
166
167%% Choose default command menuline output for uvmat (standard GUI)
168handles.output = hObject;
169
170%% Update handles structure (standard GUI)
171guidata(hObject, handles);
172
173%% add the path to uvmat (useful if uvmat has been opened in the working directory and a working directory change occured)
174path_uvmat=fileparts(which('uvmat'));
175
176%% set the position of the GUI, colorbar and ancillary GUIs:
177set(hObject,'Units','pixels')%
178set(0,'Units','pixels');
179ScreenSize=get(0,'ScreenSize');%size of the current screen
180Width=1050;
181Height=700;
182%adjust to screen size (reduced by a min margin)
183RescaleFactor=min((ScreenSize(3)-80)/Width,(ScreenSize(4)-80)/Height);
184if RescaleFactor>1
185    RescaleFactor=RescaleFactor/2+1/2; %reduce the rescale factor to provide an increased margin for a big screen
186end
187Width=Width*RescaleFactor;
188Height=Height*RescaleFactor;
189LeftX=80*RescaleFactor;%position of the left fig side, in pixels (put to the left side, with some margin)
190LowY=round(ScreenSize(4)/2-Height/2); % put at the middle height on the screen
191set(hObject,'Position',[LeftX LowY Width Height])
192UvData.OpenParam.PosColorbar=[0.80 0.02 0.018 0.445];
193% UvData.OpenParam.PosGeometryCalib=[0.95 -0.03 0.28 1 ];%position for geometry_calib
194AxeData.LimEditBox=1; %initialise AxeData
195set(handles.PlotAxes,'UserData',AxeData)
196% position of table Coord_y
197set(handles.Coord_y,'Unit','pixel')
198Pos=get(handles.Coord_y,'Position');
199set(handles.Coord_y,'Unit','normalized')
200set(handles.Coord_y,'ColumnWidth',{Pos(3)})
201set(handles.Coord_y,'ColumnFormat',{'char'})
202set(handles.Coord_y,'ColumnEditable',false)
203set(handles.Coord_y,'ColumnName',{''})
204
205%% set functions for the mouse and keyboard
206set(hObject,'WindowKeyPressFcn',{'keyboard_callback',handles})%set keyboard action function
207set(hObject,'WindowButtonMotionFcn',{'mouse_motion',handles})%set mouse action functio
208set(hObject,'WindowButtonDownFcn',{'mouse_down'})%set mouse click action function
209set(hObject,'WindowButtonUpFcn',{'mouse_up',handles})
210set(hObject,'DeleteFcn',{@closefcn})%
211set(hObject,'ResizeFcn',{@ResizeFcn,handles})%
212% set(handles.RootPath,'ButtonDownFcn',{'@mouse_down_control'})%set mouse click action function
213
214%% initialisation
215set(handles.FieldName,'Value',1)
216set(handles.FieldName,'string',{''})
217UvData.ProjObject={[]};
218
219%% TRANSFORM menu: builtin fcts
220transform_menu={'';'sub_field';'phys';'phys_polar'};
221UvData.OpenParam.NbBuiltin=numel(transform_menu); %number of functions
222transform_path=fullfile(path_uvmat,'transform_field');
223path_list=cell(UvData.OpenParam.NbBuiltin,1);
224path_list{1}='';
225for ilist=2:UvData.OpenParam.NbBuiltin
226path_list{ilist}=transform_path; % set transform_path to the path_list
227end
228
229%% load the list of previously browsed files in menus Open, Open_1 and TransformName
230dir_perso=prefdir; % path to the directory .matlab containing the personal data of the current user
231profil_perso=fullfile(dir_perso,'uvmat_perso.mat');% personal data file uvmat_perso.mat' in .matlab
232if exist(profil_perso,'file')% if the file exists
233    h=load (profil_perso); % open the personal file
234    if isfield(h,'MenuFile')% load the saved menu of previously opened files
235        for ifile=1:min(length(h.MenuFile),5)
236            set(handles.(['MenuFile_' num2str(ifile)]),'Label',h.MenuFile{ifile});
237        end
238    end
239    if isfield(h,'MenuCampaign')% load the saved menu of previously opened campaigns
240        for ifile=1:min(length(h.MenuCampaign),5)
241            set(handles.(['MenuCampaign_' num2str(ifile)]),'Label',h.MenuCampaign{ifile});
242        end
243    end
244    if isfield(h,'RootPath')
245        set(handles.RootPath,'UserData',h.RootPath); %store the previous campaign in the UserData of RootPath
246    end
247    if isfield(h,'transform_fct') && iscell(h.transform_fct) % load the menu of transform fct set by user
248        for ilist=1:length(h.transform_fct);
249            if exist(h.transform_fct{ilist},'file')
250                [path,file]=fileparts(h.transform_fct{ilist});
251                transform_menu=[transform_menu; {file}];
252                path_list=[path_list; {path}];
253            end
254        end
255    end
256end
257transform_menu=[transform_menu;{'more...'}];%append the option more.. to the menu
258set(handles.TransformName,'String',transform_menu)% display the menu of transform fcts
259set(handles.TransformName,'UserData',path_list)% store the corresponding list of path in UserData of uicontrol transform_fct
260set(handles.TransformPath,'String','')
261set(handles.TransformPath,'UserData',[])
262
263%% case of an input argument for uvmat
264testinputfield=0;
265inputfile=[];
266Field=[];
267if exist('input','var')
268    if ishandle(handles.UVMAT_title)
269        delete(handles.UVMAT_title)
270    end   
271    if isstruct(input)
272        if isfield(input,'InputFile')
273            inputfile=input.InputFile;
274        end
275        if isfield(input,'TimeIndex')
276            set(handles.i1,num2str(input.TimeIndex))
277        end
278        if isfield(input,'FieldsString')
279            UvData.FieldsString=input.FieldsString;
280        end
281    elseif ischar(input)% file name introduced as input
282           inputfile=input;
283    elseif isnumeric(input)%simple matrix introduced as input
284        sizinput=size(input);
285        if sizinput(1)<=1 || sizinput(2)<=1
286            msgbox_uvmat('ERROR','bad input for uvmat: file name, structure or numerical matrix accepted')
287            return
288        end
289        UvData.Field.ListVarName={'A','coord_y','coord_x'};
290        UvData.Field.VarDimName={{'coord_y','coord_x'},'cord_y','coord_x'};
291        UvData.Field.A=input;
292        UvData.Field.coord_x=[0.5 size(input,2)-0.5];
293        UvData.Field.coord_y=[size(input,1)-0.5 0.5];
294        testinputfield=1;
295    end
296else
297    %% check the path and date of modification of all functions in uvmat
298    path_to_uvmat=which ('uvmat');% check the path detected for source file uvmat
299    [infomsg,date_str,svn_info]=check_files;%check the path of the functions called by uvmat.m   
300    date_str=['last modification: ' date_str];
301    if ishandle(handles.UVMAT_title)
302        set(handles.UVMAT_title,'String',...
303            [{'Copyright  LEGI UMR 5519 /CNRS-UJF-Grenoble INP, 2010'};...
304            {'GNU General Public License'};...
305            {path_to_uvmat};...
306            {date_str};...
307            infomsg]);
308    end
309end
310set(handles.uvmat,'UserData',UvData)
311if ~isempty(inputfile)
312    %%%%% display the input field %%%%%%%
313    display_file_name(handles,inputfile)
314    %%%%%%%
315end
316
317set_vec_col_bar(handles) %update the display of color code for vectors
318
319%------------------------------------------------------------------------
320% --- Outputs from this function are returned to the command menuline.
321function varargout = uvmat_OutputFcn(hObject, eventdata, handles)
322%------------------------------------------------------------------------   
323varargout{1} = handles.output;% the only output argument is the handle to the GUI figure
324
325%------------------------------------------------------------------------
326% --- executed when closing uvmat: delete or desactivate the associated figures if exist
327function closefcn(gcbo,eventdata)
328%------------------------------------------------------------------------
329% delete GUI 'view_field' if detected
330hh=findobj(allchild(0),'tag','view_field');
331if ~isempty(hh)
332    delete(hh)
333end
334% delete GUI 'geometry_calib' if detected
335hh=findobj(allchild(0),'tag','geometry_calib');
336if ~isempty(hh)
337    delete(hh)
338end
339% desable set_object editing action if detected
340hh=findobj(allchild(0),'name','set_object');
341if ~isempty(hh)
342    hhh=findobj(hh,'tag','PLOT');
343    set(hhh,'enable','off')
344end
345%delete the bowser if detected
346hh=findobj(allchild(0),'tag','browser');
347if ~isempty(hh)
348    delete(hh)
349end
350
351%------------------------------------------------------------------------
352%--- activated when resizing the GUI view_field
353 function ResizeFcn(gcbo,eventdata,handles)
354%------------------------------------------------------------------------     
355set(handles.uvmat,'Units','pixels')
356size_fig=get(handles.uvmat,'Position');
357ColumnWidth=max(150,0.18*size_fig(3));
358ColumnWidth=min(ColumnWidth,250); % width of the right side display column, between 150 and 250, depending on the fig width
359
360%% position of panel InputFile
361set(handles.InputFile,'Units','pixels')
362pos_InputFile=get(handles.InputFile,'Position');% [lower x lower y width height] for text_display
363pos_InputFile(1)=0;
364pos_InputFile(2)=size_fig(4)-pos_InputFile(4);             % set frame InputFile to the top of the fig
365pos_InputFile(3)=size_fig(3);
366set(handles.InputFile,'Position',pos_InputFile);% [lower x lower y width height] for text_display
367
368%% reset position of text_display and TableDisplay
369% if strcmp(get(handles.TableDisplay,'Visible'),'off')
370    set(handles.text_display,'Units','pixels')
371    pos_1=get(handles.text_display,'Position');% [lower x lower y width height] for text_display
372        pos_1(3)=1.2*ColumnWidth;
373    pos_1(1)=size_fig(3)-pos_1(3);             % set text display to the right of the fig
374    pos_1(2)=size_fig(4)-pos_InputFile(4)-pos_1(4);             % set text display to the top of the fig
375    set(handles.text_display,'Position',pos_1)
376    % reset position of TableDisplay
377% else
378%     set(handles.TableDisplay,'Units','pixels')
379%     pos_1=get(handles.TableDisplay,'Position');
380%     pos_1(3)=1.2*ColumnWidth;
381%     pos_1(1)=size_fig(3)-pos_1(3);
382%     pos_1(2)=size_fig(4)-pos_InputFile(4)-pos_1(4);
383    set(handles.TableDisplay,'Position',pos_1)
384    % reset position of CheckTable
385    set(handles.CheckTable,'Unit','pixels')
386pos_CheckTable=get(handles.CheckTable,'Position');% [lower x lower y width height] for CheckHold
387pos_CheckTable(1)=pos_1(1)-pos_CheckTable(3);       % set 'CheckHold' to the right of the fig
388pos_CheckTable(2)=pos_InputFile(2)-pos_CheckTable(4);          % set 'CheckHold' to the lower edge of text display
389set(handles.CheckTable,'Position',pos_CheckTable)
390% end
391
392%% reset position of CheckHold
393% pos_CheckHold=get(handles.CheckHold,'Position');% [lower x lower y width height] for CheckHold
394% pos_CheckHold(1)=size_fig(3)-pos_CheckHold(3);       % set 'CheckHold' to the right of the fig
395% pos_CheckHold(2)=pos_1(2)-pos_CheckHold(4);          % set 'CheckHold' to the lower edge of text display
396% set(handles.CheckHold,'Position',pos_CheckHold)
397
398%% reset position of Coordinates
399set(handles.Coordinates,'Units','pixels')
400pos_2=get(handles.Coordinates,'Position');% [lower x lower y width height] for frame 'Coordinates'
401pos_2(3)=ColumnWidth;
402pos_2(1)=size_fig(3)-pos_2(3);       % set 'Coordinates' to the right of the fig
403pos_2(2)=pos_1(2)-pos_2(4);          % set 'Coordinates' to the lower edge of text display, allowing a margin for CheckHold
404set(handles.Coordinates,'Position',pos_2)
405
406%% reset position of  Scalar
407set(handles.Scalar,'Units','pixels')
408pos_3=get(handles.Scalar,'Position'); % [lower x lower y width height] for frame 'Scalar'
409pos_3(3)=ColumnWidth;
410pos_3(1)=size_fig(3)-pos_3(3);         % set 'Scalar' to the right of the fig
411if strcmp(get(handles.Scalar,'Visible'),'on')
412    pos_3(2)=pos_2(2)-pos_3(4); % set 'Scalar' to the lower edge of frame 'Coordinates' if visible
413else
414    pos_3(2)=pos_2(2);% set 'Scalar' to the lower edge of frame 'text display' if  unvisible
415end
416set(handles.Scalar,'Position',pos_3)
417
418%% reset position of  Vectors
419set(handles.Vectors,'Units','pixels')
420pos_4=get(handles.Vectors,'Position');
421pos_4(3)=ColumnWidth;
422pos_4(1)=size_fig(3)-pos_4(3);
423if strcmp(get(handles.Vectors,'visible'),'on')
424    pos_4(2)=pos_3(2)-pos_4(4);
425else
426    pos_4(2)=pos_3(2);
427end
428set(handles.Vectors,'Position',pos_4)
429
430%% reset position and scale of axis
431pos(1)=0.2*size_fig(3)+35;
432pos(2)=35;
433pos(3)=0.77*size_fig(3)-1.2*ColumnWidth;
434pos(4)=size_fig(4)-60;
435set(handles.PlotAxes,'Units','pixels')
436set(handles.PlotAxes,'Position',pos)
437set(handles.PlotAxes,'Units','normalized')
438
439
440%------------------------------------------------------------------------
441%------------------------------------------------------------------------
442%  II - FUNCTIONS FOR INTRODUCING THE INPUT FILES
443% automatically sets the global properties when the rootfile name is introduced
444% then activate the view-field action if selected
445% it is activated either by clicking on the RootPath window or by the
446% browser
447%------------------------------------------------------------------------
448%------------------------------------------------------------------------
449% --- Executes on the menu Open/Browse...
450% search the files, recognize their type according to their name and fill the rootfile input windows
451function MenuBrowse_Callback(hObject, eventdata, handles)
452[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
453oldfile=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
454if isempty(oldfile) %loads the previously stored file name and set it as default in the file_input box
455    oldfile=get(handles.RootPath,'UserData');
456end
457fileinput=uigetfile_uvmat('pick an input file',oldfile);
458hh=dir(fileinput);
459if numel(hh)>1
460    msgbox_uvmat('ERROR','invalid input, probably a broken link');
461else
462
463    %% display the selected field and related information
464    if ~isempty(fileinput)
465        set(handles.SubField,'Value',0)
466        desable_subfield(handles)
467        display_file_name(handles,fileinput)
468    end
469end
470
471% -----------------------------------------------------------------------
472% --- Open again the file whose name has been recorded in MenuFile_1
473function MenuFile_Callback(hObject, eventdata, handles)
474%------------------------------------------------------------------------
475fileinput=get(hObject,'Label');
476set(handles.SubField,'Value',0)
477desable_subfield(handles)
478errormsg=display_file_name( handles,fileinput);
479if ~isempty(errormsg)
480    set(hObject,'Label','')
481    MenuFile=[{get(handles.MenuFile_1,'Label')};{get(handles.MenuFile_2,'Label')};...
482        {get(handles.MenuFile_3,'Label')};{get(handles.MenuFile_4,'Label')};{get(handles.MenuFile_5,'Label')}];
483    str_find=strcmp(get(hObject,'Label'),MenuFile);
484    MenuFile(str_find)=[];% suppress the input file to the list
485    for ifile=1:numel(MenuFile)
486        set(handles.(['MenuFile_' num2str(ifile)]),'Label',MenuFile{ifile});
487    end
488end
489
490% -----------------------------------------------------------------------
491% --- Executes on the menu Open/Browse campaign...
492% --- search the file inside a campaign, using the GUI browse_data
493% -----------------------------------------------------------------------
494function MenuBrowseCampaign_Callback(hObject, eventdata, handles)
495set(handles.MenuOpenCampaign,'ForegroundColor',[1 1 0])
496drawnow
497RootPath=get(handles.RootPath,'String');
498if isempty(RootPath)
499    RootPath=get(handles.RootPath,'UserData');%use Rootpath recored from the personal file at uvmat opening
500end
501CampaignPath=fileparts(fileparts(RootPath));
502DirFull=uigetfile_uvmat('define this path as the Campaign folder:',CampaignPath,'uigetdir');
503%DirFull = uigetdir(CampaignPath,'Select a Campaign dir, then press OK');
504if isempty(DirFull)
505    return
506end
507OutPut=browse_data(DirFull);% open the GUI browse_data to get select a campaign dir, experiment and device
508if ~isfield(OutPut,'Campaign')
509    return
510end
511fileinput=uigetfile_uvmat('pick an input file',fullfile(OutPut.Campaign,OutPut.Experiment{1},OutPut.DataSeries{1}));
512hh=dir(fileinput);
513if numel(hh)>1
514    msgbox_uvmat('ERROR','invalid input, probably a broken link');
515    return
516end
517
518%
519% DirName=fullfile(OutPut.Campaign,OutPut.Experiment{1},OutPut.DataSeries{1});
520% ListStruct=dir(DirName); %list files and the dir DataSeries
521% % select the first appropriate file in the dir
522% FileName='';
523% for ilist=1:numel(ListStruct)
524%     if ~isequal(ListStruct(ilist).isdir,1)%look for files, not dir
525%         FileName=ListStruct(ilist).name;
526%         FileType=get_file_type(fullfile(DirName,FileName));
527%         switch FileType
528%             case {'image','multimage','civx','civdata','netcdf'}
529%                 break
530%         end
531%     end
532% end
533% if isempty(FileName)
534%     msgbox_uvmat('ERROR',['no appropriate input file in the DataSeries folder ' fullfile(DirName)])
535%     return
536% end
537
538%% update the list of campaigns in the menubar
539MenuCampaign=[{get(handles.MenuCampaign_1,'Label')};{get(handles.MenuCampaign_2,'Label')};...
540    {get(handles.MenuCampaign_3,'Label')};{get(handles.MenuCampaign_4,'Label')};{get(handles.MenuCampaign_5,'Label')}];
541check_dir=isempty(find(strcmp(DirFull,MenuCampaign)));
542if check_dir %insert the new campaign in the list if it is not found
543    MenuCampaign(end)=[]; %suppress the last item
544    MenuCampaign=[{DirFull};MenuCampaign];%insert the new campaign
545    for ilist=1:numel(MenuCampaign)
546        set(handles.(['MenuCampaign_' num2str(ilist)]),'Label',MenuCampaign{ilist})
547    end
548    % save the list for future opening:
549    dir_perso=prefdir;
550    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
551    if exist(profil_perso,'file')
552        save (profil_perso,'MenuCampaign','RootPath','-append'); %store the file names for future opening of uvmat
553    else
554        save (profil_perso,'MenuCampaign','RootPath','-V6'); %store the file names for future opening of uvmat
555    end
556end
557
558%% display the selected field and related information
559%display_file_name( handles,fullfile(DirName,FileName))
560display_file_name( handles,fileinput)
561set(handles.MenuOpenCampaign,'ForegroundColor',[0 0 0])
562
563% -----------------------------------------------------------------------
564% --- Open again as second field the file whose name has been recorded in MenuFile_1
565% -----------------------------------------------------------------------
566function MenuCampaign_Callback(hObject, eventdata, handles)
567
568set(handles.MenuOpenCampaign,'ForegroundColor',[1 1 0])
569OutPut=browse_data(get(hObject,'Label'));% open the GUI browse_data to get select a campaign dir, experiment and device
570if ~isfield(OutPut,'Campaign')
571    return
572end
573DirName=fullfile(OutPut.Campaign,OutPut.Experiment{1},OutPut.DataSeries{1});
574fileinput=uigetfile_uvmat('pick an input file',fullfile(OutPut.Campaign,OutPut.Experiment{1},OutPut.DataSeries{1}));
575hh=dir(fileinput);
576if numel(hh)>1
577    msgbox_uvmat('ERROR','invalid input, probably a broken link');
578    return
579end
580%
581% hdir=dir(DirName); %list files and dirs
582% FileName='';
583% for ilist=1:numel(hdir)
584%     if ~isequal(hdir(ilist).isdir,1)%look for files, not dir
585%         FileName=hdir(ilist).name;
586%         FileType=get_file_type(fullfile(DirName,FileName));
587%         switch FileType
588%             case {'image','multimage','civx','civdata','netcdf'}
589%             break
590%         end
591%     end
592% end
593% if isempty(FileName)
594%     msgbox_uvmat('ERROR','no valid input file in the selected directory')
595% else
596display_file_name(handles,fileinput)
597% end
598set(handles.MenuOpenCampaign,'ForegroundColor',[0 0 0])
599
600%------------------------------------------------------------------------
601% --- Called by action in FileIndex edit box
602function FileIndex_Callback(hObject, eventdata, handles)
603%------------------------------------------------------------------------
604[tild,tild,tild,i1,i2,j1,j2]=fileparts_uvmat(get(handles.FileIndex,'String'));
605set(handles.i1,'String',num2str(i1));
606set(handles.i2,'String',num2str(i2));
607set(handles.j1,'String',num2str(j1));
608set(handles.j2,'String',num2str(j2));
609
610
611%------------------------------------------------------------------------
612% --- Called by action in NomType edit box
613function NomType_Callback(hObject, eventdata, handles)
614%------------------------------------------------------------------------
615i1=str2num(get(handles.i1,'String'));
616i2=str2num(get(handles.i2,'String'));
617j1=str2num(get(handles.j1,'String'));
618j2=str2num(get(handles.j2,'String'));
619FileIndex=fullfile_uvmat('','','','',get(handles.NomType,'String'),i1,i2,j1,j2);
620set(handles.FileIndex,'String',FileIndex)
621% inputfilerefresh the current settings and inputfilerefresh the field view
622RootPath_Callback(hObject,eventdata,handles)
623
624%------------------------------------------------------------------------
625% --- Called by action in NomType edit box
626function NomType_1_Callback(hObject, eventdata, handles)
627%------------------------------------------------------------------------
628i1=str2num(get(handles.i1,'String'));
629i2=str2num(get(handles.i2,'String'));
630j1=str2num(get(handles.j1,'String'));
631j2=str2num(get(handles.j2,'String'));
632FileIndex=fullfile_uvmat('','','','',get(handles.NomType_1,'String'),i1,i2,j1,j2);
633set(handles.FileIndex_1,'String',FileIndex)
634% inputfilerefresh the current settings and inputfilerefresh the field view
635RootPath_1_Callback(hObject,eventdata,handles)
636
637%------------------------------------------------------------------------
638% --- Executes on button press in InputFileREFRESH.
639function InputFileREFRESH_Callback(hObject, eventdata, handles)
640%------------------------------------------------------------------------   
641set(handles.InputFileREFRESH,'BackgroundColor',[1 1 0])% set button color to yellow to indicate that refresh is under action
642set(handles.uvmat,'Pointer','watch') % set the mouse pointer to 'watch'
643drawnow
644% read the current input file name:
645[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
646% if ~exist(fullfile(RootPath,SubDir),'dir')
647%     msgbox_uvmat('ERROR',['directory ' fullfile(RootPath,SubDir) ' does not exist'])
648%     return
649% end
650% detect the file type, get the movie object if relevant, and look for the corresponding file series:
651[RootPath,SubDir,RootFile,i1_series,i2_series,j1_series,j2_series,tild,FileType,FileInfo,MovieObject]=find_file_series(fullfile(RootPath,SubDir),[RootFile FileIndices FileExt]);
652% initiate the input file series and inputfilerefresh the current field view:
653errormsg=update_rootinfo(handles,i1_series,i2_series,j1_series,j2_series,FileType,MovieObject,1);
654% inputfilerefresh the second series if selected
655if get(handles.SubField,'Value')
656    [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes_1(handles);
657    if ~exist(fullfile(RootPath,SubDir),'dir')
658        msgbox_uvmat('ERROR',['directory ' fullfile(RootPath,SubDir) ' does not exist'])
659        return
660    end
661    % detect the file type, get the movie object if relevant, and look for the corresponding file series:
662    [RootPath,SubDir,RootFile,i1_series,i2_series,j1_series,j2_series,tild,FileType,MovieObject]=find_file_series(fullfile(RootPath,SubDir),[RootFile FileIndices FileExt]);
663    % initiate the input file series and inputfilerefresh the current field view:
664    errormsg=update_rootinfo(handles,i1_series,i2_series,j1_series,j2_series,FileType,MovieObject,2);
665end
666
667if isempty(errormsg)
668% set(handles.InputFileREFRESH,'BackgroundColor',[1 0 0])% set button color to red to indicate that refresh has been updated
669else
670    set(handles.InputFileREFRESH,'BackgroundColor',[1 0 1])% keep button color magenta, input not succesfull
671end
672set(handles.uvmat,'Pointer','arrow')% set back the mouse pointer to arrow
673
674%------------------------------------------------------------------------
675% --- Fills the edit boxes RootPath, RootFile,NomType...from an input file name 'fileinput'
676function errormsg=display_file_name(handles,fileinput,index)
677%------------------------------------------------------------------------
678%% look for the input file existence
679errormsg='';%default
680if ~exist(fileinput,'file')
681    errormsg=['input file ' fileinput  ' does not exist'];
682    msgbox_uvmat('ERROR',errormsg)
683    return
684end
685
686%% define the relevant handles for the first field series (index=1) or the second file series (index=2)
687if ~exist('index','var')
688    index=1;
689end
690if index==1
691    handles_RootPath=handles.RootPath;
692    handles_SubDir=handles.SubDir;
693    handles_RootFile=handles.RootFile;
694    handles_FileIndex=handles.FileIndex;
695    handles_NomType=handles.NomType;
696    handles_FileExt=handles.FileExt;
697elseif index==2
698    handles_RootPath=handles.RootPath_1;
699    handles_SubDir=handles.SubDir_1;
700    handles_RootFile=handles.RootFile_1;
701    handles_FileIndex=handles.FileIndex_1;
702    handles_NomType=handles.NomType_1;
703    handles_FileExt=handles.FileExt_1;
704    set(handles.RootPath_1,'Visible','on')
705    set(handles.RootFile_1,'Visible','on')
706    set(handles.SubDir_1,'Visible','on');
707    set(handles.FileIndex_1,'Visible','on');
708    set(handles.FileExt_1,'Visible','on');
709    set(handles.NomType_1,'Visible','on');
710    set(handles.TimeName_1,'Visible','on')
711    set(handles.TimeValue_1,'Visible','on')
712end
713set(handles.InputFileREFRESH,'BackgroundColor',[1 1 0])% paint REFRESH button to yellow to visualise root file input
714set(handles.uvmat,'Pointer','watch') % set the mouse pointer to 'watch'
715drawnow
716
717%% detect root name, nomenclature and indices in the input file name:
718[FilePath,FileName,FileExt]=fileparts(fileinput);
719% detect the file type, get the movie object if relevant, and look for the corresponding file series:
720% the root name and indices may be corrected by including the first index i1 if a corresponding xml file exists
721[RootPath,SubDir,RootFile,i1_series,i2_series,j1_series,j2_series,NomType,FileType,FileInfo,MovieObject,i1,i2,j1,j2]=find_file_series(FilePath,[FileName FileExt]);
722
723if strcmp(FileType,'txt')
724    try
725        edit(fileinput)
726    catch ME
727        msgbox_uvmat('ERROR','invalid intput file')
728    end
729    return
730elseif strcmp(FileType,'xml')
731    editxml(fileinput)
732     return
733elseif strcmp(FileType,'figure')
734    open(fileinput)
735     return
736end
737
738%% open the file or fill the GUI uvmat according to the detected file type
739switch FileType
740    case ''
741        msgbox_uvmat('ERROR','invalid input file type')
742    case 'txt'
743        edit(fileinput)
744    case 'figure'                           %display matlab figure
745        hfig=open(fileinput);
746        set(hfig,'WindowButtonMotionFcn','mouse_motion')%set mouse action functio
747        set(hfig,'WindowButtonUpFcn','mouse_up')%set mouse click action function
748        set(hfig,'WindowButtonUpFcn','mouse_down')%set mouse click action function
749    case 'xml'                % edit xml files
750        t=xmltree(fileinput);
751        % the xml file marks a project or project link, open datatree_browser
752        if strcmp(get(t,1,'name'),'Project')&& exist(regexprep(fileinput,'.xml$',''),'dir')
753            datatree_browser(fileinput)
754        else % other xml file, open the xml editor
755            editxml(fileinput);
756        end
757    case 'xls'% Excel file opended by editxml
758        editxml(fileinput);
759    otherwise
760        set(handles_RootPath,'String',RootPath);
761        rootname=fullfile(RootPath,SubDir,RootFile);
762        set(handles_SubDir,'String',['/' SubDir]);
763        set(handles_RootFile,'String',['/' RootFile]); %display the separator
764        indices=fileinput(length(rootname)+1:end);
765        indices(end-length(FileExt)+1:end)=[]; %remove extension
766        set(handles_FileIndex,'String',indices);
767        set(handles_NomType,'String',NomType);
768        set(handles_FileExt,'String',FileExt);
769        if index==1
770            % fill file index counters if the first file series is opened
771            set(handles.i1,'String',num2str(i1));
772            set(handles.i2,'String',num2str(i2));
773            set(handles.j1,'String',num2stra(j1,NomType));
774            set(handles.j2,'String',num2stra(j2,NomType));
775        else %read the current field index to synchronise with the first series
776            i1_s=str2num(get(handles.i1,'String'));
777            i2_0=str2num(get(handles.i2,'String'));
778            if ~isempty(i2_0)
779                i2_s=i2_0;
780            else
781               i2_s=i2;
782            end
783            j1_0=stra2num(get(handles.j1,'String'));
784            if ~isempty(j1_0)
785                j1_s=j1_0;
786            else
787                j1_s=j1;
788            end
789            j2_0=stra2num(get(handles.j2,'String'));
790            if ~isempty(j2_0)
791                j2_s=j2_0;
792            else
793                j2_s=j2;
794            end
795        end
796       
797        % synchronise indices of the second  input file if it exists
798        if get(handles.SubField,'Value')==1% if the subfield button is activated, update the field numbers
799            Input=read_GUI(handles.InputFile);
800            if ~isfield(Input,'RootPath_1')||strcmp(Input.RootPath_1,'"')
801                Input.RootPath_1=Input.RootPath;
802            end
803            if ~isfield(Input,'SubDir_1')||strcmp(Input.SubDir_1,'"')
804                Input.SubDir_1=Input.SubDir;
805            end
806            if ~isfield(Input,'RootFile_1')||strcmp(Input.RootFile_1,'"')
807                Input.RootFile_1=Input.RootFile;
808            end
809            if ~isfield(Input,'FileExt_1')||strcmp(Input.FileExt_1,'"')
810                Input.FileExt_1=Input.FileExt;
811            end
812            if ~isfield(Input,'NomType_1')||strcmp(Input.NomType_1,'"')
813                Input.NomType_1=Input.NomType;
814            end
815            %updtate the indices of the second field series to correspond to the newly opened one
816            FileName_1=fullfile_uvmat(Input.RootPath_1,Input.SubDir_1,Input.RootFile_1,Input.FileExt_1,Input.NomType_1,i1_s,i2_s,j1_s,j2_s);
817            if exist(FileName_1,'file')
818                FileIndex_1=fullfile_uvmat('','','','',Input.NomType_1,i1_s,i2_s,j1_s,j2_s);
819            else
820                FileIndex_1=fullfile_uvmat('','','','',Input.NomType_1,i1,i2,j1,j2);
821                msgbox_uvmat('WARNING','unable to synchronise the indices of the two series')
822            end
823            set(handles.FileIndex_1,'String',FileIndex_1)
824        end
825       
826        %enable other menus
827        set(handles.MenuOpenCampaign,'Enable','on')
828        set(handles.MenuExport,'Enable','on')
829        set(handles.MenuExportFigure,'Enable','on')
830        set(handles.MenuExportMovie,'Enable','on')
831        set(handles.MenuTools,'Enable','on')
832
833        % initiate input file series and inputfilerefresh the current field view:     
834        update_rootinfo(handles,i1_series,i2_series,j1_series,j2_series,FileType,MovieObject,index);
835
836end
837
838%% update list of recent files in the menubar and save it for future opening
839MenuFile=[{get(handles.MenuFile_1,'Label')};{get(handles.MenuFile_2,'Label')};...
840    {get(handles.MenuFile_3,'Label')};{get(handles.MenuFile_4,'Label')};{get(handles.MenuFile_5,'Label')}];
841str_find=strcmp(fileinput,MenuFile);
842if isempty(find(str_find,1))
843    MenuFile=[{fileinput};MenuFile];%insert the current file if not already in the list
844end
845for ifile=1:min(length(MenuFile),5)
846    set(handles.(['MenuFile_' num2str(ifile)]),'Label',MenuFile{ifile});
847    %set(handles.(['MenuFile_' num2str(ifile) '_1']),'Label',MenuFile{ifile});
848end
849dir_perso=prefdir;
850profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
851if exist(profil_perso,'file')
852    save (profil_perso,'MenuFile','RootPath','-append'); %store the file names for future opening of uvmat
853else
854    save (profil_perso,'MenuFile','RootPath','-V6'); %store the file names for future opening of uvmat
855end
856
857set(handles.InputFileREFRESH,'BackgroundColor',[1 0 0])% paint back button to red to indicate update is finished
858set(handles.uvmat,'Pointer','arrow')% set back the mouse pointer to arrow
859
860
861%------------------------------------------------------------------------
862% --- Update information about a new field series (indices to scan, timing,
863%     calibration from an xml file, then inputfilerefresh current plots
864function errormsg=update_rootinfo(handles,i1_series,i2_series,j1_series,j2_series,FileType,VideoObject,index)
865%------------------------------------------------------------------------
866errormsg=''; %default error msg
867%% define the relevant handles depending on the index (1=first file series, 2= second file series)
868if ~exist('index','var')
869    index=1;
870end
871if index==1
872    handles_Fields=handles.FieldName;
873elseif index==2
874    handles_Fields=handles.FieldName_1;
875end
876
877set(handles.FieldName,'UserData',[])% reinialize data from uvmat opening
878UvData=get(handles.uvmat,'UserData');%huvmat=handles of the uvmat interface
879UvData.NewSeries=1; %flag for REFRESH: begin a new series
880UvData.FileName_1='';% name of the current second field (used to detect a  constant field during file scanning)
881UvData.FileType{index}=FileType;
882UvData.i1_series{index}=i1_series;
883UvData.i2_series{index}=i2_series;
884UvData.j1_series{index}=j1_series;
885UvData.j2_series{index}=j2_series;
886set(handles.FixVelType,'Value',0); %desactivate fixed veltype
887if index==1
888    [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
889else
890    [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes_1(handles);
891end
892FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
893FileBase=fullfile(RootPath,RootFile);
894if ~exist(FileName,'file')
895    errormsg=['input file ' FileName ' not found'];
896   msgbox_uvmat('ERROR',errormsg);   
897    return
898end
899
900%% read timing and total frame number from the current file (movie files) !! may be overrid by xml file
901TimeUnit='';%default
902TimeName='';%default
903XmlData.Time=[];%default
904imainfo=[];
905ColorType='falsecolor'; %default
906UvData.MovieObject{index}=VideoObject;
907if ~isempty(VideoObject)% case of video data
908    imainfo=get(VideoObject);
909    TimeUnit='s';
910    if isempty(j1_series); %frame index along i
911        XmlData.Time=zeros(imainfo.NumberOfFrames+1,2);
912        XmlData.Time(:,2)=(0:1/imainfo.FrameRate:(imainfo.NumberOfFrames)/imainfo.FrameRate)';
913    else
914        XmlData.Time=[0;ones(size(i1_series,3)-1,1)]*(0:1/imainfo.FrameRate:(imainfo.NumberOfFrames)/imainfo.FrameRate);
915    end
916    %set(handles.Dt_txt,'String',['Dt=' num2str(1000/imainfo.FrameRate) 'ms']);%display the elementary time interval in millisec
917    TimeName='video';
918    ColorType='truecolor';
919elseif ~isempty(FileExt(2:end))&&(~isempty(imformats(FileExt(2:end))) || isequal(FileExt,'.vol'))%&& isequal(NomType,'*')% multi-frame image
920    if ~isequal(SubDir,'')
921        imainfo=imfinfo([fullfile(RootPath,SubDir,RootFile) FileIndices FileExt]);
922    else
923        imainfo=imfinfo([FileBase FileIndices FileExt]);
924    end
925    ColorType=imainfo.ColorType;%='truecolor' for color images
926end
927if isfield(imainfo,'Width') && isfield(imainfo,'Height')
928    if length(imainfo)>1
929        set(handles.num_Npx,'String',num2str(imainfo(1).Width));%fills nbre of pixels x box
930        set(handles.num_Npy,'String',num2str(imainfo(1).Height));%fills nbre of pixels x box
931    else
932        set(handles.num_Npx,'String',num2str(imainfo.Width));%fills nbre of pixels x box
933        set(handles.num_Npy,'String',num2str(imainfo.Height));%fills nbre of pixels x box
934    end
935else
936    set(handles.num_Npx,'String','');%fills nbre of pixels x box
937    set(handles.num_Npy,'String','');%fills nbre of pixels x box
938end
939set(handles.CheckBW,'Value',strcmp(ColorType,'grayscale'))% select handles.CheckBW if grayscale image
940
941%% read parameters (time, geometric calibration..) from a documentation file (.xml advised)
942XmlData.GeometryCalib=[];%default
943XmlFileName=find_imadoc(RootPath,SubDir,RootFile,FileExt);
944[tild,tild,DocExt]=fileparts(XmlFileName);
945warntext='';%default warning message
946NbSlice=1;%default
947ImaDoc_str='';
948if ~isempty(XmlFileName)
949    set(handles.view_xml,'Visible','on')
950    set(handles.view_xml,'BackgroundColor',[1 1 0])% paint  to yellow color to indicate reading of the xml file
951    set(handles.view_xml,'String','view .xml')
952    drawnow
953    [XmlDataRead,warntext]=imadoc2struct(XmlFileName);
954    if ~isempty(warntext)
955        msgbox_uvmat('WARNING',warntext)
956    end
957    if ~isempty(XmlDataRead)
958        ImaDoc_str=['view ' DocExt];  % DocExt= '.xml' or .civ (obsolete case)
959        %XmlData=XmlDataRead;
960        if isfield(XmlDataRead,'TimeUnit')&& ~isempty(XmlDataRead.TimeUnit)
961            TimeUnit=XmlDataRead.TimeUnit;
962        end
963        if isfield(XmlDataRead,'Time')&& ~isempty(XmlDataRead.Time)
964            XmlData.Time=XmlDataRead.Time;
965        end
966        set(handles.view_xml,'BackgroundColor',[1 1 1])% paint back to white
967        drawnow
968        if isfield(XmlDataRead, 'GeometryCalib') && ~isempty(XmlDataRead.GeometryCalib)
969            XmlData.GeometryCalib=XmlDataRead.GeometryCalib;
970            if isfield(XmlData.GeometryCalib,'CheckVolumeScan') && isequal(XmlData.GeometryCalib.CheckVolumeScan,1)
971                set (handles.slices,'String','volume')
972            end
973            % check whether the GUI geometry_calib is opened
974            hgeometry_calib=findobj('tag','geometry_calib');
975            if ~isempty(hgeometry_calib) % check whether the display of the GUI geometry_calib is consistent with the current calib param
976                GUserData=get(hgeometry_calib,'UserData');
977                if ~(isfield(GUserData,'XmlInputFile') && strcmp(GUserData.XmlInputFile,XmlFileName))
978                    answer=msgbox_uvmat('INPUT_Y-N','refresh the display of the GUI geometry_calib with the new input data?');
979                    if strcmp(answer,'Yes')
980                        geometry_calib(XmlFileName);%diplay the new calibration points and parameters in geometry_calib
981                    end
982                end
983            end
984        end
985    end
986end
987if isempty(ImaDoc_str)
988    set(handles.view_xml,'Visible','off') % no .xml (or .civ) file detected
989else
990    set(handles.view_xml,'String',ImaDoc_str)% indicate that a xml file has been detected
991end
992
993%% Define timing
994% time not set by the input file: images or civ data: indicate that time is read from the xml file
995if isfield(XmlData,'Time')&& ~isempty(XmlData.Time) && ...
996        (strcmp(FileType,'image')|| strcmp(FileType,'multimage')||strcmp(FileType,'civdata')||strcmp(FileType,'civx'))
997    TimeName='xml';
998elseif strcmp(FileType,'civdata')
999    TimeName='civdata';
1000elseif strcmp(FileType,'civx')
1001    TimeName='civx';
1002end
1003if index==1
1004    set(handles.TimeName,'String',TimeName)
1005else
1006    set(handles.TimeName_1,'String',TimeName)
1007    set(handles.TimeName_1,'Visible','on')
1008end
1009
1010%% store last index in handles.MaxIndex_i and .MaxIndex_j
1011nbfield=max(max(max(i2_series)));
1012if isempty(nbfield)
1013    nbfield=max(max(max(i1_series)));
1014end
1015nbfield_j=max(max(max(j2_series)));
1016if isempty(nbfield_j)
1017    nbfield_j=max(max(max(j1_series)));
1018end
1019if isfield(XmlData,'Time')&& ~isempty(XmlData.Time)
1020    %transform .Time to a column vector if it is a line vector the nomenclature uses a single index
1021    if isequal(size(XmlData.Time,1),1)
1022        XmlData.Time=(XmlData.Time)';
1023    end
1024end
1025last_i_cell=get(handles.MaxIndex_i,'String');
1026if isempty(nbfield)
1027    last_i_cell{index}='';
1028else
1029    last_i_cell{index}=num2str(nbfield);
1030end
1031set(handles.MaxIndex_i,'String',last_i_cell)
1032last_j_cell=get(handles.MaxIndex_j,'String');
1033if isempty(nbfield_j)
1034     last_j_cell{index}='';
1035else
1036     last_j_cell{index}=num2str(nbfield_j);
1037end
1038set(handles.MaxIndex_j,'String',last_j_cell);
1039
1040%% store geometric calibration in UvData
1041if isfield(XmlData,'GeometryCalib')
1042    GeometryCalib=XmlData.GeometryCalib;
1043    if isempty(GeometryCalib)
1044        set(handles.pxcmx,'String','')
1045        set(handles.pxcmy,'String','')
1046        set(handles.pxcmx,'Visible','off')
1047        set(handles.pxcmy,'Visible','off')
1048        set(handles.TransformName,'Value',1); %  no transform by default
1049    else
1050        set(handles.pxcmx,'Visible','on')
1051        set(handles.pxcmy,'Visible','on')
1052        if (isfield(GeometryCalib,'R')&& ~isequal(GeometryCalib.R(2,1),0) && ~isequal(GeometryCalib.R(1,2),0)) ||...
1053            (isfield(GeometryCalib,'kappa1')&& ~isequal(GeometryCalib.kappa1,0))
1054            set(handles.pxcmx,'String','var')
1055            set(handles.pxcmy,'String','var')
1056        elseif isfield(GeometryCalib,'fx_fy')
1057            pixcmx=GeometryCalib.fx_fy(1);%*GeometryCalib.R(1,1)*GeometryCalib.sx/(GeometryCalib.Tz*GeometryCalib.dpx);
1058            pixcmy=GeometryCalib.fx_fy(2);%*GeometryCalib.R(2,2)/(GeometryCalib.Tz*GeometryCalib.dpy);
1059            set(handles.pxcmx,'String',num2str(pixcmx))
1060            set(handles.pxcmy,'String',num2str(pixcmy))
1061        end
1062        if ~get(handles.CheckFixLimits,'Value')
1063            set(handles.TransformName,'Value',3); % phys transform by default if fixedLimits is off
1064        end
1065        if isfield(GeometryCalib,'SliceCoord')           
1066           siz=size(GeometryCalib.SliceCoord);
1067           if siz(1)>1
1068               NbSlice=siz(1);
1069               set(handles.slices,'Visible','on')
1070               set(handles.slices,'Value',1)
1071           end
1072           if isfield(GeometryCalib,'CheckVolumeScan') && isequal(GeometryCalib.CheckVolumeScan,1)
1073               set(handles.num_NbSlice,'Visible','off')
1074           else
1075               set(handles.num_NbSlice,'Visible','on')
1076               set(handles.num_NbSlice,'String',num2str(NbSlice))
1077           end
1078           slices_Callback([],[], handles)
1079        end           
1080    end
1081end
1082
1083%% update the data attached to the uvmat interface
1084if ~isempty(TimeUnit)
1085    if index==2 && isfield(UvData,'TimeUnit') && ~strcmp(UvData.TimeUnit,TimeUnit)
1086        msgbox_uvmat('WARNING',['time unit for second file series ' TimeUnit ' inconsistent with first series'])
1087    else
1088        UvData.TimeUnit=TimeUnit;
1089    end
1090end
1091UvData.XmlData{index}=XmlData;
1092UvData.NewSeries=1;
1093
1094%display warning message
1095if ~isequal(warntext,'')
1096    msgbox_uvmat('WARNING',warntext);
1097end
1098
1099%% set default options in menu 'FieldName'
1100switch FileType
1101    case {'civx','civdata'}
1102        [FieldList,ColorList]=set_field_list('U','V','C');
1103        set(handles_Fields,'String',[{'image'};FieldList;{'get_field...'}]);%standard menu for civx data
1104        set(handles_Fields,'Value',2) % set menu to 'velocity
1105        if index==1
1106            set(handles.FieldName_1,'Value',1);
1107            set(handles.FieldName_1,'String',[{''};{'image'};FieldList;{'get_field...'}]);%standard menu for civx data reproduced for the second field
1108        end
1109        set(handles.ColorScalar,'Value',1)
1110        set(handles.ColorScalar,'String',ColorList)
1111        set(handles.Vectors,'Visible','on')
1112        set(handles.Coord_x,'Value',1);
1113        set(handles.Coord_x,'String','X');
1114%         set(handles.Coord_y,'Value',1);
1115        set(handles.Coord_y,'Data',{'Y'});
1116    case 'netcdf'
1117        set(handles_Fields,'Value',1)
1118        set(handles_Fields,'String',{'get_field...'})
1119        if index==1
1120            FieldName_Callback([],[], handles)
1121        else
1122            FieldName_1_Callback([],[], handles)
1123        end
1124    otherwise
1125        set(handles_Fields,'Value',1) % set menu to 'image'
1126        set(handles_Fields,'String',{'image'})
1127        set(handles.Coord_x,'Value',1);
1128        set(handles.Coord_x,'String','AX');
1129    set(handles.Coord_y,'Data',{'AY'});
1130end
1131set(handles.uvmat,'UserData',UvData)
1132
1133%% set index navigation options and inputfilerefresh plots
1134scan_option='i';%default
1135state_j='off'; %default
1136if index==2
1137    if get(handles.scan_j,'Value')
1138        scan_option='j'; %keep the scan option for the second file series
1139    end
1140    if strcmp(get(handles.j1,'Visible'),'on')
1141        state_j='on';
1142    end
1143end
1144[ref_j,ref_i]=find(squeeze(i1_series(1,:,:)));
1145if ~isempty(j1_series)
1146        state_j='on';
1147        if index==1
1148            if isequal(ref_i,ref_i(1)*ones(size(ref_j)))% if ref_i is always equal to its first value
1149                scan_option='j'; %scan j indext               
1150            end
1151        end
1152end
1153if isequal(scan_option,'i')
1154    diff_ref_i=diff(ref_i,1);
1155    if isempty(diff_ref_i)
1156        diff_ref_i=1;
1157    end
1158    if isequal (diff_ref_i,diff_ref_i(1)*ones(size(diff_ref_i)))
1159        set(handles.num_IndexIncrement,'String',num2str(diff_ref_i(1)))
1160    end
1161     set(handles.scan_i,'Value',1)
1162     scan_i_Callback([],[], handles);
1163else
1164    diff_ref_j=diff(ref_j);
1165    if isempty(diff_ref_j)
1166        diff_ref_j=1;
1167    end
1168    if isequal (diff_ref_j,diff_ref_j(1)*ones(size(diff_ref_j)))
1169        set(handles.num_IndexIncrement,'String',num2str(diff_ref_j(1)))
1170    end
1171     set(handles.scan_j,'Value',1)
1172     scan_j_Callback([],[], handles);
1173end
1174set(handles.scan_j,'Visible',state_j)
1175set(handles.j1,'Visible',state_j)
1176set(handles.j2,'Visible',state_j)
1177set(handles.MaxIndex_j,'Visible',state_j);
1178set(handles.j_text,'Visible',state_j);
1179if ~isempty(i2_series)||~isempty(j2_series)
1180    set(handles.CheckFixPair,'Visible','on')
1181elseif index==1
1182    set(handles.CheckFixPair,'Visible','off')
1183end
1184
1185%% apply the effect of the transform fct and view the field 
1186transform=get(handles.TransformPath,'UserData');
1187if index==2 && (~isa(transform,'function_handle')||nargin(transform)<3)
1188    set(handles.TransformName,'value',2); % set transform to sub_field if the current fct doe not accept two input fields
1189end
1190set(handles.InputFileREFRESH,'BackgroundColor',[1 0 0])% set button color to red to indicate that refresh has been updated
1191TransformName_Callback([],[],handles)% callback for the selection of transform function, then refresh the current plot
1192mask_test=get(handles.CheckMask,'value');
1193if mask_test
1194    MaskData=get(handles.CheckMask,'UserData');
1195    if isfield(MaskData,'maskhandle') && ishandle(MaskData.maskhandle)
1196          delete(MaskData.maskhandle)    %delete old mask
1197    end
1198    CheckMask_Callback([],[],handles)
1199end
1200
1201%------------------------------------------------------------------------
1202% --- switch file index scanning options scan_i and scan_j in an exclusive way
1203%------------------------------------------------------------------------
1204function scan_i_Callback(hObject, eventdata, handles)
1205
1206if get(handles.scan_i,'Value')==1
1207    set(handles.scan_j,'Value',0)
1208else
1209    set(handles.scan_j,'Value',1)
1210end
1211scan_j_Callback(hObject, eventdata, handles)
1212
1213%------------------------------------------------------------------------
1214% --- switch file index scanning options scan_i and scan_j in an exclusive way
1215%------------------------------------------------------------------------
1216function scan_j_Callback(hObject, eventdata, handles)
1217
1218if get(handles.scan_j,'Value')==1
1219    set(handles.scan_i,'Value',0)
1220else
1221    set(handles.scan_i,'Value',1)
1222    set(handles.CheckFixPair,'Visible','off')
1223end
1224
1225%------------------------------------------------------------------------
1226function i1_Callback(hObject, eventdata, handles)
1227%------------------------------------------------------------------------
1228update_ij(handles,1)
1229
1230%------------------------------------------------------------------------
1231function i2_Callback(hObject, eventdata, handles)
1232%------------------------------------------------------------------------
1233update_ij(handles,2)
1234
1235%------------------------------------------------------------------------
1236function j1_Callback(hObject, eventdata, handles)
1237%------------------------------------------------------------------------
1238update_ij(handles,3)
1239
1240%------------------------------------------------------------------------
1241function j2_Callback(hObject, eventdata, handles)
1242%------------------------------------------------------------------------
1243update_ij(handles,4)
1244
1245%------------------------------------------------------------------------
1246%--- update the index display after action on edit boxes i1, i2, j1 or j2
1247%------------------------------------------------------------------------
1248function update_ij(handles,index_rank)
1249   
1250NomType=get(handles.NomType,'String');
1251indices=get(handles.FileIndex,'String');
1252[tild,tild,tild,i1,i2,j1,j2]=fileparts_uvmat(indices);% the indices for the second series taken from FileIndex
1253switch index_rank
1254    case 1
1255        indices=fullfile_uvmat('','','','',NomType,stra2num(get(handles.i1,'String')),i2,j1,j2);
1256        set(handles.i1,'BackgroundColor',[0.7 0.7 0.7])% mark the edit box in grey, then RUN0 will mark it in white for confirmation
1257    case 2
1258        indices=fullfile_uvmat('','','','',NomType,i1,stra2num(get(handles.i2,'String')),j1,j2);
1259        set(handles.i2,'BackgroundColor',[0.7 0.7 0.7])% mark the edit box in grey, then RUN0 will mark it in white for confirmation
1260    case 3
1261        indices=fullfile_uvmat('','','','',NomType,i1,i2,stra2num(get(handles.j1,'String')),j2);
1262        set(handles.j1,'BackgroundColor',[0.7 0.7 0.7])% mark the edit box in grey, then RUN0 will mark it in white for confirmation
1263    case 4
1264        indices=fullfile_uvmat('','','','',NomType,i1,i2,j1,stra2num(get(handles.j2,'String')));
1265        set(handles.j2,'BackgroundColor',[0.7 0.7 0.7])% mark the edit box in grey, then RUN0 will mark it in white for confirmation
1266end
1267set(handles.FileIndex,'String',indices)
1268set(handles.FileIndex,'BackgroundColor',[0.7 0.7 0.7])% mark the edit box in grey, then RUN0 will mark it in white for confirmation
1269% update the second index if relevant
1270if strcmp(get(handles.FileIndex_1,'Visible'),'on')
1271    NomType_1=get(handles.NomType_1,'String');
1272    indices_1=get(handles.FileIndex_1,'String');
1273    [tild,tild,tild,i1_1,i2_1,j1_1,j2_1]=fileparts_uvmat(indices_1);% the indices for the second series taken from FileIndex_1
1274    switch index_rank
1275        case 1
1276            indices_1=fullfile_uvmat('','','','',NomType_1,stra2num(get(handles.i1,'String')),i2_1,j1_1,j2_1);
1277        case 2
1278            indices_1=fullfile_uvmat('','','','',NomType_1,i1_1,stra2num(get(handles.i2,'String')),j1_1,j2_1);
1279        case 3
1280            indices_1=fullfile_uvmat('','','','',NomType_1,i1_1,i2_1,stra2num(get(handles.j1,'String')),j2_1);
1281        case 4
1282            indices_1=fullfile_uvmat('','','','',NomType_1,i1_1,i2_1,j1_1,stra2num(get(handles.j2,'String')));
1283    end
1284    set(handles.FileIndex_1,'String',indices_1)
1285    set(handles.FileIndex_1,'BackgroundColor',[0.7 0.7 0.7])% mark the edit box in grey, then RUN0 will mark it in white for confirmation
1286end
1287   
1288%------------------------------------------------------------------------
1289
1290%------------------------------------------------------------------------
1291function slices_Callback(hObject, eventdata, handles)
1292%------------------------------------------------------------------------
1293if strcmp(get(handles.slices,'String'),'slices')
1294    if get(handles.slices,'Value')==1
1295        set(handles.num_NbSlice,'Visible','on')
1296        set(handles.z_text,'Visible','on')
1297        set(handles.z_index,'Visible','on')
1298        num_NbSlice_Callback(hObject, eventdata, handles)
1299    else
1300        set(handles.num_NbSlice,'Visible','off')
1301        set(handles.z_text,'Visible','off')
1302        set(handles.z_index,'Visible','off')
1303        set(handles.masklevel,'Value',1)
1304        set(handles.masklevel,'String',{'1'})
1305    end
1306end
1307
1308%------------------------------------------------------------------------
1309function num_NbSlice_Callback(hObject, eventdata, handles)
1310%------------------------------------------------------------------------
1311mode=get(handles.slices,'String');
1312nb_slice_str=get(handles.num_NbSlice,'String');
1313if strcmp(mode,'volume')
1314    z=stra2num(get(handles.j1,'String'));
1315else
1316    num=str2double(get(handles.i1,'String'));
1317    nbslice=str2double(get(handles.num_NbSlice,'String'));
1318    z=mod(num-1,nbslice)+1;
1319end
1320set(handles.z_index,'String',num2str(z))
1321for ilist=1:nbslice
1322    list_index{ilist,1}=num2str(ilist);
1323end   
1324set(handles.masklevel,'String',list_index)
1325set(handles.masklevel,'Value',z)
1326
1327%------------------------------------------------------------------------
1328% --- Executes on button press in view_xml.
1329%------------------------------------------------------------------------
1330function view_xml_Callback(hObject, eventdata, handles)
1331
1332% if TimeName defined, open the xml file corresponding to the first file
1333% series, else open the xml file corresponding to the second series
1334if isempty(get(handles.TimeName,'String'))% open the xml file corresponding to the secodn file series
1335    [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes_1(handles);
1336else
1337   [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
1338end
1339option=get(handles.view_xml,'String');
1340if isequal(option,'view .xml')     
1341    FileXml=fullfile(RootPath,[SubDir '.xml']);
1342    if ~exist(FileXml,'file')% case of civ files , removes the extension for subdir
1343        FileXml=fullfile(RootPath,[regexprep(SubDir,'\..+$','') '.xml']);
1344    end
1345    heditxml=editxml(FileXml);
1346end
1347
1348%------------------------------------------------------------------------
1349% --- Executes on button press in CheckMask.
1350function CheckMask_Callback(hObject, eventdata, handles)
1351%------------------------------------------------------------------------
1352%case of view mask selection
1353if isequal(get(handles.CheckMask,'Value'),1)
1354    [RootPath,SubDir]=read_file_boxes(handles);
1355    MaskSubDir=regexprep(SubDir,'\..*','');%take the root part of SubDir, before the first dot '.'
1356    MaskPath=fullfile(RootPath,[MaskSubDir '.mask']);
1357    mdetect=0;
1358    if exist(MaskPath,'dir')
1359        ListStruct=dir(MaskPath);%look for a mask file
1360        ListCells=struct2cell(ListStruct);% transform dir struct to a cell arrray
1361        check_dir=cell2mat(ListCells(4,:));% =1 for directories, =0 for files
1362        ListFiles=ListCells(1,:);%list of file and dri names
1363        ListFiles=ListFiles(~check_dir);%list of file names (excluding dir)
1364        if ~isempty(ListFiles)
1365            for ifile=1:numel(ListFiles)
1366                [tild,tild,MaskExt]=fileparts(ListFiles{1});
1367                [tild,tild,MaskFile{ifile},i1_series,i2_series,j1_series,j2_series,MaskNomType,MaskFileType]=find_file_series(MaskPath,ListFiles{ifile},0);
1368                if strcmp(MaskFileType,'image') && isempty(i2_series) && isempty(j2_series)
1369                    mdetect=1;
1370                end
1371                if ~strcmp(MaskFile{ifile},MaskFile{1})
1372                    mdetect=0;% cancel detection test in case of multiple masks, use the brower for selection
1373                    break
1374                end
1375            end
1376        end
1377        RootPath=MaskPath;
1378    end
1379    if mdetect==0
1380        MaskFullName=uigetfile_uvmat('pick a mask image file:',RootPath,'image');
1381        if isempty(MaskFullName)
1382            set(handles.CheckMask,'Value',0)
1383        end
1384        [MaskPath,MaskName,MaskExt]=fileparts(MaskFullName);
1385        [tild,tild,MaskFile,i1_series,i2_series,j1_series,j2_series,MaskNomType]=find_file_series(MaskPath,[MaskName MaskExt],0);
1386        if ~(isempty(i2_series) && isempty(j2_series))
1387            MaskNomType='*';
1388        end
1389    end
1390    Mask.Path=MaskPath;
1391    if isempty(MaskFile)
1392        Mask.File='';
1393    elseif ischar(MaskFile)
1394        Mask.File=MaskFile;
1395    else
1396        Mask.File=MaskFile{1};
1397    end
1398    Mask.Ext=MaskExt;
1399    Mask.NomType=MaskNomType;
1400    set(handles.CheckMask,'UserData',Mask);
1401    errormsg=update_mask(handles);
1402else % desactivate mask display
1403    MaskData=get(handles.CheckMask,'UserData');
1404    if isfield(MaskData,'maskhandle') && ishandle(MaskData.maskhandle)
1405        delete(MaskData.maskhandle)
1406    end
1407    set(handles.CheckMask,'UserData',[])
1408    UvData=get(handles.uvmat,'UserData');
1409    if isfield(UvData,'MaskName')
1410        UvData=rmfield(UvData,'MaskName');
1411        set(handles.uvmat,'UserData',UvData)
1412    end
1413    set(handles.CheckMask,'BackgroundColor',[0.7 0.7 0.7])
1414end
1415
1416%------------------------------------------------------------------------
1417function errormsg=update_mask(handles)
1418%------------------------------------------------------------------------
1419errormsg=[];%default
1420Mask=get(handles.CheckMask,'UserData');
1421MaskIndex=1;
1422if strcmp(get(handles.z_index,'Visible'),'on')
1423    MaskIndex=str2num(get(handles.z_index,'String'));
1424end
1425if isfield(Mask,'maskhandle')&& ishandle(Mask.maskhandle)
1426    uistack(Mask.maskhandle,'top');
1427end
1428MaskName=fullfile_uvmat(Mask.Path,'',Mask.File,Mask.Ext,Mask.NomType,MaskIndex);
1429UvData=get(handles.uvmat,'UserData');
1430
1431%% update mask image if the mask is new
1432if ~ (isfield(UvData,'MaskName') && isequal(UvData.MaskName,MaskName))
1433    UvData.MaskName=MaskName; %update the recorded name on UvData
1434    set(handles.uvmat,'UserData',UvData);
1435    if ~exist(MaskName,'file')
1436        if isfield(Mask,'maskhandle')&& ishandle(Mask.maskhandle)
1437            delete(Mask.maskhandle)   
1438        end
1439    else
1440        %read mask image
1441        [MaskField,tild,errormsg] = read_field(MaskName,'image');
1442        if ~isempty(errormsg)
1443            return
1444        end
1445        npxy=size(MaskField.A);
1446        if length(npxy)>2
1447            errormsg=[MaskName ' is not a grey scale image'];
1448            return
1449        elseif ~isa(MaskField.A,'uint8')
1450            errormsg=[MaskName ' is not a 8 bit grey level image'];
1451            return
1452        end
1453        MaskField.ZIndex=MaskIndex;
1454        %px to phys or other transform on field
1455         menu_transform=get(handles.TransformName,'String');
1456        choice_value=get(handles.TransformName,'Value');
1457        transform_name=menu_transform{choice_value};%name of the transform fct  given by the menu 'transform_fct'
1458        transform=get(handles.TransformPath,'UserData');
1459        if  ~isequal(transform_name,'') && ~isequal(transform_name,'px')
1460            if isfield(UvData,'XmlData') && isfield(UvData.XmlData{1},'GeometryCalib')%use geometry calib recorded from the ImaDoc xml file as first priority
1461                Calib=UvData.XmlData{1}.GeometryCalib;
1462                MaskField=transform(MaskField,UvData.XmlData{1});
1463            end
1464        end
1465        flagmask=MaskField.A < 200;
1466       
1467        %make brown color image
1468        imflag(:,:,1)=0.9*flagmask;
1469        imflag(:,:,2)=0.7*flagmask;
1470        imflag(:,:,3)=zeros(size(flagmask));
1471       
1472        %update mask image
1473        hmask=[]; %default
1474        if isfield(Mask,'maskhandle')&& ishandle(Mask.maskhandle)
1475            hmask=Mask.maskhandle;
1476        end
1477        if ~isempty(hmask)
1478            set(hmask,'CData',imflag)   
1479            set(hmask,'AlphaData',flagmask*0.6)
1480            set(hmask,'XData',MaskField.AX);
1481            set(hmask,'YData',MaskField.AY);
1482%             uistack(hmask,'top')
1483        else
1484            axes(handles.PlotAxes)
1485            hold on   
1486            Mask.maskhandle=image(MaskField.AX,MaskField.AY,imflag,'Tag','mask','HitTest','off','AlphaData',0.6*ones(size(flagmask)));
1487            set(handles.CheckMask,'UserData',Mask)
1488        end
1489    end
1490end
1491
1492%------------------------------------------------------------------------
1493%------------------------------------------------------------------------
1494% III - MAIN InputFileREFRESH FUNCTIONS : 'FRAME PLOT'
1495%------------------------------------------------------------------------
1496
1497%------------------------------------------------------------------------
1498% --- Executes on button press in runplus: make one step forward and call
1499% --- InputFileREFRESH. The step forward is along the fieldname series 1 or 2 depending on
1500% --- the scan_i and scan_j check box (exclusive each other)
1501function runplus_Callback(hObject, eventdata, handles)
1502%------------------------------------------------------------------------
1503
1504set(handles.runplus,'BackgroundColor',[1 1 0])%paint the command button in yellow
1505drawnow
1506increment=str2double(get(handles.num_IndexIncrement,'String')); %get the field increment d
1507if isnan(increment)% case of free increment: move to next available field index
1508    increment='+';
1509end
1510errormsg=runpm(hObject,eventdata,handles,increment);
1511if ~isempty(errormsg)
1512    msgbox_uvmat('ERROR',errormsg);
1513end
1514set(handles.runplus,'BackgroundColor',[1 0 0])%paint the command button back to red
1515
1516%------------------------------------------------------------------------
1517% --- Executes on button press in runmin: make one step backward and call
1518% --- InputFileREFRESH. The step backward is along the fieldname series 1 or 2 depending on
1519% --- the scan_i and scan_j check box (exclusive each other)
1520function runmin_Callback(hObject, eventdata, handles)
1521%------------------------------------------------------------------------
1522
1523set(handles.runmin,'BackgroundColor',[1 1 0])%paint the command button in yellow
1524drawnow
1525increment=-str2double(get(handles.num_IndexIncrement,'String')); %get the field increment d
1526if isnan(increment)% case of free increment: move to previous available field index
1527    increment='-';
1528end
1529errormsg=runpm(hObject,eventdata,handles,increment);
1530if ~isempty(errormsg)
1531    msgbox_uvmat('ERROR',errormsg);
1532end
1533set(handles.runmin,'BackgroundColor',[1 0 0])%paint the command button back to red
1534
1535%------------------------------------------------------------------------
1536% -- Executes on button press in Movie: make a series of +> steps
1537function Movie_Callback(hObject, eventdata, handles)
1538%------------------------------------------------------------------------
1539
1540set(handles.Movie,'BackgroundColor',[1 1 0])%paint the command button in yellow
1541drawnow
1542increment=str2double(get(handles.num_IndexIncrement,'String')); %get the field increment d
1543if isnan(increment)% case of free increment: move to next available field index
1544    increment='+';
1545end
1546set(handles.STOP,'Visible','on')
1547set(handles.speed,'Visible','on')
1548set(handles.speed_txt,'Visible','on')
1549set(handles.Movie,'BusyAction','queue')
1550UvData=get(handles.uvmat,'UserData');
1551
1552while get(handles.Movie,'Value')==1 && get(handles.speed,'Value')~=0 && isequal(get(handles.Movie,'BusyAction'),'queue') % enable STOP command
1553        errormsg=runpm(hObject,eventdata,handles,increment);
1554        if ~isempty(errormsg)
1555            set(handles.Movie,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1556            return
1557        end
1558        pause(1.02-get(handles.speed,'Value'))% wait for next image
1559end
1560if isfield(UvData,'aviobj') && ~isempty( UvData.aviobj),
1561    UvData.aviobj=close(UvData.aviobj);
1562   set(handles.uvmat,'UserData',UvData);
1563end
1564set(handles.Movie,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1565
1566%------------------------------------------------------------------------
1567% -- Executes on button press in Movie: make a series of <- steps
1568function MovieBackward_Callback(hObject, eventdata, handles)
1569%------------------------------------------------------------------------
1570set(handles.MovieBackward,'BackgroundColor',[1 1 0])%paint the command button in yellow
1571drawnow
1572increment=-str2double(get(handles.num_IndexIncrement,'String')); %get the field increment d
1573if isnan(increment)% case of free increment: move to next available field index
1574    increment='-';
1575end
1576set(handles.STOP,'Visible','on')
1577set(handles.speed,'Visible','on')
1578set(handles.speed_txt,'Visible','on')
1579set(handles.MovieBackward,'BusyAction','queue')
1580UvData=get(handles.uvmat,'UserData');
1581
1582while get(handles.MovieBackward,'Value')==1 && get(handles.speed,'Value')~=0 && isequal(get(handles.MovieBackward,'BusyAction'),'queue') % enable STOP command
1583        errormsg=runpm(hObject,eventdata,handles,increment);
1584        if ~isempty(errormsg)
1585            set(handles.MovieBackward,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1586            return
1587        end
1588        pause(1.02-get(handles.speed,'Value'))% wait for next image
1589end
1590if isfield(UvData,'aviobj') && ~isempty( UvData.aviobj),
1591    UvData.aviobj=close(UvData.aviobj);
1592   set(handles.uvmat,'UserData',UvData);
1593end
1594set(handles.MovieBackward,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1595
1596%------------------------------------------------------------------------
1597function STOP_Callback(hObject, eventdata, handles)
1598%------------------------------------------------------------------------
1599set(handles.movie_pair,'BusyAction','Cancel')
1600set(handles.movie_pair,'value',0)
1601set(handles.Movie,'BusyAction','Cancel')
1602set(handles.MovieBackward,'BusyAction','Cancel')
1603set(handles.MenuExportMovie,'BusyAction','Cancel')
1604%set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1605set(handles.Movie,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1606set(handles.MovieBackward,'BackgroundColor',[1 0 0])%paint the command buttonback to red
1607
1608%------------------------------------------------------------------------
1609% --- function activated by runplus and run minus
1610function errormsg=runpm(hObject,eventdata,handles,increment)
1611%------------------------------------------------------------------------
1612errormsg='';%default
1613%% check for movie pair status
1614movie_status=get(handles.movie_pair,'Value');
1615if isequal(movie_status,1)
1616    STOP_Callback(hObject, eventdata, handles)%interrupt movie pair if active
1617end
1618
1619%% read the current input file name(s) and field indices
1620InputFile=read_GUI(handles.InputFile);
1621InputFile.RootFile=regexprep(InputFile.RootFile,'^[\\/]|[\\/]$','');%suppress possible / or \ separator at the beginning or the end of the string
1622InputFile.SubDir=regexprep(InputFile.SubDir,'^[\\/]|[\\/]$','');%suppress possible / or \ separator at the beginning or the end of the string
1623FileExt=InputFile.FileExt;
1624NomType=InputFile.NomType;
1625% i1=str2num(get(handles.i1,'String'));%read the field indices (for movie, it is not given by the file name)
1626% i2=[];%default
1627% if strcmp(get(handles.i2,'Visible'),'on')
1628%     i2=str2num(get(handles.i2,'String'));
1629% end
1630% j1=[];
1631% if strcmp(get(handles.j1,'Visible'),'on')
1632%     j1=stra2num(get(handles.j1,'String'));
1633% end
1634% j2=j1;
1635% if strcmp(get(handles.j2,'Visible'),'on')
1636%     j2=stra2num(get(handles.j2,'String'));
1637% end
1638[tild,tild,tild,i1,i2,j1,j2]=fileparts_uvmat(InputFile.FileIndex);% check back the indices used
1639if isempty(i1)
1640    i1=str2num(get(handles.i1,'String'));%read the field indices (for movie, it is not given by the file name)
1641elseif isempty(j1) && strcmp(get(handles.j1,'Visible'),'on')
1642    j1=str2num(get(handles.j1,'String'));%case of indexed movie
1643end
1644sub_value= get(handles.SubField,'Value');
1645if sub_value % a second input file has been entered
1646    [InputFile.RootPath_1,InputFile.SubDir_1,InputFile.RootFile_1,InputFile.FileIndex_1,InputFile.FileExt_1,InputFile.NomType_1]=read_file_boxes_1(handles);
1647    [tild,tild,tild,i1_1,i2_1,j1_1,j2_1]=fileparts_uvmat(InputFile.FileIndex_1);% the indices for the second series taken from FileIndex_1
1648    if isempty(i1_1)
1649        i1_1=str2num(get(handles.i1,'String'));%read the field indices (for movie, it is not given by the file name)
1650    elseif isempty(j1_1) && strcmp(get(handles.j1,'Visible'),'on')
1651        j1_1=str2num(get(handles.j1,'String'));%case of indexed movie
1652    end
1653else
1654    filename_1=[];
1655end
1656
1657%% increment (or decrement) the field indices and update the input filename(s)
1658if ~isnumeric(increment)% undefined increment value
1659    set(handles.CheckFixPair,'Value',0)
1660end
1661CheckFixPair=get(handles.CheckFixPair,'Value')||(isempty(i2)&&isempty(j2));
1662
1663% the pair i1-i2 or j1-j2 is imposed (check box CheckFixPair selected)
1664if CheckFixPair && isnumeric(increment)
1665    if get(handles.scan_i,'Value')==1% case of scanning along index i
1666        i1=i1+increment;
1667        i2=i2+increment;
1668        if sub_value
1669            i1_1=i1_1+increment;
1670            i2_1=i2_1+increment;
1671        end
1672    else % case of scanning along index j (burst numbers)
1673        j1=j1+increment;
1674        j2=j2+increment;
1675        if sub_value
1676            j1_1=j1_1+increment;
1677            j2_1=j2_1+increment;
1678        end
1679    end
1680   
1681    % the pair i1-i2 or j1-j2 is free (check box CheckFixPair not selected): the list of existing indices recorded in UvData is used
1682else
1683    UvData=get(handles.uvmat,'UserData');
1684    ref_i=i1;
1685    if ~isempty(i2)
1686        ref_i=floor((i1+i2)/2);% current reference index i
1687    end
1688    ref_j=1;
1689    if ~isempty(j1)
1690        ref_j=j1;
1691        if ~isempty(j2)
1692            ref_j=floor((j1+j2)/2);% current reference index j
1693        end
1694    end
1695    if isnumeric(increment)
1696        if get(handles.scan_i,'Value')==1% case of scanning along index i
1697            ref_i=ref_i+increment;% increment the current reference index i
1698        else % case of scanning along index j (burst numbers)
1699            ref_j=ref_j+increment;% increment the current reference index j if scan_j option is used
1700        end
1701    else % free increment
1702        runaction=get(gcbo,'tag');
1703        if strcmp(increment,'+')% if runplus or movie is activated
1704            step=1;
1705        else
1706            step=-1;
1707        end
1708        if get(handles.scan_i,'Value')==1% case of scanning along index i
1709            ref_i=ref_i+step;
1710            while ref_i>=0  && size(UvData.i1_series{1},3)>=ref_i+1 && UvData.i1_series{1}(1,ref_j+1,ref_i+1)==0
1711                ref_i=ref_i+step;
1712            end
1713        else % case of scanning along index j (burst numbers)
1714            ref_j=ref_j+step;
1715            while ref_j>=0  && size(UvData.i1_series{1},2)>=ref_j+1 && UvData.i1_series{1}(1,ref_j+1,ref_i+1)==0
1716                ref_j=ref_j+step;
1717            end
1718        end
1719    end
1720    if ref_i<0
1721        errormsg='minimum i index reached';
1722    elseif ref_j<0
1723        errormsg='minimum j index reached';
1724    elseif ref_i+1>size(UvData.i1_series{1},3)
1725        errormsg='maximum i index reached (reload the input file to update the index bound)';
1726    elseif ref_j+1>size(UvData.i1_series{1},2)
1727        errormsg='maximum j index reached (reload the input file to update the index bound)';
1728    end
1729    if ~isempty(errormsg),return,end
1730    siz=size(UvData.i1_series{1});
1731    ref_indices=ref_i*siz(1)*siz(2)+ref_j*siz(1)+1:ref_i*siz(1)*siz(2)+(ref_j+1)*siz(1);
1732    i1_subseries=UvData.i1_series{1}(ref_indices);
1733    ref_indices=ref_indices(i1_subseries>0);
1734    if isempty(ref_indices)% case of pairs (free index i)
1735        ref_indices=ref_i*siz(1)*siz(2)+1:(ref_i+1)*siz(1)*siz(2);
1736        i1_subseries=UvData.i1_series{1}(ref_indices);
1737        ref_indices=ref_indices(i1_subseries>0);
1738    end
1739    if isempty(ref_indices),errormsg='no next frame: set num_IndexIncrement =''*'' to reach the next existing file';return
1740    end
1741    i1=UvData.i1_series{1}(ref_indices(end));
1742    if ~isempty(UvData.i2_series{1})
1743        i2=UvData.i2_series{1}(ref_indices(end));
1744    end
1745    if ~isempty(UvData.j1_series{1})
1746        j1=UvData.j1_series{1}(ref_indices(end));
1747    end
1748    if ~isempty(UvData.j2_series{1})
1749        j2=UvData.j2_series{1}(ref_indices(end));
1750    end
1751   
1752    % case of a second file series
1753    if sub_value
1754        ref_i_1=i1_1;
1755        if ~isempty(i2_1)
1756            ref_i_1=floor((i1_1+i2_1)/2);% current reference index i
1757        end
1758        ref_j_1=1;
1759        if ~isempty(j1_1)
1760            ref_j_1=j1_1;
1761            if ~isempty(j2_1)
1762                ref_j_1=floor((j1_1+j2_1)/2);% current reference index j
1763            end
1764        end
1765        if isnumeric(increment)
1766            if get(handles.scan_i,'Value')==1% case of scanning along index i
1767                ref_i_1=ref_i_1+increment;% increment the current reference index i
1768            else % case of scanning along index j (burst numbers)
1769                ref_j_1=ref_j_1+increment;% increment the current reference index j if scan_j option is used
1770            end
1771        else % free increment, synchronise the ref indices with the first series
1772            ref_i_1=ref_i;
1773            ref_j_1=ref_j;
1774        end
1775        if numel(UvData.i1_series)==1
1776            UvData.i1_series{2}=UvData.i1_series{1};
1777            UvData.j1_series{2}=UvData.j1_series{1};
1778            UvData.i2_series{2}=UvData.i2_series{1};
1779            UvData.j2_series{2}=UvData.j2_series{1};
1780        end
1781        if ref_i_1<0
1782            errormsg='minimum i index reached';
1783        elseif ref_j_1<0
1784            errormsg='minimum j index reached';
1785        elseif ref_i_1+1>size(UvData.i1_series{2},3)
1786            errormsg='maximum i index reached for the second series (reload the input file to update the index bound)';
1787        elseif ref_j_1+1>size(UvData.i1_series{2},2)
1788            errormsg='maximum j index reached for the second series(reload the input file to update the index bound)';
1789        end
1790        if ~isempty(errormsg),return,end
1791        siz=size(UvData.i1_series{2});
1792        ref_indices=ref_i_1*siz(1)*siz(2)+ref_j_1*siz(1)+1:ref_i_1*siz(1)*siz(2)+(ref_j_1+1)*siz(1);
1793        i1_subseries=UvData.i1_series{2}(ref_indices);
1794        ref_indices=ref_indices(i1_subseries>0);
1795        if isempty(ref_indices)% case of pairs (free index i)
1796            ref_indices=ref_i_1*siz(1)*siz(2)+1:(ref_i_1+1)*siz(1)*siz(2);
1797            i1_subseries=UvData.i1_series{2}(ref_indices);
1798            ref_indices=ref_indices(i1_subseries>0);
1799        end
1800        i1_1=UvData.i1_series{2}(ref_indices(end));
1801        if ~isempty(UvData.i2_series{2})
1802            i2_1=UvData.i2_series{2}(ref_indices(end));
1803        end
1804        if ~isempty(UvData.j1_series{2})
1805            j1_1=UvData.j1_series{2}(ref_indices(end));
1806        end
1807        if ~isempty(UvData.j2_series{2})
1808            j2_1=UvData.j2_series{1}(ref_indices(end));
1809        end
1810    else% the second series (if needed) is the same file as the first
1811        i1_1=i1;
1812        i2_1=i2;
1813        j1_1=j1;
1814        j2_1=j2;
1815    end
1816end
1817filename=fullfile_uvmat(InputFile.RootPath,InputFile.SubDir,InputFile.RootFile,FileExt,NomType,i1,i2,j1,j2);
1818
1819%% inputfilerefresh plots
1820if sub_value
1821    filename_1=fullfile_uvmat(InputFile.RootPath_1,InputFile.SubDir_1,InputFile.RootFile_1,InputFile.FileExt_1,InputFile.NomType_1,i1_1,i2_1,j1_1,j2_1);
1822    errormsg=refresh_field(handles,filename,filename_1,i1,i2,j1,j2,i1_1,i2_1,j1_1,j2_1);
1823else
1824    errormsg=refresh_field(handles,filename,filename_1,i1,i2,j1,j2);
1825end
1826set(handles.InputFileREFRESH,'BackgroundColor',[1 0 0])
1827
1828%% update the index counters if the index move is successfull
1829if isempty(errormsg)
1830    set(handles.i1,'String',num2stra(i1,NomType,1));
1831    if isequal(i2,i1)
1832        set(handles.i2,'String','');
1833    else
1834        set(handles.i2,'String',num2stra(i2,NomType,1));
1835    end
1836    set(handles.j1,'String',num2stra(j1,NomType,2));
1837    if isequal(j2,j1)
1838        set(handles.j2,'String','');
1839    else
1840        set(handles.j2,'String',num2stra(j2,NomType,2));
1841    end
1842    indices=fullfile_uvmat('','','','',NomType,i1,i2,j1,j2);
1843    set(handles.FileIndex,'String',indices);
1844    if ~isempty(filename_1)
1845        indices_1=fullfile_uvmat('','','','',InputFile.NomType_1,i1_1,i2_1,j1_1,j2_1);
1846        set(handles.FileIndex_1,'String',indices_1);
1847    end
1848    if isequal(movie_status,1)
1849        set(handles.movie_pair,'Value',1)
1850        movie_pair_Callback(hObject, eventdata, handles); %reactivate moviepair if it was activated
1851    else
1852        if isempty(i2), set(handles.i2,'String',''); end % suppress the second index display if not used
1853        if isempty(j2), set(handles.j2,'String',''); end
1854    end
1855    set(handles.i1,'BackgroundColor',[1 1 1])
1856    set(handles.i2,'BackgroundColor',[1 1 1])
1857    set(handles.j1,'BackgroundColor',[1 1 1])
1858    set(handles.j2,'BackgroundColor',[1 1 1])
1859    set(handles.FileIndex,'BackgroundColor',[1 1 1])
1860    set(handles.FileIndex_1,'BackgroundColor',[1 1 1])
1861end
1862
1863%------------------------------------------------------------------------
1864% --- Executes on button press in movie_pair: create an alternating movie with two view
1865function movie_pair_Callback(hObject, eventdata, handles)
1866%------------------------------------------------------------------------
1867
1868%% stop movie action if the movie_pair button is off
1869if ~get(handles.movie_pair,'value')
1870    set(handles.movie_pair,'BusyAction','Cancel')%stop movie pair if button is 'off'
1871    set(handles.i2,'String','')
1872    set(handles.j2,'String','')
1873    set(handles.Dt_txt,'String','')
1874    return
1875else
1876    set(handles.movie_pair,'BusyAction','queue')
1877    set(handles.InputFileREFRESH,'BackgroundColor',[1 0 0])
1878end
1879
1880%% initialisation
1881set(handles.movie_pair,'BackgroundColor',[1 1 0])%paint the command button in yellow
1882drawnow
1883list_fields=get(handles.FieldName,'String');% list menu fields
1884index_fields=get(handles.FieldName,'Value');% selected string index
1885FieldName=list_fields{index_fields}; % selected field
1886UvData=get(handles.uvmat,'UserData');
1887if isequal(FieldName,'image')
1888    index=1;
1889    [RootPath,SubDir,RootFile,FileIndices,Ext]=read_file_boxes(handles);
1890    NomType=get(handles.NomType,'String');
1891else
1892    list_fields=get(handles.FieldName_1,'String');% list menu fields
1893    index_fields=get(handles.FieldName_1,'Value');% selected string index
1894    FieldName=list_fields{index_fields}; % selected field
1895    if isequal(FieldName,'image')
1896        index=2;
1897        [RootPath,SubDir,RootFile,FileIndex_1,Ext,NomType]=read_file_boxes_1(handles);% get info from the second input line
1898    else
1899        msgbox_uvmat('ERROR','an image or movie must be first introduced as input')
1900        set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
1901        set(handles.movie_pair,'Value',0)
1902        return
1903    end
1904end
1905num_i1=str2num(get(handles.i1,'String'));
1906num_j1=stra2num(get(handles.j1,'String'));
1907num_i2=str2num(get(handles.i2,'String'));
1908num_j2=stra2num(get(handles.j2,'String'));
1909imaname_1='';
1910if isempty(num_j2)
1911    if isempty(num_i2)
1912        if strcmp(get(handles.j2,'Visible'),'on') %if the j box is visible
1913            imaname_1=fullfile_uvmat(RootPath,SubDir,RootFile,Ext,NomType,num_i1,[],num_j1+1);
1914        end
1915        if exist(imaname_1,'file')
1916            num_j2=num_j1+1;% look by default for the next j index as the second file
1917            set(handles.j2,'String',num2stra(num_j2,NomType));
1918        else
1919            imaname_1=fullfile_uvmat(RootPath,SubDir,RootFile,Ext,NomType,num_i1+1,[],num_j1);
1920            if exist(imaname_1,'file')
1921                num_i2=num_i1+1;
1922                set(handles.i2,'String',num2str(num_i2));
1923            else
1924                msgbox_uvmat('ERROR', 'a second image index i2 or j2 is needed to show the pair as a movie')
1925                set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
1926                set(handles.movie_pair,'Value',0)
1927                return
1928            end
1929        end
1930    else
1931        num_j2=num_j1;%repeat the index i1 by default
1932    end
1933end
1934if isempty(num_i2)
1935    num_i2=num_i1;%repeat the index i1 by default
1936end
1937if isempty(num_j1)
1938    num_j1=1;
1939end
1940if isempty(num_j2)
1941    num_j2=num_j1;%repeat the index i1 by default
1942end
1943imaname_1=fullfile_uvmat(RootPath,SubDir,RootFile,Ext,NomType,num_i2,[],num_j2);
1944if strcmp(NomType,'*')
1945    num_frame=num_i2;
1946else
1947    num_frame=num_j2;
1948end
1949if ~exist(imaname_1,'file')
1950      msgbox_uvmat('ERROR',['second input open (-)  ' imaname_1 ' not found']);
1951      set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
1952       set(handles.movie_pair,'Value',0)
1953      return
1954end
1955
1956%% display time interval for the image pair
1957if isfield(UvData,'XmlData')&&isfield(UvData.XmlData{1},'Time')...
1958        && size(UvData.XmlData{1}.Time,1)>=num_i2+1 && size(UvData.XmlData{1}.Time,2)>=num_j2+1
1959    dt=(UvData.XmlData{1}.Time(num_i2+1,num_j2+1)-UvData.XmlData{1}.Time(num_i1+1,num_j1+1));
1960    if  isfield(UvData,'TimeUnit')
1961        set(handles.Dt_txt,'String',['Dt=' num2str(1000*dt,3) '  m' UvData.TimeUnit] )
1962    else
1963        set(handles.Dt_txt,'String',['Dt=' num2str(1000*dt,3) '  10^(-3)'] )
1964    end
1965else
1966    set(handles.Dt_txt,'String','')
1967end
1968
1969%% get the first image
1970%Field.AName='image';
1971if index==1
1972    Field_a=UvData.Field;% movie on the second field
1973else
1974    Field_a=UvData.Field_1;% movie on the first field
1975end
1976
1977%% read the second image
1978MovieObject=[];
1979if numel(UvData.MovieObject)>=index
1980    MovieObject=UvData.MovieObject{index};
1981end
1982[Field_b,ParamOut,errormsg] = read_field(imaname_1,UvData.FileType{index},MovieObject,num_frame);
1983
1984%px to phys or other transform on field
1985transform=get(handles.TransformPath,'UserData');
1986if  ~isempty(transform)
1987    if isfield(UvData,'XmlData') && numel(UvData.XmlData)>=index %use geometry calib recorded from the ImaDoc xml file as first priority
1988        if index==2
1989        Field_a=transform(Field_a,UvData.XmlData{index});%the first field has been stored without transform
1990        end
1991        if nargin(transform)>=2
1992        Field_b=transform(Field_b,UvData.XmlData{index});
1993        else
1994          Field_b=transform(Field_b);
1995        end
1996    end
1997end
1998
1999% make movie until movie speed is set to 0 or STOP is activated
2000hima=findobj(handles.PlotAxes,'Tag','ima');% %handles.PlotAxes =main plotting window (A GENERALISER)
2001set(handles.STOP,'Visible','on')
2002set(handles.speed,'Visible','on')
2003set(handles.speed_txt,'Visible','on')
2004set(handles.i2,'BackgroundColor',[1 1 1])% mark the edit box in white to indicate its use as input
2005set(handles.j2,'BackgroundColor',[1 1 1])% mark the edit box in white to indicate its use as input
2006set(handles.FileIndex,'BackgroundColor',[1 1 1])% mark the edit box in white to indicate its use as input
2007while get(handles.speed,'Value')~=0 && isequal(get(handles.movie_pair,'BusyAction'),'queue') % enable STOP command
2008    % read and plot the series of images in non erase mode
2009    set(hima,'CData',Field_b.A);
2010    pause(1.02-get(handles.speed,'Value'));% wait for next image
2011    set(hima,'CData',Field_a.A);
2012    pause(1.02-get(handles.speed,'Value'));% wait for next image
2013end
2014set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
2015set(handles.movie_pair,'Value',0)
2016set(handles.Dt_txt,'String','')
2017
2018%------------------------------------------------------------------------
2019% --- Executes on button press in InputFileREFRESH.
2020function REFRESH_Callback(hObject, eventdata, handles)
2021%------------------------------------------------------------------------
2022set(handles.REFRESH,'BackgroundColor',[1 1 0])%paint the command button in yellow
2023drawnow
2024[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
2025[tild,tild,tild,i1,i2,j1,j2]=fileparts_uvmat(FileIndex);% check back the indices used
2026if isempty(i2), set(handles.i2,'String',''); end % suppress the second index display if not used
2027if isempty(j2), set(handles.j2,'String',''); end
2028filename=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];
2029filename_1='';%default
2030FileIndex_1='';
2031if get(handles.SubField,'Value')
2032    [RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
2033    filename_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];
2034end
2035num_i1=stra2num(get(handles.i1,'String'));
2036num_i2=stra2num(get(handles.i2,'String'));
2037num_j1=stra2num(get(handles.j1,'String'));
2038num_j2=stra2num(get(handles.j2,'String'));
2039[tild,tild,tild,i1_1,i2_1,j1_1,j2_1]=fileparts_uvmat(FileIndex_1);% get the indices of the second series from the string FileIndex_1
2040if isempty(j1_1)% case of movies, the index is not given by file index
2041    j1_1=num_j1;
2042end
2043
2044errormsg=refresh_field(handles,filename,filename_1,num_i1,num_i2,num_j1,num_j2,i1_1,i2_1,j1_1,j2_1);
2045
2046if ~isempty(errormsg)
2047      msgbox_uvmat('ERROR',errormsg);
2048      set(handles.InputFileREFRESH,'BackgroundColor',[1 0 1])% keep button color magenta, input not succesfull
2049else
2050    set(handles.i1,'BackgroundColor',[1 1 1])
2051    set(handles.i2,'BackgroundColor',[1 1 1])
2052    set(handles.j1,'BackgroundColor',[1 1 1])
2053    set(handles.j2,'BackgroundColor',[1 1 1])
2054    set(handles.FileIndex,'BackgroundColor',[1 1 1])
2055    set(handles.FileIndex_1,'BackgroundColor',[1 1 1]) 
2056    set(handles.REFRESH,'BackgroundColor',[1 0 0])% set button color to red, update successfull
2057end   
2058
2059%------------------------------------------------------------------------
2060% --- read the input files and inputfilerefresh all the plots, including projection.
2061% OUTPUT:
2062%  errormsg: error message char string  =[] by default
2063% INPUT:
2064% FileName: first input file (=[] in the absence of input file)
2065% FileName_1: second input file (=[] in the asbsence of second input file)
2066% num_i1,num_i2,num_j1,num_j2; frame indices
2067% i1_1,i2_1,j1_1,j2_1: frame indices for the second input file  (needed if FileName_1 is not empty)
2068%------------------------------------------------------------------------
2069function errormsg=refresh_field(handles,FileName,FileName_1,num_i1,num_i2,num_j1,num_j2,i1_1,i2_1,j1_1,j2_1)
2070%------------------------------------------------------------------------
2071
2072%% initialisation
2073pointer=get(handles.uvmat,'Pointer');
2074if strcmp(pointer,'watch')% reinitialise the mouse if stuck to 'watch'
2075    set(handles.CheckZoom,'Value',0)
2076    pointer='arrow';
2077end
2078set(handles.uvmat,'Pointer','watch')
2079drawnow
2080if ~exist('Field','var')
2081    Field={};
2082end
2083UvData=get(handles.uvmat,'UserData');
2084if ishandle(handles.UVMAT_title) %remove title panel on uvmat
2085    delete(handles.UVMAT_title)
2086end
2087
2088%% determine the main input file information for action
2089if ~exist(FileName,'file')
2090    errormsg=['input file ' FileName ' does not exist'];
2091    return
2092end
2093NomType=get(handles.NomType,'String');
2094NomType_1='';
2095if strcmp(get(handles.NomType_1,'Visible'),'on')
2096    NomType_1=get(handles.NomType_1,'String');
2097end
2098%update the z position index
2099mode_slice=get(handles.slices,'String');
2100if strcmp(mode_slice,'volume')
2101    z_index=num_j1;
2102    set(handles.z_index,'String',num2str(z_index))
2103else
2104    nbslice=str2num(get(handles.num_NbSlice,'String'));
2105    z_index=mod(num_i1-1,nbslice)+1;
2106    set(handles.z_index,'String',num2str(z_index))
2107end
2108% inputfilerefresh menu for save_mask if relevant
2109masknumber=get(handles.masklevel,'String');
2110if length(masknumber)>=z_index
2111    set(handles.masklevel,'Value',z_index)
2112end
2113
2114%% test for need of tps
2115check_proj_tps=0;
2116if  (strcmp(UvData.FileType{1},'civdata')||strcmp(UvData.FileType{1},'civx'))
2117    for iobj=1:numel(UvData.ProjObject)
2118        if isfield(UvData.ProjObject{iobj},'ProjMode')&& strcmp(UvData.ProjObject{iobj}.ProjMode,'interp_tps')
2119            check_proj_tps=1;
2120            break
2121        end
2122    end
2123end
2124
2125%% read the first input field
2126ParamIn.ColorVar='';%default variable name for vector color
2127frame_index=1;%default
2128FieldName='';%default
2129VelType='';%default
2130switch UvData.FileType{1}
2131    case {'civx','civdata','netcdf'};
2132        list_fields=get(handles.FieldName,'String');% list menu fields
2133        FieldName= list_fields{get(handles.FieldName,'Value')}; % selected field
2134        if ~strcmp(FieldName,'get_field...')
2135            if get(handles.FixVelType,'Value')
2136                VelTypeList=get(handles.VelType,'String');
2137                VelType=VelTypeList{get(handles.VelType,'Value')};
2138            end
2139        end
2140        % case of input vector field, get the scalar used for vector color
2141        if ~isempty(regexp(FieldName,'^vec('))
2142            list_code=get(handles.ColorCode,'String');% list menu fields
2143            index_code=get(handles.ColorCode,'Value');% selected string index
2144            if  ~strcmp(list_code{index_code},'black') &&  ~strcmp(list_code{index_code},'white')
2145                list_code=get(handles.ColorScalar,'String');% list menu fields
2146                index_code=get(handles.ColorScalar,'Value');% selected string index
2147                ParamIn.ColorVar= list_code{index_code}; % selected field
2148            end
2149        end
2150    case {'video','mmreader'}
2151        ParamIn=UvData.MovieObject{1};     
2152        if strcmp(NomType,'*')
2153            frame_index=num_i1;%frame index from a single movies or multimage
2154        else
2155            frame_index=num_j1;% frame index from a set of indexed movies
2156        end
2157    case 'multimage'
2158        if ~strcmp(NomType,'*')
2159            frame_index=num_j1;%frame index for movies or multimage
2160        else
2161            frame_index=num_i1;
2162        end
2163    case 'vol' %TODO: update
2164        if isfield(UvData.XmlData,'Npy') && isfield(UvData.XmlData,'Npx')
2165            ParamIn.Npy=UvData.XmlData.Npy;
2166            ParamIn.Npx=UvData.XmlData.Npx;
2167        else           
2168            errormsg='Npx and Npy need to be defined in the xml file for volume images .vol';
2169            return
2170        end
2171end
2172if isstruct (ParamIn)
2173    ParamIn.FieldName=FieldName;
2174    ParamIn.VelType=VelType;
2175    ParamIn.Coord_x=get(handles.Coord_x,'String');
2176    ParamIn.Coord_y=get(handles.Coord_y,'Data');
2177end
2178check_tps = 0;         
2179if strcmp(UvData.FileType{1},'civdata')&&~strcmp(ParamIn.FieldName,'velocity')&&~strcmp(ParamIn.FieldName,'get_field...')
2180       check_tps=1;%tps needed to get the requested field
2181end
2182[Field{1},ParamOut,errormsg] = read_field(FileName,UvData.FileType{1},ParamIn,frame_index);
2183if ~isempty(errormsg)
2184    errormsg=['uvmat / refresh_field / read_field( ' FileName ') / ' errormsg];
2185    return
2186end 
2187if isfield(ParamOut,'Npx')&& isfield(ParamOut,'Npy')
2188    set(handles.num_Npx,'String',num2str(ParamOut.Npx));% display image size on the interface
2189    set(handles.num_Npy,'String',num2str(ParamOut.Npy));
2190end
2191Field{1}.ZIndex=z_index; %used for multiplane 3D calibration
2192
2193%% choose and read a second field FileName_1 if defined
2194VelType_1=[];%default
2195FieldName_1=[];
2196ParamIn_1=[];
2197ParamOut_1=[];
2198frame_index_1=1;
2199if ~isempty(FileName_1)
2200    if ~exist(FileName_1,'file')
2201        errormsg=['second file ' FileName_1 ' does not exist'];
2202        return
2203    end
2204    switch UvData.FileType{2}
2205        case {'civx','civdata','netcdf'};
2206            list_fields=get(handles.FieldName_1,'String');% list menu fields
2207            if ischar(list_fields),list_fields={list_fields};end
2208            FieldName_1= list_fields{get(handles.FieldName_1,'Value')}; % selected field
2209            if ~strcmp(FieldName,'get_field...')
2210                if get(handles.FixVelType,'Value')
2211                    VelTypeList=get(handles.VelType_1,'String');
2212                    VelType_1=VelTypeList{get(handles.VelType_1,'Value')};% read the velocity type.
2213                end
2214            end
2215            if strcmp(FieldName_1,'velocity')&& strcmp(get(handles.ColorCode,'Visible'),'on')
2216                list_code=get(handles.ColorCode,'String');% list menu fields
2217                index_code=get(handles.ColorCode,'Value');% selected string index
2218                if  ~strcmp(list_code{index_code},'black') &&  ~strcmp(list_code{index_code},'white')
2219                    list_code=get(handles.ColorScalar,'String');% list menu fields
2220                    index_code=get(handles.ColorScalar,'Value');% selected string index
2221                    ParamIn_1.ColorVar= list_code{index_code}; % selected field for vector color display                 
2222                end
2223            end
2224        case {'video','mmreader'}
2225            ParamIn_1=UvData.MovieObject{2};
2226                        if ~strcmp(NomType_1,'*')
2227                frame_index_1=j1_1;%frame index for movies or multimage
2228            else
2229                frame_index_1=i1_1;
2230            end 
2231         case 'multimage'
2232            if strcmp(NomType_1,'*')%frame index for movies or multimage
2233                frame_index_1=i1_1;
2234            else
2235                frame_index_1=j1_1;
2236            end   
2237        case 'vol' %TODO: update
2238            if isfield(UvData.XmlData,'Npy') && isfield(UvData.XmlData,'Npx')
2239                ParamIn_1.Npy=UvData.XmlData.Npy;
2240                ParamIn_1.Npx=UvData.XmlData.Npx;
2241            else
2242                errormsg='Npx and Npy need to be defined in the xml file for volume images .vol';
2243                return
2244            end
2245    end
2246    if isequal(get(handles.NomType_1,'Visible'),'on')
2247    NomType_1=get(handles.NomType_1,'String');
2248    else
2249        NomType_1=get(handles.NomType,'String');
2250    end
2251    test_keepdata_1=0;% test for keeping the previous stored data if the input files are unchanged
2252    if ~isequal(NomType_1,'*')&& isfield(UvData,'FileName_1')
2253           test_keepdata_1= strcmp(FileName_1,UvData.FileName_1) ;
2254    end
2255    if test_keepdata_1
2256        Field{2}=UvData.Field_1;% keep the stored field
2257        ParamOut_1=UvData.ParamOut_1;
2258    else
2259        if isempty(ParamIn_1) || isstruct(ParamIn_1)
2260        ParamIn_1.FieldName=FieldName_1;
2261        ParamIn_1.VelType=VelType_1;
2262        ParamIn_1.Coord_x=get(handles.Coord_x,'String');
2263        ParamIn_1.Coord_y=get(handles.Coord_y,'Data');
2264        end 
2265        [Field{2},ParamOut_1,errormsg] = read_field(FileName_1,UvData.FileType{2},ParamIn_1,frame_index_1);
2266        if ~isempty(errormsg)
2267            errormsg=['error in reading ' FieldName_1 ' in ' FileName_1 ': ' errormsg];
2268            return
2269        end
2270        if isstruct(ParamOut_1)&&~strcmp(ParamOut_1.FieldName,'get_field...')&& (strcmp(UvData.FileType{2},'civdata')||strcmp(UvData.FileType{2},'civx'))...
2271                &&~strcmp(ParamOut_1.FieldName,'velocity') && ~strcmp(ParamOut_1.FieldName,'get_field...')
2272            if ~check_proj_tps
2273            end
2274        end
2275    end
2276    Field{2}.ZIndex=z_index;%used for multi-plane 3D calibration
2277end
2278
2279%% update uvmat interface
2280if isfield(ParamOut,'Npx')
2281    set(handles.num_Npx,'String',num2str(ParamOut.Npx));% display image size on the interface
2282    set(handles.num_Npy,'String',num2str(ParamOut.Npy));
2283elseif isfield(ParamOut_1,'Npx')
2284    set(handles.num_Npx,'String',num2str(ParamOut_1.Npx));% display image size on the interface
2285    set(handles.num_Npy,'String',num2str(ParamOut_1.Npy));
2286end
2287
2288%% update the display menu for the first velocity type (first menuline)
2289test_veltype=0;
2290if (strcmp(UvData.FileType{1},'civx')||strcmp(UvData.FileType{1},'civdata'))&& ~strcmp(FieldName,'get_field...')
2291    test_veltype=1;
2292    set(handles.VelType,'Visible','on')
2293    set(handles.VelType_1,'Visible','on')
2294    set(handles.FixVelType,'Visible','on')
2295    menu=set_veltype_display(ParamOut.CivStage,UvData.FileType{1});
2296    index_menu=strcmp(ParamOut.VelType,menu);%look for VelType in  the menu
2297    index_val=find(index_menu,1);
2298    if isempty(index_val)
2299        index_val=1;
2300    end
2301    set(handles.VelType,'Value',index_val)
2302    if ~get(handles.SubField,'value')
2303        set(handles.VelType,'String',menu)
2304        set(handles.VelType_1,'Value',1)
2305        set(handles.VelType_1,'String',[{''};menu])
2306    end
2307else
2308    set(handles.VelType,'Visible','off')
2309end
2310
2311%% update the display menu for the second velocity type (second menuline)
2312test_veltype_1=0;
2313if isempty(FileName_1)
2314    %     set(handles.FieldName_1,'Value',1); %update the field menu
2315    %     if isstruct(ParamOut)
2316    %     set(handles.FieldName_1,'String',[{''};ParamOut.FieldList]); %update the field menu
2317    %     end
2318elseif ~test_keepdata_1
2319    if (strcmp(UvData.FileType{2},'civx')||strcmp(UvData.FileType{2},'civdata'))&& ~strcmp(FieldName_1,'get_field...')
2320%     if (~strcmp(UvData.FileType{2},'netcdf')&&~strcmp(UvData.FileType{2},'civdata')&&~strcmp(UvData.FileType{2},'civx'))|| isequal(FieldName_1,'get_field...')
2321        test_veltype_1=1;
2322        set(handles.VelType_1,'Visible','on')
2323        menu=set_veltype_display(ParamOut_1.CivStage,UvData.FileType{2});
2324        index_menu=strcmp(ParamOut_1.VelType,menu);
2325        set(handles.VelType_1,'Value',1+find(index_menu,1))
2326        set(handles.VelType_1,'String',[{''};menu])
2327    else
2328         set(handles.VelType_1,'Visible','off')
2329    end
2330    % update the second field menu: the same quantity
2331    if isstruct(ParamOut_1)
2332        % display the FieldName menu from the input file and pick the selected one:
2333        FieldList=get(handles.FieldName_1,'String');
2334        field_index=strcmp(ParamOut_1.FieldName,FieldList);
2335        if ~isempty(field_index)
2336            set(handles.FieldName_1,'Value',find(field_index,1))
2337        end
2338    end
2339end
2340if test_veltype||test_veltype_1
2341    set(handles.FixVelType,'Visible','on')
2342else
2343    set(handles.FixVelType,'Visible','off')
2344end
2345   
2346%% introduce w as background image by default for a new series (only for nbdim=2)
2347if ~isfield(UvData,'NewSeries')
2348    UvData.NewSeries=1;
2349end
2350%put W as background image by default if NbDim=2:
2351if  UvData.NewSeries && isequal(get(handles.SubField,'Value'),0) && isfield(Field{1},'W') && ~isempty(Field{1}.W) && ~isequal(Field{1}.NbDim,3);
2352        set(handles.SubField,'Value',1);
2353        set(handles.RootPath_1,'String','"')
2354        set(handles.RootFile_1,'String','"')
2355        set(handles.SubDir_1,'String','"');
2356         indices=fullfile_uvmat('','','','',NomType,num_i1,num_i2,num_j1,num_j2);
2357        set(handles.FileIndex_1,'String',indices)
2358        set(handles.FileExt_1,'String','"');
2359        set(handles.FieldName_1,'Visible','on');
2360        set(handles.FieldName_1,'Visible','on');
2361        set(handles.RootPath_1,'Visible','on')
2362        set(handles.RootFile_1,'Visible','on')
2363        set(handles.SubDir_1,'Visible','on');
2364        set(handles.FileIndex_1,'Visible','on');
2365        set(handles.FileExt_1,'Visible','on');
2366        set(handles.FieldName_1,'Visible','on');
2367        Field{1}.AName='w';
2368end           
2369
2370%% display time value of the current file
2371abstime=[];%default inputs
2372dt=[];
2373TimeUnit='';
2374if isfield(UvData,'TimeUnit')
2375TimeUnit=UvData.TimeUnit;%retrieve info from update_rootinfo
2376end
2377% time from xml file or video movie
2378TimeName=get(handles.TimeName,'String');% indicate that time is from xml
2379if strcmp(TimeName,'xml')||strcmp(TimeName,'video')
2380    if isempty(num_i2)||isnan(num_i2)
2381        num_i2=num_i1;
2382    end
2383    if isempty(num_j1)||isnan(num_j1)
2384        num_j1=1;
2385    end
2386    if isempty(num_j2)||isnan(num_j2)
2387        num_j2=num_j1;
2388    end
2389    siz=size(UvData.XmlData{1}.Time);
2390    if ~isempty(num_i1)&& ~isempty(num_i2) && num_i1>=0 &&siz(1)>=max(num_i1+1,num_i2+1) && siz(2)>=max(num_j1+1,num_j2+1)
2391        abstime=(UvData.XmlData{1}.Time(num_i1+1,num_j1+1)+UvData.XmlData{1}.Time(num_i2+1,num_j2+1))/2;%overset the time read from files
2392        dt=(UvData.XmlData{1}.Time(num_i2+1,num_j2+1)-UvData.XmlData{1}.Time(num_i1+1,num_j1+1));
2393        Field{1}.Dt=dt;
2394        if isfield(UvData.XmlData{1},'TimeUnit')
2395            TimeUnit=UvData.XmlData{1}.TimeUnit;
2396        end
2397    end
2398end
2399
2400% get time in the input file, not defined in a xml file or movie
2401if isempty(abstime)
2402    if strcmp(TimeName,'civdata')||strcmp(TimeName,'civx')
2403        abstime=Field{1}.Time;
2404    elseif ~isempty(regexp(TimeName,'^att:'))||~isempty(regexp(TimeName,'^var:'))
2405        abstime=Field{1}.(TimeName(5:end));%the time is an attribute or variale selected by get_file
2406    elseif ~isempty(regexp(TimeName,'^dim:'))
2407        abstime=str2num(get(handles.i1,'String'));
2408    end
2409    if isfield(Field{1},'Dt')
2410        dt=Field{1}.Dt;%dt read from the netcdf input file
2411        if isfield(Field{1},'TimeUnit')
2412            TimeUnit=Field{1}.TimeUnit;
2413        end
2414    elseif numel(Field)==2 && isfield(Field{2},'Dt')%dt obtained from the second field if not defined in the first
2415        dt=Field{2}.Dt;%dt read from the netcdf input file
2416        if isfield(Field{2},'TimeUnit')
2417            TimeUnit=Field{2}.TimeUnit;
2418        end
2419    end
2420end
2421set(handles.TimeValue,'String',num2str(abstime))
2422
2423%% display time value of the second current file if relevant
2424abstime_1=[];
2425if ~isempty(FileName_1)
2426    TimeName_1=get(handles.TimeName_1,'String');% indicate whether time is from xml or video
2427    % time from xml file or video movie as a second file series
2428    if strcmp(TimeName_1,'xml')||strcmp(TimeName_1,'video')
2429        if numel(UvData.XmlData)==2
2430            if isempty(i2_1)
2431                i2_1=num_i1;
2432            end
2433            if isempty(j1_1)
2434                j1_1=1;
2435            end
2436            if isempty(j2_1)
2437                j2_1=j1_1;
2438            end
2439            siz=size(UvData.XmlData{2}.Time);
2440            if ~isempty(i1_1) && siz(1)>=max(i1_1+1,i2_1+1) && siz(2)>=max(j1_1+1,j2_1+1)
2441                abstime_1=(UvData.XmlData{2}.Time(i1_1+1,j1_1+1)+UvData.XmlData{2}.Time(i2_1+1,j2_1+1))/2;%overset the time read from files
2442                Field{2}.Dt=(UvData.XmlData{2}.Time(i2_1+1,j2_1+1)-UvData.XmlData{2}.Time(i1_1+1,j1_1+1));
2443            end
2444        end
2445    end
2446   
2447    % get time in the input file of the second series, not defined in a xml file or movie
2448    if isempty(abstime_1) && numel(Field)==2
2449         if strcmp(TimeName_1,'civdata')||strcmp(TimeName_1,'civx')
2450        abstime_1=Field{2}.Time;
2451         elseif  ~isempty(regexp(TimeName_1,'^att:')) ||~isempty(regexp(TimeName_1,'^dim:'))||~isempty(regexp(TimeName_1,'^var:'))
2452        abstime_1=Field{2}.(TimeName_1(5:end));%the time is an attribute or variale selected by get_file
2453         end
2454    end
2455    set(handles.TimeValue_1,'String',num2str(abstime_1,5))
2456end
2457
2458if isempty(dt)||isequal(dt,0)
2459    set(handles.Dt_txt,'String','')
2460else
2461    if  isempty(TimeUnit)
2462        set(handles.Dt_txt,'String',['Dt=' num2str(1000*dt,3) '  10^(-3)'] )
2463    else
2464        set(handles.Dt_txt,'String',['Dt=' num2str(1000*dt,3) '  m' TimeUnit] )
2465    end
2466end
2467
2468%% Time title with unit
2469if isempty(abstime)&&isempty(abstime_1)
2470    Time_title='';
2471else
2472    Time_title='Time';
2473    if ~isempty(TimeUnit)
2474        Time_title=['Time (' TimeUnit ')'];
2475    end
2476end
2477set(handles.Time_title,'String',Time_title)
2478
2479%% store the current open names, fieldname and vel types in uvmat interface
2480UvData.FileName_1=FileName_1;
2481UvData.ParamOut_1=ParamOut_1;
2482if numel(Field)==2
2483    UvData.Field_1=Field{2}; %store the second field for possible use at next RUN
2484end
2485
2486%% apply coordinate transform or other user fct
2487transform=get(handles.TransformPath,'UserData');
2488if isempty(transform)
2489    UvData.Field=Field{1};
2490else
2491    XmlData=[];%default
2492    XmlData_1=[];%default
2493    if isfield(UvData,'XmlData')%use geometry calib recorded from the ImaDoc xml file as first priority
2494        XmlData=UvData.XmlData{1};
2495        if numel(UvData.XmlData)==2
2496            XmlData_1=UvData.XmlData{2};
2497        end
2498    end
2499    switch nargin(transform)
2500        case 4
2501            if length(Field)==2
2502                UvData.Field=transform(Field{1},XmlData,Field{2},XmlData_1);
2503            else
2504                UvData.Field=transform(Field{1},XmlData);
2505            end
2506        case 3
2507            if length(Field)==2
2508                UvData.Field=transform(Field{1},XmlData,Field{2});
2509            else
2510                UvData.Field=transform(Field{1},XmlData);
2511            end
2512        case 2
2513            UvData.Field=transform(Field{1},XmlData);
2514        case 1
2515            UvData.Field=transform(Field{1});
2516    end
2517end
2518
2519%% calculate tps coefficients if needed
2520UvData.Field=tps_coeff_field(UvData.Field,check_proj_tps);
2521
2522%% get bounds and dimensions of the input field
2523UvData.Field=find_field_bounds(UvData.Field);
2524
2525if UvData.Field.NbDim>1
2526    % default projection plane
2527    if isempty(UvData.ProjObject{1})
2528        UvData.ProjObject{1}.Type='plane';%main plotting plane
2529        UvData.ProjObject{1}.ProjMode='projection';%main plotting plane
2530       % UvData.ProjObject{1}.Coord=[0 0 0];
2531        UvData.ProjObject{1}.DisplayHandle.uvmat=[]; %plane not visible in uvmat
2532        UvData.ProjObject{1}.DisplayHandle.view_field=[]; %plane not visible in uvmat
2533    end
2534    %% 3D case (menuvolume)
2535    if UvData.Field.NbDim==3% && UvData.NewSeries
2536        test_set_object=1;
2537        hset_object=findobj(allchild(0),'tag','set_object');% look for the set_object GUI
2538        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
2539        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
2540        if ~isempty(hset_object) %if set_object is detected
2541            delete(hset_object);% delete the GUI set_object if it does not fit
2542        end
2543        if test_set_object% reinitiate the GUI set_object
2544            delete_object(1);% delete the current projection object in the list UvData.ProjObject, delete its graphic representations and update the list displayed in handles.ListObject and 2
2545            UvData.ProjObject{1}.NbDim=NbDim;%test for 3D objects
2546            UvData.ProjObject{1}.RangeZ=UvData.Field.CoordMesh;%main plotting plane
2547            UvData.ProjObject{1}.Coord(1,3)=(UvData.Field.ZMin+UvData.Field.ZMax)/2;%section at a middle plane chosen
2548            UvData.ProjObject{1}.Angle=[0 0 0];
2549            UvData.ProjObject{1}.HandlesDisplay=plot(0,0,'Tag','proj_object');% A REVOIR
2550            UvData.ProjObject{1}.Name='1-PLANE';
2551            UvData.ProjObject{1}.enable_plot=1;
2552            set_object(UvData.ProjObject{1},handles,ZBounds);
2553            set(hset_object,'name','set_object');% rename if set_object already used with series
2554            set(handles.ListObject,'Value',1);
2555            set(handles.ListObject,'String',{'1-PLANE'});
2556            set(handles.CheckEditObject,'Value',1)% put the plane in edit mode to enable the z cursor
2557            CheckEditObject_Callback([],[], handles)
2558        end
2559        %multilevel case (single menuplane in a 3D space)
2560    elseif isfield(UvData,'Z')
2561        if isfield(UvData,'CoordType')&& isequal(UvData.CoordType,'phys') && isfield(UvData,'XmlData')
2562            XmlData=UvData.XmlData{1};
2563            if isfield(XmlData,'PlanePos')
2564                UvData.ProjObject{1}.Coord=XmlData.PlanePos(UvData.ZIndex,:);
2565            end
2566            if isfield(XmlData,'PlaneAngle')
2567                siz=size(XmlData.PlaneAngle);
2568                indangle=min(siz(1),UvData.ZIndex);%take first angle if a single angle is defined (translating scanning)
2569                UvData.ProjObject{1}.PlaneAngle=XmlData.PlaneAngle(indangle,:);
2570            end
2571        elseif isfield(UvData,'ZIndex')
2572            UvData.ProjObject{1}.ZObject=UvData.ZIndex;
2573        end
2574    end
2575end
2576
2577testnewseries=UvData.NewSeries;
2578UvData.NewSeries=0;% put to 0 the test for a new field series (set by RootPath_callback)
2579set(handles.uvmat,'UserData',UvData)
2580
2581%% reset the min and max of scalar if only the mask is displayed(TODO: check the need)
2582% if isfield(UvData,'Mask')&& ~isfield(UvData,'A')
2583%     set(handles.num_MinA,'String','0')
2584%     set(handles.num_MaxA,'String','255')
2585% end
2586
2587%% usual 1D (x,y) plots
2588if UvData.Field.NbDim<=1
2589    set(handles.Objects,'Visible','off')
2590%     set(handles.ListObject_1_title,'Visible','off')
2591%     set(handles.ListObject_1,'Visible','off')
2592    [PlotType,PlotParamOut]=plot_field(UvData.Field,handles.PlotAxes,read_GUI(handles.uvmat));
2593    errormsg=fill_GUI(PlotParamOut,handles.uvmat);
2594    for list={'Scalar','Vectors'}
2595        if ~isfield(PlotParamOut,list{1})
2596            set(handles.(list{1}),'Visible','off')
2597        end
2598    end
2599   
2600%% 2D or 3D fieldname are generally projected
2601else
2602    set(handles.Objects,'Visible','on')
2603%     set(handles.ListObject_1_title,'Visible','on')
2604%     set(handles.ListObject_1,'Visible','on')
2605   
2606    %% Plot the projections on the selected  projection objects
2607    % main projection object (uvmat display)
2608    list_object=get(handles.ListObject_1,'String');
2609    if isequal(list_object,{''})||isequal(list_object,' ')%refresh list of objects if the menu is empty
2610        set(handles.ListObject,'Value',1)
2611        set(handles.ListObject,'String',{'plane'})
2612        UvData.ProjObject{1}.Type='plane';%main plotting plane
2613        UvData.ProjObject{1}.ProjMode='projection';%main plotting plane
2614        UvData.ProjObject{1}.DisplayHandle.uvmat=[]; %plane not visible in uvmat
2615        UvData.ProjObject{1}.DisplayHandle.view_field=[]; %plane not visible in uvmat
2616        set(handles.ListObject_1,'Value',1)
2617        set(handles.ListObject_1,'String',{'plane'})
2618    end
2619    IndexObj=get(handles.ListObject_1,'Value');%selected projection object for main view
2620    if IndexObj> numel(UvData.ProjObject)
2621        IndexObj=1;%select the first object if the selected one does not exist
2622        set(handles.ListObject_1,'Value',1)
2623    end
2624    if get(handles.CheckViewField,'Value')
2625        IndexObj_2=get(handles.ListObject,'Value');%selected projection object for view_field
2626        if ~isequal(IndexObj_2,IndexObj(1))
2627            IndexObj(2)=IndexObj_2;
2628        end
2629    end
2630    plot_handles{1}=handles;
2631    if isfield(UvData,'plotaxes')%case of movies
2632        haxes(1)=UvData.plotaxes;
2633    else
2634        haxes(1)=handles.PlotAxes;
2635    end
2636    PlotParam{1}=read_GUI(handles.uvmat);
2637    %default settings if vectors not visible
2638    if ~isfield(PlotParam{1},'Vectors')
2639        PlotParam{1}.Vectors.MaxVec=1;
2640        PlotParam{1}.Vectors.MinVec=0;
2641        PlotParam{1}.Vectors.CheckFixVecColor=1;
2642        PlotParam{1}.Vectors.ColCode1=0.33;
2643        PlotParam{1}.Vectors.ColCode2=0.66;
2644        PlotParam{1}.Vectors.ColorScalar={''};
2645        PlotParam{1}.Vectors.ColorCode= {'rgb'};
2646    end
2647    PosColorbar{1}=UvData.OpenParam.PosColorbar;%prescribe the colorbar position on the uvmat interface
2648   
2649    %% second projection object (view_field display)
2650    if length( IndexObj)>=2
2651        view_field_handle=findobj(allchild(0),'tag','view_field');%handles of the view_field GUI
2652        if ~isempty(view_field_handle)
2653            plot_handles{2}=guidata(view_field_handle);
2654            haxes(2)=plot_handles{2}.PlotAxes;
2655            PlotParam{2}=read_GUI(view_field_handle);
2656           % PlotParam{2}=read_GUI(handles.uvmat);%read plotting parameters on the uvmat interface
2657            PosColorbar{2}='*'; %TODO: deal with colorbar position on view_field
2658        end
2659    end
2660   
2661    %% loop on the projection objects: one or two
2662   
2663    for imap=1:numel(IndexObj)
2664        iobj=IndexObj(imap);
2665        if numel(UvData.ProjObject)<iobj
2666            break
2667        end
2668        [ObjectData,errormsg]=proj_field(UvData.Field,UvData.ProjObject{iobj});% project field on the object
2669        if ~isempty(errormsg)
2670            return
2671        end
2672        if testnewseries
2673            PlotParam{imap}.Scalar.CheckBW=[]; %B/W option depends on the input field (image or scalar)
2674            if isfield(ObjectData,'CoordUnit')
2675                PlotParam{imap}.Coordinates.CheckFixAspectRatio=1;% set x and y scaling equal if CoordUnit is defined (common unit for x and y)
2676                PlotParam{imap}.Coordinates.AspectRatio=1; %set aspect ratio to 1
2677            end
2678        end
2679        %use of mask (TODO: check)
2680        if isfield(ObjectData,'NbDim') && isequal(ObjectData.NbDim,2) && isfield(ObjectData,'Mask') && isfield(ObjectData,'A')
2681            flag_mask=double(ObjectData.Mask>200);%=0 for masked regions
2682            AX=ObjectData.AX;%x coordiantes for the scalar field
2683            AY=ObjectData.AY;%y coordinates for the scalar field
2684            MaskX=ObjectData.MaskX;%x coordiantes for the mask
2685            MaskY=ObjectData.MaskY;%y coordiantes for the mask
2686            if ~isequal(MaskX,AX)||~isequal(MaskY,AY)
2687                nxy=size(flag_mask);
2688                sizpx=(ObjectData.MaskX(end)-ObjectData.MaskX(1))/(nxy(2)-1);%size of a mask pixel
2689                sizpy=(ObjectData.MaskY(1)-ObjectData.MaskY(end))/(nxy(1)-1);
2690                x_mask=ObjectData.MaskX(1):sizpx:ObjectData.MaskX(end); % pixel x coordinates for image display
2691                y_mask=ObjectData.MaskY(1):-sizpy:ObjectData.MaskY(end);% pixel x coordinates for image display
2692                %project on the positions of the scalar
2693                npxy=size(ObjectData.A);
2694                dxy(1)=(ObjectData.AY(end)-ObjectData.AY(1))/(npxy(1)-1);%grid mesh in y
2695                dxy(2)=(ObjectData.AX(end)-ObjectData.AX(1))/(npxy(2)-1);%grid mesh in x
2696                xi=ObjectData.AX(1):dxy(2):ObjectData.AX(end);
2697                yi=ObjectData.AY(1):dxy(1):ObjectData.AY(end);
2698                [XI,YI]=meshgrid(xi,yi);% creates the matrix of regular coordinates
2699                flag_mask = interp2(x_mask,y_mask,flag_mask,XI,YI);
2700            end
2701            AClass=class(ObjectData.A);
2702            ObjectData.A=flag_mask.*double(ObjectData.A);
2703            ObjectData.A=feval(AClass,ObjectData.A);
2704        end
2705        if ~isempty(ObjectData)
2706            %PlotType='none'; %default
2707            if imap==2 && isempty(view_field_handle)
2708                view_field(ObjectData)
2709            else
2710              %  ObjectData.VarAttribute{5}.Role='scalar';TODO    CORRECT
2711                [PlotType,PlotParamOut]=plot_field(ObjectData,haxes(imap),PlotParam{imap},PosColorbar{imap});
2712                if imap==1
2713                    errormsg=fill_GUI(PlotParamOut,handles.uvmat);
2714                else
2715                    errormsg=fill_GUI(PlotParamOut,view_field_handle);
2716                end
2717                for list={'Scalar','Vectors'}
2718                    if ~isfield(PlotParamOut,list{1})
2719                        set(plot_handles{imap}.(list{1}),'Visible','off')
2720                    end
2721                end
2722                if isfield(Field,'CoordMesh')&&~isempty(Field.CoordMesh)
2723                    ObjectData.CoordMesh=Field.CoordMesh; % gives an estimated mesh size (useful for mouse action on the plot)
2724                end
2725            end
2726        end
2727    end
2728   
2729    %% update the mask
2730    if isequal(get(handles.CheckMask,'Value'),1)%if the mask option is on
2731        update_mask(handles);
2732    end
2733   
2734    %% prepare the menus of histograms and plot them (histogram of the whole volume in 3D case)
2735    menu_histo=(UvData.Field.ListVarName)';%list of field variables to be displayed for the menu of histogram display
2736    ind_skip=[];
2737    % nb_histo=1;
2738    Ustring='';
2739    Vstring='';
2740    % suppress coordinates from the histogram menu
2741    for ivar=1:numel(menu_histo)%l loop on field variables:
2742        if isfield(UvData.Field,'VarAttribute') && numel(UvData.Field.VarAttribute)>=ivar && isfield(UvData.Field.VarAttribute{ivar},'Role')
2743            Role=UvData.Field.VarAttribute{ivar}.Role;
2744            switch Role
2745                case {'coord_x','coord_y','coord_z','dimvar'}
2746                    ind_skip=[ind_skip ivar];
2747                case {'vector_x'}
2748                    Ustring=UvData.Field.ListVarName{ivar};
2749                    ind_skip=[ind_skip ivar];
2750                case {'vector_y'}
2751                    Vstring=UvData.Field.ListVarName{ivar};
2752                    ind_skip=[ind_skip ivar];
2753            end
2754        end
2755        DimCell=UvData.Field.VarDimName{ivar};
2756        DimName='';
2757        if ischar(DimCell)
2758            DimName=DimCell;
2759        elseif iscell(DimCell)&& numel(DimCell)==1
2760            DimName=DimCell{1};
2761        end
2762        if strcmp(DimName,menu_histo{ivar})
2763            ind_skip=[ind_skip ivar];
2764        end
2765    end
2766    menu_histo(ind_skip)=[];% remove skipped items
2767    if ~isempty(Ustring)
2768        menu_histo=[{[Ustring ',' Vstring]};menu_histo];% add U, V at the beginning if they exist
2769    end
2770   
2771    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2772    % display menus and plot histograms
2773    test_v=0;
2774    if ~isempty(menu_histo)
2775        set(handles.histo1_menu,'Value',1)
2776        set(handles.histo1_menu,'String',menu_histo)
2777        histo1_menu_Callback(handles.histo1_menu, [], handles)% plot first histogram
2778    end
2779end
2780ResizeFcn(handles.uvmat,[],handles)
2781set(handles.uvmat,'Pointer',pointer)
2782
2783%------------------------------------------------------------------------
2784function histo1_menu_Callback(hObject, eventdata, handles)
2785%--------------------------------------------
2786histo_menu=get(handles.histo1_menu,'String');
2787histo_value=get(handles.histo1_menu,'Value');
2788FieldName=histo_menu{histo_value};
2789
2790UvData=get(handles.uvmat,'UserData');
2791Field=UvData.Field;
2792r=regexp(FieldName,'(?<var1>.*)(?<sep>,)(?<var2>.*)','names');
2793FieldName_2='';
2794if ~isempty(r)
2795    FieldName=r.var1;
2796    FieldName_2=r.var2;
2797end
2798if ~isfield(UvData.Field,FieldName)
2799    msgbox_uvmat('ERROR',['no field  ' FieldName ' for histogram'])
2800    return
2801end
2802FieldHisto=Field.(FieldName);
2803if isfield(Field,'FF') && ~isempty(Field.FF) && isequal(size(Field.FF),size(FieldHisto))
2804    indsel=find(Field.FF==0);%find values marked as false
2805    if ~isempty(indsel)
2806        FieldHisto=FieldHisto(indsel);
2807        if ~isempty(FieldName_2)
2808            FieldHisto(:,:,2)=Field.(FieldName_2)(indsel);
2809        end
2810    end
2811elseif ~isempty(FieldName_2)
2812    FieldHisto(:,:,2)=Field.(FieldName_2);
2813end
2814if isempty(Field)
2815    msgbox_uvmat('ERROR',['empty field ' FieldName])
2816else
2817    nxy=size(FieldHisto);
2818    Amin=double(min(min(min(FieldHisto))));%min of field value
2819    Amax=double(max(max(max(FieldHisto))));%max of field value
2820    if isequal(Amin,Amax)
2821        cla(handles.HistoAxes)
2822    else
2823        Histo.ListVarName={FieldName,'histo'};
2824        if isfield(Field,'NbDim') && isequal(Field.NbDim,3)
2825            Histo.VarDimName={FieldName,FieldName}; %dimensions for the histogram
2826        else
2827            if numel(nxy)==2
2828                Histo.VarDimName={FieldName,FieldName}; %dimensions for the histogram
2829            else
2830                Histo.VarDimName={FieldName,{FieldName,'component'}}; %dimensions for the histogram
2831            end
2832        end
2833        %unit
2834        units=[]; %default
2835        for ivar=1:numel(Field.ListVarName)
2836            if strcmp(Field.ListVarName{ivar},FieldName)
2837                if isfield(Field,'VarAttribute') && numel(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'units')
2838                    units=Field.VarAttribute{ivar}.units;
2839                    break
2840                end
2841            end
2842        end
2843        if ~isempty(units)
2844            Histo.VarAttribute{1}.units=units;
2845        end
2846        eval(['Histo.' FieldName '=linspace(Amin,Amax,50);'])%absissa values for histo
2847        if isfield(Field,'NbDim') && isequal(Field.NbDim,3)
2848            C=reshape(double(FieldHisto),1,[]);% reshape in a vector
2849            Histo.histo(:,1)=hist(C, Histo.(FieldName));  %calculate histogram
2850        else
2851            for col=1:size(FieldHisto,3)
2852                B=FieldHisto(:,:,col);
2853                C=reshape(double(B),1,nxy(1)*nxy(2));% reshape in a vector
2854                Histo.histo(:,col)=hist(C, Histo.(FieldName));  %calculate histogram
2855            end
2856        end
2857        plot_field(Histo,handles.HistoAxes);
2858        hlegend=legend;
2859        if isempty(FieldName_2)
2860        set(hlegend,'String',FieldName)
2861        else
2862            set(hlegend,'String',{FieldName;FieldName_2})
2863        end
2864    end
2865end
2866
2867%------------------------------------------------------------------------
2868% --- translate coordinate to matrix index
2869%------------------------------------------------------------------------
2870function [indx,indy]=pos2ind(x0,rangx0,nxy)
2871indx=1+round((nxy(2)-1)*(x0-rangx0(1))/(rangx0(2)-rangx0(1)));% index x of pixel 
2872indy=1+round((nxy(1)-1)*(y12-rangy0(1))/(rangy0(2)-rangy0(1)));% index y of pixel
2873
2874%------------------------------------------------------------------------
2875% --- Executes on button press in 'CheckZoom'.
2876%------------------------------------------------------------------------
2877function CheckZoom_Callback(hObject, eventdata, handles)
2878
2879    if get(handles.CheckZoom,'Value')
2880        set(handles.CheckFixLimits,'Value',1)% propose by default fixed limits for the plotting axes
2881        set(handles.CheckZoomFig,'Value',0)%desactivate zoom fig
2882    end
2883
2884
2885%------------------------------------------------------------------------
2886% --- Executes on button press in CheckZoomFig.
2887%------------------------------------------------------------------------
2888function CheckZoomFig_Callback(hObject, eventdata, handles)
2889
2890if get(handles.CheckZoomFig,'Value')
2891    set(handles.CheckZoom,'value',0)
2892end
2893
2894%------------------------------------------------------------------------
2895% --- Executes on button press in 'CheckFixLimits'.
2896%------------------------------------------------------------------------
2897function CheckFixLimits_Callback(hObject, eventdata, handles)
2898
2899if ~get(handles.CheckFixLimits,'Value')
2900    update_plot(handles)
2901    set(handles.CheckZoom,'Value',0)
2902end
2903
2904%------------------------------------------------------------------------
2905% --- Executes on button press in CheckFixAspectRatio.
2906function CheckFixAspectRatio_Callback(hObject, eventdata, handles)
2907%------------------------------------------------------------------------
2908
2909% if get(handles.CheckFixAspectRatio,'Value')
2910    update_plot(handles);
2911% else
2912%     update_plot(handles);
2913% end
2914
2915%------------------------------------------------------------------------
2916function num_AspectRatio_Callback(hObject, eventdata, handles)
2917%------------------------------------------------------------------------
2918set(handles.CheckFixAspectRatio,'Value',1)% select the fixed aspect ratio button
2919update_plot(handles);
2920
2921%------------------------------------------------------------------------
2922%----Executes on button press in 'record': records the current flags of manual correction.
2923%------------------------------------------------------------------------
2924function record_Callback(hObject, eventdata, handles)
2925
2926[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
2927FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
2928[erread,message]=fileattrib(FileName);
2929if ~isempty(message) && ~isequal(message.UserWrite,1)
2930     msgbox_uvmat('ERROR',['no writting access to ' FileName])
2931     return
2932end
2933MenuVelType=get(handles.VelType,'String');
2934test_civ2=strcmp(MenuVelType{get(handles.VelType,'Value')},'civ2');
2935test_civ1=strcmp(MenuVelType{get(handles.VelType,'Value')},'civ1');
2936if ~test_civ2 && ~test_civ1
2937    msgbox_uvmat('ERROR','manual correction only possible for CIV1 or CIV2 velocity fields')
2938end
2939if test_civ2
2940    nbname='nb_vec_2';
2941   flagname='Civ2_FF';
2942   CivStage=5;
2943end
2944if test_civ1
2945    nbname='nb_vec_1';
2946   flagname='Civ1_FF';
2947    CivStage=2;
2948end
2949%write fix flags in the netcdf file
2950UvData=get(handles.uvmat,'UserData');
2951hhh=which('netcdf.open');% look for built-in matlab netcdf library
2952if ~isequal(hhh,'')% case of  builtin Matlab netcdf library
2953    nc=netcdf.open(FileName,'NC_WRITE');
2954    netcdf.reDef(nc);
2955    netcdf.putAtt(nc,netcdf.getConstant('NC_GLOBAL'),'CivStage',CivStage);
2956    dimid = netcdf.inqDimID(nc,nbname);
2957    try
2958        varid = netcdf.inqVarID(nc,flagname);% look for already existing fixflag variable
2959    catch
2960        varid=netcdf.defVar(nc,flagname,'double',dimid);%create fixflag variable if it does not exist
2961    end
2962    netcdf.endDef(nc);
2963    netcdf.putVar(nc,varid,UvData.PlotAxes.FF);
2964    netcdf.close(nc); 
2965else %old netcdf library
2966    netcdf_toolbox(FileName,AxeData,attrname,nbname,flagname)
2967end
2968
2969%-------------------------------------------------------------------
2970%----Correct the netcdf file, using toolbox (old versions of Matlab).
2971%-------------------------------------------------------------------
2972function netcdf_toolbox(FileName,AxeData,attrname,nbname,flagname)
2973nc=netcdf(FileName,'write'); %open netcdf file
2974result=redef(nc);
2975eval(['nc.' attrname '=1;']);
2976theDim=nc(nbname) ;% get the number of velocity vectors
2977nb_vectors=size(theDim);
2978var_FixFlag=ncvar(flagname,nc);% var_FixFlag will be written as the netcdf variable vec_FixFlag
2979var_FixFlag(1:nb_vectors)=AxeData.FF;%
2980fin=close(nc);
2981
2982%-----------------------------------------------------------------------
2983% --- Executes on button press in SubField
2984%-----------------------------------------------------------------------
2985function SubField_Callback(hObject, eventdata, handles)
2986
2987if get(handles.SubField,'Value')==0% if the subfield button is desactivated 
2988    desable_subfield(handles)
2989    transform_fct_list=get(handles.TransformName,'String');
2990    transform_fct=transform_fct_list(get(handles.TransformName,'Value'));
2991    if strcmp(transform_fct,'sub_field')
2992        set(handles.TransformName,'Value',1)%suppress the sub_field transform
2993        TransformName_Callback(hObject, eventdata, handles);
2994    else
2995        REFRESH_Callback(hObject, eventdata, handles)
2996    end 
2997else
2998    fileinput_1=uigetfile_uvmat('select a second input file:',get(handles.RootPath,'String'));
2999    if isempty(fileinput_1)
3000        set(handles.SubField,'Value',0)
3001    else       
3002        % refresh the current displayed field
3003        display_file_name(handles,fileinput_1,2)
3004       
3005        %update list of recent files in the menubar
3006        MenuFile_1=fileinput_1;
3007        MenuFile_2=get(handles.MenuFile_1,'Label');
3008        MenuFile_3=get(handles.MenuFile_2,'Label');
3009        MenuFile_4=get(handles.MenuFile_3,'Label');
3010        MenuFile_5=get(handles.MenuFile_4,'Label');
3011        set(handles.MenuFile_1,'Label',MenuFile_1)
3012        set(handles.MenuFile_2,'Label',MenuFile_2)
3013        set(handles.MenuFile_3,'Label',MenuFile_3)
3014        set(handles.MenuFile_4,'Label',MenuFile_4)
3015        set(handles.MenuFile_5,'Label',MenuFile_5)
3016    end
3017end
3018
3019%-----------------------------------------------------------------------
3020% --- desactivate display used for a second file series
3021%-----------------------------------------------------------------------
3022function desable_subfield(handles)
3023   
3024set(handles.RootPath_1,'String','')
3025set(handles.RootFile_1,'String','')
3026set(handles.SubDir_1,'String','');
3027set(handles.FileIndex_1,'String','');
3028set(handles.FileExt_1,'String','');
3029set(handles.RootPath_1,'Visible','off')
3030set(handles.RootFile_1,'Visible','off')
3031set(handles.SubDir_1,'Visible','off');
3032set(handles.NomType_1,'Visible','off');
3033set(handles.FileIndex_1,'Visible','off');
3034set(handles.FileExt_1,'Visible','off');
3035set(handles.TimeName_1,'String','');
3036set(handles.TimeName_1,'Visible','off');
3037set(handles.TimeValue_1,'String','');
3038set(handles.TimeValue_1,'Visible','off');
3039set(handles.FieldName_1,'Value',1);%set to blank state
3040set(handles.VelType_1,'Value',1);%set to blank state
3041set(handles.num_Opacity,'String','')% desactivate opacity setting
3042FieldList=get(handles.FieldName,'String');
3043if numel(FieldList)>1   % if a choice of fields exists
3044    set(handles.FieldName_1,'Value',1)% set second field choice to blank
3045    set(handles.FieldName_1,'String',[{''};FieldList])% reproduce the menu FieldName plus a blank option
3046else
3047    set(handles.FieldName_1,'String',{''})% set second field choice to blank
3048end
3049if ~strcmp(get(handles.VelType,'Visible'),'on')
3050    set(handles.VelType_1,'Visible','off')
3051end
3052UvData=get(handles.uvmat,'UserData');
3053if isfield(UvData,'XmlData_1')
3054    UvData=rmfield(UvData,'XmlData_1');
3055end
3056set(handles.uvmat,'UserData',UvData);
3057
3058%------------------------------------------------------------------------
3059% --- read the data displayed for the input rootfile windows (new): TODO use read_GUI
3060%------------------------------------------------------------------------
3061function [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles)
3062
3063InputFile=read_GUI(handles.InputFile);
3064RootPath=InputFile.RootPath;
3065SubDir=regexprep(InputFile.SubDir,'/|\','');
3066RootFile=regexprep(InputFile.RootFile,'/|\','');
3067FileIndices=InputFile.FileIndex;
3068FileExt=InputFile.FileExt;
3069
3070
3071%------------------------------------------------------------------------
3072% ---- read the data displayed for the second input rootfile windows
3073%------------------------------------------------------------------------
3074function [RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1,NomType_1]=read_file_boxes_1(handles)
3075
3076RootPath_1=get(handles.RootPath_1,'String'); % read the data from the file1_input window
3077if isequal(get(handles.RootPath_1,'Visible'),'off') || isequal(RootPath_1,'"')
3078    RootPath_1=get(handles.RootPath,'String');
3079end;
3080SubDir_1=get(handles.SubDir_1,'String');
3081if isequal(get(handles.SubDir_1,'Visible'),'off')|| isequal(SubDir_1,'"')
3082    SubDir_1=get(handles.SubDir,'String');
3083end
3084SubDir_1=regexprep(SubDir_1,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3085RootFile_1=get(handles.RootFile_1,'String');
3086if isequal(get(handles.RootFile_1,'Visible'),'off') || isequal(RootFile_1,'"')
3087    RootFile_1=get(handles.RootFile,'String');
3088end
3089RootFile_1=regexprep(RootFile_1,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3090FileIndex_1=get(handles.FileIndex_1,'String');
3091if isequal(get(handles.FileIndex_1,'Visible'),'off')|| isequal(FileIndex_1,'"')
3092    FileIndex_1=get(handles.FileIndex,'String');
3093end
3094FileExt_1=get(handles.FileExt_1,'String');
3095if isequal(get(handles.FileExt_1,'Visible'),'off') || isequal(FileExt_1,'"')
3096    FileExt_1=get(handles.FileExt,'String');%read FileExt by default
3097end
3098NomType_1=get(handles.NomType_1,'String');
3099if isequal(get(handles.NomType_1,'Visible'),'off') || isequal(NomType_1,'"')
3100    NomType_1=get(handles.NomType,'String');%read FileExt by default
3101end
3102%------------------------------------------------------------------------
3103% --- Executes on menu selection FieldName
3104function FieldName_Callback(hObject, eventdata, handles)
3105%------------------------------------------------------------------------
3106
3107%% read data from uvmat
3108UvData=get(handles.uvmat,'UserData');
3109list_fields=get(handles.FieldName,'String');% list menu fields
3110index_fields=get(handles.FieldName,'Value');% selected string index
3111field= list_fields{index_fields(1)}; % selected string
3112[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
3113FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3114[tild,tild,tild,i1,i2,j1,j2,tild,NomType]=fileparts_uvmat(['xxx' get(handles.FileIndex,'String') FileExt]);
3115
3116switch field
3117   
3118    case 'get_field...'
3119        %% fill the coordinates and variables from selections in get_field
3120        ParamIn=[];
3121        % in case of civ data, we use the civ choice as default input for the GUI get_field
3122        if strcmp(get(handles.VelType,'Visible'),'on')
3123            ParamIn.SwitchVarIndexTime='attribute';
3124            ListVelType=get(handles.VelType,'String');
3125            VelType=ListVelType{get(handles.VelType,'Value')};
3126            switch VelType
3127                case 'civ1'
3128                    ParamIn.TimeAttrName='Civ1_Time';
3129                    ParamIn.vector_x='Civ1_U';
3130                    ParamIn.vector_y='Civ1_V';
3131                    ParamIn.vec_color='Civ1_C';
3132                case 'filter1'
3133                    ParamIn.TimeAttrName='Civ1_Time';
3134                    ParamIn.vector_x='Civ1_U_smooth';
3135                    ParamIn.vector_y='Civ1_V_smooth';
3136                case 'civ2'
3137                    ParamIn.TimeAttrName='Civ2_Time';
3138                    ParamIn.vector_x='Civ2_U';
3139                    ParamIn.vector_y='Civ2_V';
3140                case 'filter2'
3141                    ParamIn.TimeAttrName='Civ2_Time';
3142                    ParamIn.vector_x='Civ2_U_smooth';
3143                    ParamIn.vector_y='Civ2_V_smooth';
3144                    ParamIn.vec_color='Civ2_C';
3145            end
3146        end
3147       
3148        % VelType menu desactivated
3149        set(handles.FixVelType,'visible','off')
3150        set(handles.VelType,'Visible','off')
3151       
3152        %read selection from get_field
3153        [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
3154        FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3155        GetFieldData=get_field(FileName,ParamIn);% inport field names from the GUI get_field
3156        FieldList={};
3157        VecColorList={''};
3158        switch GetFieldData.FieldOption
3159            case 'vectors'
3160                UName=GetFieldData.PanelVectors.vector_x;
3161                VName=GetFieldData.PanelVectors.vector_y;
3162                YName={GetFieldData.Coordinates.Coord_y};
3163                CName=GetFieldData.PanelVectors.vec_color;
3164                FieldList={['vec(' UName ',' VName ')'];...
3165                    ['norm(' UName ',' VName ')'];...
3166                    UName;VName};
3167                VecColorList={['norm(' UName ',' VName ')'];...
3168                    UName;VName};
3169                if ~isempty(CName)
3170                    VecColorList=[{CName};VecColorList];
3171                end
3172            case 'scalar'
3173                AName=GetFieldData.PanelScalar.scalar;
3174                YName={GetFieldData.Coordinates.Coord_y};
3175                FieldList={AName};
3176            case '1D plot'
3177                YName=GetFieldData.PanelOrdinate.ordinate;
3178            case 'civdata...'%reinitiate input, return to automatic civ data reading
3179                display_file_name(handles,FileName,1)
3180        end
3181        if ~strcmp(GetFieldData.FieldOption,'civdata...')
3182            XName=GetFieldData.Coordinates.Coord_x;
3183            TimeNameStr=GetFieldData.Time.SwitchVarIndexTime;
3184            switch TimeNameStr
3185                case 'file index'
3186                    set(handles.TimeName,'String','');
3187                case 'attribute'
3188                    set(handles.TimeName,'String',['att:' GetFieldData.Time.TimeName]);
3189                case 'variable'
3190                    set(handles.TimeName,'String',['var:' GetFieldData.Time.TimeName])
3191                    set(handles.NomType,'String','*')
3192                    set(handles.RootFile,'String',[get(handles.RootFile,'String') get(handles.FileIndex,'String')])
3193                    set(handles.FileIndex,'String','')
3194                    ParamIn.TimeVarName=GetFieldData.Time.TimeName;
3195                case 'matrix_index'
3196                    set(handles.TimeName,'String',['dim:' GetFieldData.Time.TimeName]);
3197                    set(handles.NomType,'String','*')
3198                    set(handles.RootFile,'String',[get(handles.RootFile,'String') get(handles.FileIndex,'String')])
3199                    set(handles.FileIndex,'String','')
3200                    ParamIn.TimeDimName=GetFieldData.Time.TimeName;
3201            end
3202            set(handles.Coord_x,'String',XName)
3203            if ischar(YName)
3204                YName={YName};
3205            end
3206            set(handles.Coord_y,'Data',YName)
3207            set(handles.FieldName,'Value',1)
3208            set(handles.FieldName,'String',[FieldList; {'get_field...'}]);
3209            set(handles.ColorScalar,'Value',1)
3210            set(handles.ColorScalar,'String',VecColorList);
3211            UvData.FileType{1}='netcdf';
3212            set(handles.uvmat,'UserData',UvData)
3213            REFRESH_Callback(hObject, eventdata, handles)
3214        end
3215       
3216    case 'image'
3217        %% look for image corresponding to civ data
3218        if  isfield(UvData.Field,'Civ2_ImageA')%get the corresponding input image in the netcdf file
3219            imagename=UvData.Field.Civ2_ImageA;
3220        elseif isfield(UvData.Field,'Civ1_ImageA')%
3221            imagename=UvData.Field.Civ1_ImageA;
3222        else
3223            SubDirBase=regexprep(SubDir,'\..*','');%take the root part of SubDir, before the first dot '.'
3224            imagename=fullfile_uvmat(RootPath,SubDirBase,RootFile,'.png',NomType,i1,[],j1,[]);
3225        end
3226        if ~exist(imagename,'file')
3227            imagename=uigetfile_uvmat('Pick an image file',imagename,'image');
3228            if isempty(imagename)
3229                return
3230            end
3231        end
3232        % display the selected field and related information
3233        display_file_name(handles,imagename)%display the image
3234    otherwise
3235        REFRESH_Callback(hObject, eventdata, handles)
3236end
3237
3238%----------------------------------------------------------------
3239% --- Executes on menu selection FieldName
3240function FieldName_1_Callback(hObject, eventdata, handles)
3241%-------------------------------------------------
3242
3243%%%%%% TODO: modify like FieldName_Callback
3244%% read input data
3245check_new=~get(handles.SubField,'Value'); %check_new=1 if a second field was not previously entered
3246UvData=get(handles.uvmat,'UserData');
3247if check_new && isfield(UvData,'XmlData')
3248    UvData.XmlData{2}=UvData.XmlData{1};
3249end
3250if isfield(UvData,'Field_1')
3251    UvData=rmfield(UvData,'Field_1');% remove the stored second field (a new one needs to be read)
3252end
3253UvData.FileName_1='';% desactivate the use of a constant second file
3254list_fields=get(handles.FieldName,'String');% list menu fields
3255field= list_fields{get(handles.FieldName,'Value')}; % selected string
3256list_fields=get(handles.FieldName_1,'String');% list menu fields
3257field_1= list_fields{get(handles.FieldName_1,'Value')}; % selected string for the second field
3258if isempty(field_1)%||(numel(UvData.FileType)>=2 && strcmp(UvData.FileType{2},'image'))
3259    set(handles.SubField,'Value',0)
3260    SubField_Callback(hObject, eventdata, handles)
3261    return
3262else
3263    set(handles.SubField,'Value',1)%state that a second field is now entered
3264end
3265
3266%% read the rootfile input display
3267[RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
3268FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];
3269[tild,tild,tild,i1,i2,j1,j2]=fileparts_uvmat(get(handles.FileIndex,'String'));
3270switch field_1
3271    case 'get_field...'
3272         %% fill the coordinates and variables from selections in get_field
3273        ParamIn=[];
3274        % in case of civ data, we use the civ choice as default input for the GUI get_field
3275        if strcmp(get(handles.VelType_1,'Visible'),'on')
3276            ParamIn.SwitchVarIndexTime='attribute';
3277            ListVelType=get(handles.VelType_1,'String');
3278            VelType=ListVelType{get(handles.VelType_1,'Value')};
3279            switch VelType
3280                case 'civ1'
3281                    ParamIn.TimeAttrName='Civ1_Time';
3282                    ParamIn.vector_x='Civ1_U';
3283                    ParamIn.vector_y='Civ1_V';
3284                    ParamIn.vec_color='Civ1_C';
3285                case 'filter1'
3286                    ParamIn.TimeAttrName='Civ1_Time';
3287                    ParamIn.vector_x='Civ1_U_smooth';
3288                    ParamIn.vector_y='Civ1_V_smooth';
3289                case 'civ2'
3290                    ParamIn.TimeAttrName='Civ2_Time';
3291                    ParamIn.vector_x='Civ2_U';
3292                    ParamIn.vector_y='Civ2_V';
3293                case 'filter2'
3294                    ParamIn.TimeAttrName='Civ2_Time';
3295                    ParamIn.vector_x='Civ2_U_smooth';
3296                    ParamIn.vector_y='Civ2_V_smooth';
3297                    ParamIn.vec_color='Civ2_C';
3298            end
3299        end
3300       
3301        % VelType menu desactivated
3302        set(handles.FixVelType,'visible','off')
3303        set(handles.VelType,'Visible','off')
3304       
3305        %read selection from get_field
3306        [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes_1(handles);
3307        FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3308        GetFieldData=get_field(FileName,ParamIn);% inport field names from the GUI get_field
3309        FieldList={};
3310        VecColorList={};
3311        switch GetFieldData.FieldOption
3312            case 'vectors'
3313                UName=GetFieldData.PanelVectors.vector_x;
3314                VName=GetFieldData.PanelVectors.vector_y;
3315                YName={GetFieldData.Coordinates.Coord_y};
3316                CName=GetFieldData.PanelVectors.vec_color;
3317                FieldList={['vec(' UName ',' VName ')'];...
3318                    ['norm(' UName ',' VName ')'];...
3319                    UName;VName};
3320                VecColorList={['norm(' UName ',' VName ')'];...
3321                    UName;VName};
3322                if ~isempty(CName)
3323                    VecColorList=[{CName};VecColorList];
3324                end
3325            case 'scalar'
3326                AName=GetFieldData.PanelScalar.scalar;
3327                YName={GetFieldData.Coordinates.Coord_y};
3328                FieldList={AName};
3329            case '1D plot'
3330                YName=GetFieldData.PanelOrdinate.ordinate;
3331            case 'civdata...'%reinitiate input, return to automatic civ data reading
3332                display_file_name(handles,FileName,1)
3333        end
3334        if ~strcmp(GetFieldData.FieldOption,'civdata...')
3335            XName=GetFieldData.Coordinates.Coord_x;
3336            TimeNameStr=GetFieldData.Time.SwitchVarIndexTime;
3337            switch TimeNameStr
3338                case 'file index'
3339                    set(handles.TimeName_1,'String','');
3340                case 'attribute'
3341                    set(handles.TimeName_1,'String',['att:' GetFieldData.Time.TimeName]);
3342                case 'variable'
3343                    set(handles.TimeName_1,'String',['var:' GetFieldData.Time.TimeName])
3344                    set(handles.NomType_1,'String','*')
3345                    set(handles.RootFile_1,'String',[get(handles.RootFile,'String') get(handles.FileIndex,'String')])
3346                    set(handles.FileIndex_1,'String','')
3347                    ParamIn.TimeVarName=GetFieldData.Time.TimeName;
3348                case 'matrix_index'
3349                    set(handles.TimeName_1,'String',['dim:' GetFieldData.Time.TimeName]);
3350                    set(handles.NomType_1,'String','*')
3351                    set(handles.RootFile_1,'String',[get(handles.RootFile,'String') get(handles.FileIndex,'String')])
3352                    set(handles.FileIndex_1,'String','')
3353                    ParamIn.TimeDimName_1=GetFieldData.Time.TimeName;
3354            end
3355            set(handles.Coord_x,'String',XName)
3356            if ischar(YName)
3357                YName={YName};
3358            end
3359            set(handles.Coord_y,'Data',YName)
3360            set(handles.FieldName_1,'Value',1)
3361            set(handles.FieldName_1,'String',[FieldList; {'get_field...'}]);
3362            set(handles.ColorScalar,'Value',1)
3363            set(handles.ColorScalar,'String',VecColorList);
3364            UvData.FileType{2}='netcdf';
3365            set(handles.uvmat,'UserData',UvData)
3366            REFRESH_Callback(hObject, eventdata, handles)
3367        end
3368         
3369%         set_veltype_display(0) % no veltype display
3370%         hget_field=findobj(allchild(0),'name','get_field_1');
3371%         if ~isempty(hget_field)
3372%             delete(hget_field)
3373%         end
3374%         hget_field=get_field(FileName_1);
3375%         set(hget_field,'name','get_field_1')
3376%         hhget_field=guidata(hget_field);
3377%         set(hhget_field.list_fig,'Value',1)
3378%         set(hhget_field.list_fig,'String',{'uvmat'})
3379%         if check_new
3380%             UvData.FileType{2}=UvData.FileType{1};
3381%             set(handles.FileIndex_1,'String',get(handles.FileIndex,'String'))
3382%               set(handles.uvmat,'UserData',UvData)
3383%         end
3384    case 'image'
3385        %% look for image corresponding to civ data
3386        imagename='';
3387        if  isfield(UvData.Field,'Civ2_ImageA')%get the corresponding input image in the netcdf file
3388            imagename=UvData.Field.Civ2_ImageA;
3389        elseif isfield(UvData.Field,'Civ1_ImageA')%
3390            imagename=UvData.Field.Civ1_ImageA;
3391        else
3392            SubDirBase=regexprep(SubDir,'\..*','');%take the root part of SubDir, before the first dot '.'
3393            imagename=fullfile_uvmat(RootPath,SubDirBase,RootFile,'.png',NomType,i1,[],j1,[]);
3394        end
3395        if ~exist(imagename,'file')
3396            imagename=uigetfile_uvmat('Pick an image file',imagename,'image');
3397           
3398        end
3399        if isempty(imagename)
3400            set(handles.SubField,'Value',0)
3401            return
3402        else
3403            display_file_name(handles,imagename,2)%display the image as second field
3404        end
3405    otherwise
3406        check_refresh=1;
3407        if check_new% if a second field was not previously entered, we just read another field in the first input file
3408            set(handles.FileIndex_1,'String',get(handles.FileIndex,'String'))
3409            set(handles.FileExt_1,'String',get(handles.FileExt,'String'))
3410           
3411            UvData.FileType{2}=UvData.FileType{1};
3412            UvData.XmlData{2}= UvData.XmlData{1};
3413            transform=get(handles.TransformPath,'UserData');
3414             if (~isa(transform,'function_handle')||nargin(transform)<3)
3415                set(handles.uvmat,'UserData',UvData)
3416                set(handles.TransformName,'value',2); % set transform fct to 'sub_field' if the current fct does not accept two input fields
3417                TransformName_Callback(hObject, eventdata, handles)% activate transform_fct_Callback and refresh current plot
3418                 check_refresh=0;
3419             end             
3420        end
3421        if ~isequal(field,'image')
3422            set(handles.TitleNpxy,'Visible','off')% visible npx,pxcm... buttons
3423            set(handles.num_Npx,'Visible','off')
3424            set(handles.num_Npy,'Visible','off')
3425        end
3426        set(handles.uvmat,'UserData',UvData)
3427 
3428        if check_refresh && ~(isfield(UvData,'NewSeries')&&isequal(UvData.NewSeries,1))
3429            REFRESH_Callback(hObject, eventdata, handles)
3430        end
3431end
3432
3433%------------------------------------------------------------------------
3434% --- set the visibility of relevant velocity type menus:
3435function menu=set_veltype_display(Civ,FileType)
3436%------------------------------------------------------------------------
3437if ~exist('FileType','var')
3438    FileType='civx';
3439end
3440switch FileType
3441    case 'civx'
3442        menu={'civ1';'interp1';'filter1';'civ2';'interp2';'filter2'};
3443        if isequal(Civ,0)
3444            imax=0;
3445        elseif isequal(Civ,1) || isequal(Civ,2)
3446            imax=1;
3447        elseif isequal(Civ,3)
3448            imax=3;
3449        elseif isequal(Civ,4) || isequal(Civ,5)
3450            imax=4;
3451        elseif isequal(Civ,6) %patch2
3452            imax=6;
3453        end
3454    case 'civdata'
3455        menu={'civ1';'filter1';'civ2';'filter2'};
3456        if isequal(Civ,0)
3457            imax=0;
3458        elseif isequal(Civ,1) || isequal(Civ,2)
3459            imax=1;
3460        elseif isequal(Civ,3)
3461            imax=2;
3462        elseif isequal(Civ,4) || isequal(Civ,5)
3463            imax=3;
3464        elseif isequal(Civ,6) %patch2
3465            imax=4;
3466        end
3467end
3468menu=menu(1:imax);
3469
3470%------------------------------------------------------------------------
3471% --- Executes on button press in FixVelType.
3472function FixVelType_Callback(hObject, eventdata, handles)
3473%------------------------------------------------------------------------
3474% inputfilerefresh the current plot if the fixed  veltype is unselected
3475if ~get(handles.FixVelType,'Value')
3476    REFRESH_Callback(hObject, eventdata, handles)
3477end
3478
3479%------------------------------------------------------------------------
3480% --- Executes on button press in VelType.
3481function VelType_Callback(hObject, eventdata, handles)
3482%------------------------------------------------------------------------
3483set(handles.FixVelType,'Value',1)
3484REFRESH_Callback(hObject, eventdata, handles)
3485
3486%------------------------------------------------------------------------
3487% --- Executes on choice selection in VelType_1.
3488function VelType_1_Callback(hObject, eventdata, handles)
3489%------------------------------------------------------------------------
3490set(handles.FixVelType,'Value',1)% the velocity type is now imposed by the GUI (not automatic)
3491UvData=get(handles.uvmat,'UserData');
3492set(handles.InputFileREFRESH,'BackgroundColor',[1 1 0])%paint REFRESH button in yellow to indicate its activation
3493drawnow   
3494InputFile=read_GUI(handles.InputFile);% read the input file parameters
3495[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
3496[RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
3497FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];% name of the first input file
3498
3499check_refresh=0;
3500if isempty(InputFile.VelType_1)
3501        FileName_1='';% we plot the first input field without the second field
3502        set(handles.SubField,'Value',0)
3503        SubField_Callback(hObject, eventdata, handles)% activate SubField_Callback and refresh current plot, removing the second field
3504elseif get(handles.SubField,'Value')% if subfield is already 'on'
3505     FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];% name of the second input file
3506     check_refresh=1;%will refresh the current plot
3507else% we introduce the same file (with a different field) for the second series
3508     FileName_1=FileName;% we compare two fields in the same file
3509     UvData.FileType{2}=UvData.FileType{1};
3510     UvData.XmlData{2}= UvData.XmlData{1};
3511     set(handles.SubField,'Value',1)
3512     transform=get(handles.TransformPath,'UserData');
3513     if (~isa(transform,'function_handle')||nargin(transform)<3)
3514        set(handles.uvmat,'UserData',UvData)
3515        set(handles.TransformName,'value',2); % set transform fct to 'sub_field' if the current fct does not accept two input fields
3516        TransformName_Callback(hObject, eventdata, handles)% activate transform_fct_Callback and refresh current plot
3517     else
3518         check_refresh=1;
3519     end 
3520end
3521
3522% inputfilerefresh the current plot if it has not been done previously
3523if check_refresh
3524    UvData.FileName_1='';% desactivate the use of a constant second file
3525    set(handles.uvmat,'UserData',UvData)
3526    num_i1=stra2num(get(handles.i1,'String'));
3527    num_i2=stra2num(get(handles.i2,'String'));
3528    num_j1=stra2num(get(handles.j1,'String'));
3529    num_j2=stra2num(get(handles.j2,'String'));
3530    [tild,tild,tild,i1_1,i2_1,j1_1,j2_1]=fileparts_uvmat(['xx' FileIndex_1]);
3531    errormsg=refresh_field(handles,FileName,FileName_1,num_i1,num_i2,num_j1,num_j2,i1_1,i2_1,j1_1,j2_1);
3532    if ~isempty(errormsg)
3533        msgbox_uvmat('ERROR',errormsg);
3534    else
3535        set(handles.i1,'BackgroundColor',[1 1 1])
3536        set(handles.i2,'BackgroundColor',[1 1 1])
3537        set(handles.j1,'BackgroundColor',[1 1 1])
3538        set(handles.j2,'BackgroundColor',[1 1 1])
3539        set(handles.FileIndex,'BackgroundColor',[1 1 1])
3540        set(handles.FileIndex_1,'BackgroundColor',[1 1 1])
3541    end
3542    set(handles.InputFileREFRESH,'BackgroundColor',[1 0 0])
3543end
3544
3545
3546%------------------------------------------------------------------------
3547% --- reset civ buttons
3548function reset_vel_type(handles_civ0,handle1)
3549%------------------------------------------------------------------------
3550for ibutton=1:length(handles_civ0)
3551    set(handles_civ0(ibutton),'BackgroundColor',[0.831 0.816 0.784])
3552    set(handles_civ0(ibutton),'Value',0)
3553end
3554if exist('handle1','var')%handles of selected button
3555        set(handle1,'BackgroundColor',[1 1 0]) 
3556end
3557
3558%-----------------------------------------------------------------------
3559% --- Executes on button press in MENUVOLUME.
3560function VOLUME_Callback(hObject, eventdata, handles)
3561%-----------------------------------------------------------------------
3562%errordlg('command VOL not implemented yet')
3563if ishandle(handles.UVMAT_title)
3564    delete(handles.UVMAT_title)
3565end
3566UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
3567if isequal(get(handles.VOLUME,'Value'),1)
3568    set(handles.CheckZoom,'Value',0)
3569%     set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
3570    set(handles.edit_vect,'Value',0)
3571    edit_vect_Callback(hObject, eventdata, handles)
3572    set(handles.CheckEditObject,'Value',0)
3573%     set(handles.CheckEditObject,'BackgroundColor',[0.7 0.7 0.7])
3574%     set(handles.cal,'Value',0)
3575%     set(handles.cal,'BackgroundColor',[0 1 0])
3576    set(handles.edit_vect,'Value',0)
3577    edit_vect_Callback(hObject, eventdata, handles)
3578    %initiate set_object GUI
3579    data.Name='VOLUME';
3580    if isfield(UvData,'CoordType')
3581        data.CoordType=UvData.CoordType;
3582    end
3583    if isfield(UvData.Field,'CoordMesh')&~isempty(UvData.Field.CoordMesh)
3584        data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
3585        data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
3586        data.DX=UvData.Field.CoordMesh;
3587        data.DY=UvData.Field.CoordMesh;
3588    elseif isfield(UvData.Field,'AX')&isfield(UvData.Field,'AY')& isfield(UvData.Field,'A')%only image
3589        np=size(UvData.Field.A);
3590        meshx=(UvData.Field.AX(end)-UvData.Field.AX(1))/np(2);
3591        meshy=abs(UvData.Field.AY(end)-UvData.Field.AY(1))/np(1);
3592        data.RangeY=max(meshx,meshy);
3593        data.RangeX=max(meshx,meshy);
3594        data.DX=max(meshx,meshy);
3595    end
3596    data.ParentButton=handles.VOLUME;
3597    PlotHandles=get_plot_handles(handles);%get the handles of the interface elements setting the plotting parameters
3598    [hset_object,UvData.sethandles]=set_object(data,PlotHandles);% call the set_object interface with action on haxes,
3599                                                      % associate the set_object interface handle to the plotting axes
3600    set(hset_object,'name','set_object')
3601    UvData.MouseAction='create_object';
3602else
3603    set(handles.VOLUME,'BackgroundColor',[0 1 0])
3604end
3605set(handles.uvmat,'UserData',UvData)
3606
3607%-------------------------------------------------------
3608function edit_vect_Callback(hObject, eventdata, handles)
3609%-------------------------------------------------------
3610%
3611if isequal(get(handles.edit_vect,'Value'),1)
3612    VelTypeMenu=get(handles.VelType,'String');
3613    VelType=VelTypeMenu{get(handles.VelType,'Value')};
3614    if ~strcmp(VelType,'civ2') && ~strcmp(VelType,'civ1')
3615        msgbox_uvmat('ERROR','manual correction only possible for CIV1 or CIV2 velocity fields')
3616    end
3617    set(handles.record,'Visible','on')
3618    set(handles.edit_vect,'BackgroundColor',[1 1 0])
3619    set(handles.CheckEditObject,'Value',0)
3620    set(handles.CheckZoom,'Value',0)
3621    set(gcf,'Pointer','arrow')
3622else
3623    set(handles.record,'Visible','off')
3624    set(handles.edit_vect,'BackgroundColor',[0.7 0.7 0.7])
3625end
3626
3627%----------------------------------------------
3628function save_mask_Callback(hObject, eventdata, handles)
3629%-----------------------------------------------------------------------
3630UvData=get(handles.uvmat,'UserData');
3631
3632flag=1;
3633npx=size(UvData.Field.A,2);
3634npy=size(UvData.Field.A,1);
3635xi=0.5:npx-0.5;
3636yi=0.5:npy-0.5;
3637[Xi,Yi]=meshgrid(xi,yi);
3638if isfield(UvData,'ProjObject')
3639    for iobj=1:length(UvData.ProjObject)
3640        ObjectData=UvData.ProjObject{iobj};
3641        if isfield(ObjectData,'ProjMode') &&(isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside'));
3642            flagobj=1;
3643            testphys=0; %coordinates in pixels by default
3644            if isfield(ObjectData,'CoordType') && isequal(ObjectData.CoordType,'phys')
3645                if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
3646                    Calib=UvData.XmlData{1}.GeometryCalib;
3647                    testphys=1;
3648                end
3649            end
3650            if isfield(ObjectData,'Coord')& isfield(ObjectData,'Style')
3651                if isequal(ObjectData.Type,'polygon')
3652                    X=ObjectData.Coord(:,1);
3653                    Y=ObjectData.Coord(:,2);
3654                    if testphys
3655                        [X,Y]=px_XYZ(Calib,X,Y,0);% to generalise with 3D cases
3656                    end
3657                    flagobj=~inpolygon(Xi,Yi,X',Y');%=0 inside the polygon, 1 outside                 
3658                elseif isequal(ObjectData.Type,'ellipse')
3659                    if testphys
3660                        %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
3661                    end
3662                    RangeX=max(ObjectData.RangeX);
3663                    RangeY=max(ObjectData.RangeY);
3664                    X2Max=RangeX*RangeX;
3665                    Y2Max=RangeY*RangeY;
3666                    distX=(Xi-ObjectData.Coord(1,1));
3667                    distY=(Yi-ObjectData.Coord(1,2));
3668                    flagobj=(distX.*distX/X2Max+distY.*distY/Y2Max)>1;
3669                elseif isequal(ObjectData.Type,'rectangle')
3670                    if testphys
3671                        %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
3672                    end
3673                    distX=abs(Xi-ObjectData.Coord(1,1));
3674                    distY=abs(Yi-ObjectData.Coord(1,2));
3675                    flagobj=distX>max(ObjectData.RangeX) | distY>max(ObjectData.RangeY);
3676                end
3677                if isequal(ObjectData.ProjMode,'mask_outside')
3678                    flagobj=~flagobj;
3679                end
3680                flag=flag & flagobj;
3681            end
3682        end
3683    end
3684end
3685% flag=~flag;
3686%mask name
3687RootPath=get(handles.RootPath,'String');
3688RootFile=get(handles.RootFile,'String');
3689RootFile=regexprep(RootFile,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3690filebase=fullfile(RootPath,RootFile);
3691list=get(handles.masklevel,'String');
3692masknumber=num2str(length(list));
3693maskindex=get(handles.masklevel,'Value');
3694mask_name=fullfile_uvmat(RootPath,SubDir,[RootFile '_' masknumber 'mask'],'.png','_1',maskindex);
3695%mask_name=name_generator([filebase '_' masknumber 'mask'],maskindex,1,'.png','_i');
3696imflag=uint8(255*(0.392+0.608*flag));% =100 for flag=0 (vectors not computed when 20<imflag<200)
3697imflag=flipdim(imflag,1);
3698% imflag=uint8(255*flag);% =0 for flag=0 (vectors=0 when 20<imflag<200)
3699msgbox_uvmat('CONFIRMATION',[mask_name ' saved'])
3700imwrite(imflag,mask_name,'BitDepth',8);
3701
3702%display the mask
3703figure;
3704vec=linspace(0,1,256);%define a linear greyscale colormap
3705map=[vec' vec' vec'];
3706colormap(map)
3707
3708image(imflag);
3709
3710%------------------------------------------------------------------------
3711%------------------------------------------------------------------------
3712%  - FUNCTIONS FOR SETTING PLOTTING PARAMETERS
3713
3714%------------------------------------------------------------------------
3715%------------------------------------------------------------------------
3716% --- Executes on selection change in TransformName.
3717
3718function TransformName_Callback(hObject, eventdata, handles)
3719%------------------------------------------------------------------------
3720set(handles.TransformName,'backgroundColor',[1 1 0])% indicate activation  of the menu
3721drawnow
3722UvData=get(handles.uvmat,'UserData');
3723menu=get(handles.TransformName,'String');%refresh
3724ichoice=get(handles.TransformName,'Value');%item number in the menu
3725transform_name=menu{ichoice};% choice of the transform fct
3726list_path=get(handles.TransformName,'UserData');
3727
3728%% handles  visibility of the path to the transform function
3729if isempty(transform_name)
3730    set(handles.TransformPath,'Visible','off')
3731else
3732    set(handles.TransformPath,'Visible','on')
3733end
3734
3735%% add a new item to the menu if the option 'more...' has been selected
3736prev_path=fullfile(get(handles.TransformPath,'String'));
3737if ~exist(prev_path,'dir')
3738    prev_path=fullfile(fileparts(which('uvmat')),'transform_field');
3739end
3740if strcmp(transform_name,'more...');
3741    transform_fct_chosen=uigetfile_uvmat('Pick the transform function',prev_path,'.m');
3742    if ~isempty(transform_fct_chosen)
3743        [PathName,transform_name]=fileparts(transform_fct_chosen);
3744        ichoice=find(strcmp(transform_name,menu),1);%look for the selected fct in the existing menu
3745        if isempty(ichoice)% if the item is not found, add it to the menu (before 'more...' and select it)
3746            menu=[menu(1:end-1);{transform_name};{'more...'}];
3747            ichoice=numel(menu)-1;
3748        end
3749        list_path{ichoice}=PathName;%update the list fo fct paths
3750        set(handles.TransformName,'String',menu)
3751        set(handles.TransformName,'Value',ichoice)
3752       
3753        % save the new menu in the personal file 'uvmat_perso.mat'
3754        dir_perso=prefdir;%personal Matalb directory
3755        profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
3756        if exist(profil_perso,'file')
3757            nb_builtin=UvData.OpenParam.NbBuiltin;% number of 'builtin' (basic) transform fcts in uvmat
3758            if nb_builtin<numel(list_path)
3759                for ilist=nb_builtin+1:numel(list_path)
3760                    transform_fct{ilist-nb_builtin}=[fullfile(list_path{ilist},menu{ilist}) '.m'];
3761                end
3762                save (profil_perso,'transform_fct','-append'); %store the root name for future opening of uvmat
3763            end
3764        end
3765    end
3766end
3767
3768%% create the function handle of the selected fct
3769if isempty(list_path{ichoice})% case of no selected fct
3770    transform_handle=[];
3771else
3772    if ~exist(list_path{ichoice},'dir')
3773        msgbox_uvmat('ERROR','invalid fct path: select the transform fct again with the option more...')
3774        return
3775    end
3776    current_dir=pwd;%current working dir
3777    cd(list_path{ichoice})
3778    transform_handle=str2func(transform_name);
3779    cd(current_dir)
3780end
3781set(handles.TransformPath,'String',list_path{ichoice})
3782set(handles.TransformPath,'UserData',transform_handle)
3783set(handles.TransformName,'UserData',list_path)
3784
3785%% update the ToolTip string of the menu TransformName with the first line of the selected fct file
3786if isempty(list_path{ichoice})% case of no selected fct
3787    set(handles.TransformName,'ToolTipString','transform_fct:choose a transform function')
3788else
3789    try
3790        [fid,errormsg] =fopen([fullfile(list_path{ichoice},transform_name) '.m']);
3791        InputText=textscan(fid,'%s',1,'delimiter','\n');
3792        fclose(fid);
3793        set(handles.TransformName,'ToolTipString',['transform_fct: ' InputText{1}{1}])% put the first line of the selected function as tooltip help
3794    end
3795end
3796
3797%% adapt the GUI to the input/output conditions of the selected transform fct
3798DataOut=[];
3799CoordUnit='';
3800CoordUnitPrev='';
3801if isfield(UvData,'Field')&&isfield(UvData.Field,'CoordUnit')
3802    CoordUnitPrev=UvData.Field.CoordUnit;
3803end
3804if ~isempty(list_path{ichoice})
3805    if nargin(transform_handle)>1 && isfield(UvData,'XmlData')&&~isempty(UvData.XmlData)
3806        %XmlData=UvData.XmlData{1};
3807        DataOut=feval(transform_handle,'*',UvData.XmlData{1});
3808        if isfield(DataOut,'CoordUnit')% set the requested coord unit (info used to possibly delete the current projection objects)
3809            CoordUnit=DataOut.CoordUnit;
3810        end
3811        if isfield(DataOut,'InputFieldType')% to be used to impose a type of input file (eg. for image transform)
3812            UvData.InputFieldType=DataOut.InputFieldType;
3813        end
3814        if isfield(DataOut,'TransformInput')%  used to add transform parameters at selection of the transform fct
3815            UvData.XmlData{1}.TransformInput=DataOut.TransformInput;
3816%             ListFields=fieldnames(DataOut.XmlData);
3817%             for ilist=1:numel(ListFields)
3818%             UvData.XmlData{1}.(ListFields{ilist})=DataOut.XmlData.(ListFields{ilist});
3819%             end
3820        end
3821%     else
3822%         DataOut=feval(transform_handle,'*');
3823    end
3824end
3825
3826
3827%% delete drawn objects if the output CooordUnit is different from the previous one
3828if  ~strcmp(CoordUnit,CoordUnitPrev)
3829    set(handles.CheckFixLimits,'Value',0)
3830    hother=findobj('Tag','proj_object');%find all the proj objects
3831    for iobj=1:length(hother)
3832        delete_object(hother(iobj))
3833    end
3834    hother=findobj('Tag','DeformPoint');%find all the proj objects
3835    for iobj=1:length(hother)
3836        delete_object(hother(iobj))
3837    end
3838    hh=findobj('Tag','calib_points');
3839    if ~isempty(hh)
3840        delete(hh)
3841    end
3842    hhh=findobj('Tag','calib_marker');
3843    if ~isempty(hhh)
3844        delete(hhh)
3845    end
3846    set(handles.ListObject,'Value',1)
3847    set(handles.ListObject,'String',{''})
3848    set(handles.ListObject_1,'Value',1)
3849    set(handles.ListObject_1,'String',{''})
3850    set(handles.CheckViewObject,'value',0)
3851    CheckViewObject_Callback(hObject, eventdata, handles)
3852    set(handles.CheckViewField,'value',0)
3853    CheckViewField_Callback(hObject, eventdata, handles)
3854    set(handles.CheckEditObject,'Value',0)
3855    CheckEditObject_Callback(hObject, eventdata, handles)
3856    UvData.ProjObject={[]};
3857end
3858set(handles.uvmat,'UserData',UvData)
3859set(handles.TransformName,'backgroundColor',[1 1 1])% indicate desactivation  of the menu
3860drawnow
3861
3862%% inputfilerefresh the current plot
3863if isempty(list_path{ichoice}) || nargin(transform_handle)<3
3864    set(handles.SubField,'Value',0)
3865    SubField_Callback(hObject, eventdata, handles)
3866else
3867    REFRESH_Callback(hObject, eventdata, handles)
3868end
3869
3870%------------------------------------------------
3871%CALLBACKS FOR PLOTTING PARAMETERS
3872%-------------------------------------------------
3873%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3874% Plot coordinates
3875%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3876%------------------------------------------------------------------------
3877function num_MinX_Callback(hObject, eventdata, handles)
3878%------------------------------------------------------------------------
3879set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3880% set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3881update_plot(handles);
3882
3883%------------------------------------------------------------------------
3884function num_MaxX_Callback(hObject, eventdata, handles)
3885%------------------------------------------------------------------------
3886set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3887% set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3888update_plot(handles);
3889
3890%------------------------------------------------------------------------
3891function num_MinY_Callback(hObject, eventdata, handles)
3892%------------------------------------------
3893set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3894% set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3895update_plot(handles);
3896
3897%------------------------------------------------------------------------
3898function num_MaxY_Callback(hObject, eventdata, handles)
3899%------------------------------------------------------------------------
3900set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3901% set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3902update_plot(handles);
3903
3904%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3905% Scalar or image representation
3906%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3907%------------------------------------------------------------------------
3908function num_MinA_Callback(hObject, eventdata, handles)
3909%------------------------------------------
3910set(handles.CheckFixScalar,'Value',1) %suppress auto mode
3911% set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3912MinA=str2double(get(handles.num_MinA,'String'));
3913MaxA=str2double(get(handles.num_MaxA,'String'));
3914if MinA>MaxA% switch minA and maxA in case of error
3915    MinA_old=MinA;
3916    MinA=MaxA;
3917    MaxA=MinA_old;
3918    set(handles.num_MinA,'String',num2str(MinA,5));
3919    set(handles.num_MaxA,'String',num2str(MaxA,5));
3920end
3921update_plot(handles);
3922
3923%------------------------------------------------------------------------
3924function num_MaxA_Callback(hObject, eventdata, handles)
3925%------------------------------------------------------------------------
3926set(handles.CheckFixScalar,'Value',1) %suppress auto mode
3927% set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3928MinA=str2double(get(handles.num_MinA,'String'));
3929MaxA=str2double(get(handles.num_MaxA,'String'));
3930if MinA>MaxA% switch minA and maxA in case of error
3931        MinA_old=MinA;
3932    MinA=MaxA;
3933    MaxA=MinA_old;
3934    set(handles.num_MinA,'String',num2str(MinA,5));
3935    set(handles.num_MaxA,'String',num2str(MaxA,5));
3936end
3937update_plot(handles);
3938
3939%------------------------------------------------------------------------
3940function CheckFixScalar_Callback(hObject, eventdata, handles)
3941%------------------------------------------------------------------------
3942test=get(handles.CheckFixScalar,'Value');
3943if test
3944%     set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3945else
3946%     set(handles.CheckFixScalar,'BackgroundColor',[0.7 0.7 0.7])
3947    update_plot(handles);
3948end
3949
3950%-------------------------------------------------------------------
3951function CheckBW_Callback(hObject, eventdata, handles)
3952%-------------------------------------------------------------------
3953update_plot(handles);
3954
3955%-------------------------------------------------------------------
3956function num_Opacity_Callback(hObject, eventdata, handles)
3957update_plot(handles);
3958%-------------------------------------------------------------------
3959
3960%-------------------------------------------------------------------
3961function ListContour_Callback(hObject, eventdata, handles)
3962%-------------------------------------------------------------------
3963val=get(handles.ListContour,'Value');
3964if val==2% option 'contours'
3965    set(handles.interval_txt,'Visible','on')
3966    set(handles.num_IncrA,'Visible','on')
3967    set(handles.num_IncrA,'String','')% refresh contour interval
3968%     set(handles.opacity_txt,'Visible','off')
3969%     set(handles.num_Opacity,'Visible','off')
3970else % option 'image'
3971    set(handles.interval_txt,'Visible','off')
3972    set(handles.num_IncrA,'Visible','off')
3973%     set(handles.opacity_txt,'Visible','on')
3974%     set(handles.num_Opacity,'Visible','on')
3975end
3976update_plot(handles);
3977
3978%-------------------------------------------------------------------
3979function num_IncrA_Callback(hObject, eventdata, handles)
3980%-------------------------------------------------------------------
3981update_plot(handles);
3982
3983
3984%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3985% Vector representation
3986%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3987%-------------------------------------------------------------------
3988function CheckHideWarning_Callback(hObject, eventdata, handles)
3989%-------------------------------------------------------------------
3990update_plot(handles);
3991
3992%-------------------------------------------------------------------
3993function CheckHideFalse_Callback(hObject, eventdata, handles)
3994%-------------------------------------------------------------------
3995update_plot(handles);
3996
3997%-------------------------------------------------------------------
3998function num_VecScale_Callback(hObject, eventdata, handles)
3999%-------------------------------------------------------------------
4000set(handles.CheckFixVectors,'Value',1);
4001set(handles.CheckFixVectors,'BackgroundColor',[1 1 0])
4002update_plot(handles);
4003
4004%-------------------------------------------------------------------
4005function CheckFixVectors_Callback(hObject, eventdata, handles)
4006%-------------------------------------------------------------------
4007if ~get(handles.CheckFixVectors,'Value')
4008    update_plot(handles);
4009end
4010
4011%------------------------------------------------------------------------
4012% --- Executes on selection change in CheckDecimate4 (nb_vec/4).
4013%------------------------------------------------------------------------
4014function CheckDecimate4_Callback(hObject, eventdata, handles)
4015
4016if isequal(get(handles.CheckDecimate4,'Value'),1)
4017    set(handles.CheckDecimate16,'Value',0)
4018end
4019update_plot(handles);
4020
4021%------------------------------------------------------------------------
4022% --- Executes on selection change in CheckDecimate16 (nb_vec/16).
4023%------------------------------------------------------------------------
4024function CheckDecimate16_Callback(hObject, eventdata, handles)
4025
4026if isequal(get(handles.CheckDecimate16,'Value'),1)
4027    set(handles.CheckDecimate4,'Value',0)
4028end
4029update_plot(handles);
4030
4031%------------------------------------------------------------------------
4032% --- Executes on selection change in ColorCode menu
4033function ColorCode_Callback(hObject, eventdata, handles)
4034%------------------------------------------------------------------------
4035% edit the choice for color code
4036update_color_code_boxes(handles);
4037update_plot(handles);
4038
4039%------------------------------------------------------------------------
4040function update_color_code_boxes(handles)
4041%------------------------------------------------------------------------
4042list_code=get(handles.ColorCode,'String');% list menu fields
4043colcode= list_code{get(handles.ColorCode,'Value')}; % selected field
4044enable_slider='off';%default
4045enable_bounds='off';%default
4046enable_scalar='off';%default
4047switch colcode
4048    case {'rgb','bgr'}
4049        enable_slider='on';
4050        enable_bounds='on';
4051        enable_scalar='on';
4052    case '64 colors'
4053        enable_bounds='on';
4054        enable_scalar='on';
4055end
4056set(handles.Slider1,'Visible',enable_slider)
4057set(handles.Slider2,'Visible', enable_slider)
4058set(handles.num_ColCode1,'Visible',enable_slider)
4059set(handles.num_ColCode2,'Visible',enable_slider)
4060set(handles.TitleColCode1,'Visible',enable_slider)
4061set(handles.TitleColCode2,'Visible',enable_slider)
4062set(handles.CheckFixVecColor,'Visible',enable_bounds)
4063set(handles.num_MinVec,'Visible',enable_bounds)
4064set(handles.num_MaxVec,'Visible',enable_bounds)
4065set(handles.ColorScalar,'Visible',enable_scalar)
4066set_vec_col_bar(handles)
4067
4068%------------------------------------------------------------------
4069% --- Executes on selection change in ColorScalar: choice of the color code.
4070function ColorScalar_Callback(hObject, eventdata, handles)
4071%------------------------------------------------------------------
4072% edit the choice for color code
4073list_scalar=get(handles.ColorScalar,'String');% list menu fields
4074col_scalar= list_scalar{get(handles.ColorScalar,'Value')}; % selected field
4075if isequal(col_scalar,'ima_cor')
4076    set(handles.CheckFixVecColor,'Value',1)%fixed scale by default
4077    ColorCode='rgb';
4078    set(handles.num_MinVec,'String','0')
4079    set(handles.num_MaxVec,'String','1')
4080    set(handles.num_ColCode1,'String','0.333')
4081    set(handles.num_ColCode2,'String','0.666')
4082else
4083    set(handles.CheckFixVecColor,'Value',0)%auto scale between min,max by default
4084    ColorCode='64 colors';
4085end
4086ColorCodeList=get(handles.ColorCode,'String');
4087ichoice=find(strcmp(ColorCode,ColorCodeList),1);
4088set(handles.ColorCode,'Value',ichoice)% set color code in the menu
4089
4090update_color_code_boxes(handles);
4091%replot the current graph
4092REFRESH_Callback(hObject, eventdata, handles)
4093
4094%----------------------------------------------------------------
4095% -- Executes on slider movement to set the color code
4096%
4097function Slider1_Callback(hObject, eventdata, handles)
4098%------------------------------------------------------------------
4099slider1=get(handles.Slider1,'Value');
4100min_val=str2num(get(handles.num_MinVec,'String'));
4101max_val=str2num(get(handles.num_MaxVec,'String'));
4102col=min_val+(max_val-min_val)*slider1;
4103set(handles.num_ColCode1,'String',num2str(col))
4104if(get(handles.Slider2,'Value') < col)%move also the second slider at the same value if needed
4105    set(handles.Slider2,'Value',col)
4106    set(handles.num_ColCode2,'String',num2str(col))
4107end
4108set_vec_col_bar(handles)
4109update_plot(handles);
4110
4111%----------------------------------------------------------------
4112% Executes on slider movement to set the color code
4113%----------------------------------------------------------------
4114function Slider2_Callback(hObject, eventdata, handles)
4115slider2=get(handles.Slider2,'Value');
4116min_val=str2num(get(handles.num_MinVec,'String'));
4117max_val=str2num(get(handles.num_MaxVec,'String'));
4118col=min_val+(max_val-min_val)*slider2;
4119set(handles.num_ColCode2,'String',num2str(col))
4120if(get(handles.Slider1,'Value') > col)%move also the first slider at the same value if needed
4121    set(handles.Slider1,'Value',col)
4122    set(handles.num_ColCode1,'String',num2str(col))
4123end
4124set_vec_col_bar(handles)
4125update_plot(handles);
4126
4127%----------------------------------------------------------------
4128% --- Execute on return carriage on the edit box corresponding to slider 1
4129%----------------------------------------------------------------
4130function num_ColCode1_Callback(hObject, eventdata, handles)
4131set_vec_col_bar(handles)
4132update_plot(handles);
4133
4134%----------------------------------------------------------------
4135% --- Execute on return carriage on the edit box corresponding to slider 2
4136%----------------------------------------------------------------
4137function num_ColCode2_Callback(hObject, eventdata, handles)
4138set_vec_col_bar(handles)
4139update_plot(handles);
4140%------------------------------------------------------------------------
4141%-------------------------------------------------------
4142% --- Executes on button press in CheckFixVecColor.
4143%-------------------------------------------------------
4144function VecColBar_Callback(hObject, eventdata, handles)
4145set_vec_col_bar(handles)
4146
4147%------------------------------------------------------------------------
4148% --- Executes on button press in CheckFixVecColor.
4149function CheckFixVecColor_Callback(hObject, eventdata, handles)
4150%------------------------------------------------------------------------
4151if ~get(handles.CheckFixVecColor,'Value')
4152    update_plot(handles);
4153end
4154
4155%------------------------------------------------------------------------
4156% --- Executes on selection change in num_MaxVec.
4157function num_MinVec_Callback(hObject, eventdata, handles)
4158%------------------------------------------------------------------------
4159num_MaxVec_Callback(hObject, eventdata, handles)
4160
4161%------------------------------------------------------------------------
4162% --- Executes on selection change in num_MaxVec.
4163function num_MaxVec_Callback(hObject, eventdata, handles)
4164%------------------------------------------------------------------------
4165set(handles.CheckFixVecColor,'Value',1)
4166CheckFixVecColor_Callback(hObject, eventdata, handles)
4167min_val=str2num(get(handles.num_MinVec,'String'));
4168max_val=str2num(get(handles.num_MaxVec,'String'));
4169slider1=get(handles.Slider1,'Value');
4170slider2=get(handles.Slider2,'Value');
4171colcode1=min_val+(max_val-min_val)*slider1;
4172colcode2=min_val+(max_val-min_val)*slider2;
4173set(handles.num_ColCode1,'String',num2str(colcode1))
4174set(handles.num_ColCode2,'String',num2str(colcode2))
4175update_plot(handles);
4176
4177%------------------------------------------------------------------------
4178% --- update the display of color code for vectors (on vecColBar)
4179function set_vec_col_bar(handles)
4180%------------------------------------------------------------------------
4181%get the image of the color display button 'VecColBar' in pixels
4182set(handles.VecColBar,'Unit','pixel');
4183pos_vert=get(handles.VecColBar,'Position');
4184set(handles.VecColBar,'Unit','Normalized');
4185width=ceil(pos_vert(3));
4186height=ceil(pos_vert(4));
4187
4188%get slider indications
4189list=get(handles.ColorCode,'String');
4190ichoice=get(handles.ColorCode,'Value');
4191colcode.ColorCode=list{ichoice};
4192colcode.MinVec=str2num(get(handles.num_MinVec,'String'));
4193colcode.MaxVec=str2num(get(handles.num_MaxVec,'String'));
4194test3color=strcmp(colcode.ColorCode,'rgb') || strcmp(colcode.ColorCode,'bgr');
4195if test3color
4196    colcode.ColCode1=str2num(get(handles.num_ColCode1,'String'));
4197    colcode.ColCode2=str2num(get(handles.num_ColCode2,'String'));
4198end
4199vec_C=colcode.MinVec+(colcode.MaxVec-colcode.MinVec)*(0.5:width-0.5)/width;%sample of vec_C values from min to max
4200[colorlist,col_vec]=set_col_vec(colcode,vec_C);
4201oneheight=ones(1,height);
4202A1=colorlist(col_vec,1)*oneheight;
4203A2=colorlist(col_vec,2)*oneheight;
4204A3=colorlist(col_vec,3)*oneheight;
4205A(:,:,1)=A1';
4206A(:,:,2)=A2';
4207A(:,:,3)=A3';
4208set(handles.VecColBar,'Cdata',A)
4209
4210%-------------------------------------------------------------------
4211function update_plot(handles)
4212%-------------------------------------------------------------------
4213set(handles.REFRESH,'BackgroundColor',[1 1 0]);% display plot activity by yellow color
4214drawnow
4215UvData=get(handles.uvmat,'UserData');
4216AxeData=UvData.PlotAxes;% retrieve the current plotted data
4217PlotParam=read_GUI(handles.uvmat);
4218[tild,PlotParamOut]= plot_field(AxeData,handles.PlotAxes,PlotParam);
4219errormsg=fill_GUI(PlotParamOut,handles.uvmat);
4220if ~isempty(errormsg)
4221    msgbox_uvmat('ERROR',errormsg)
4222    return
4223end
4224set(handles.REFRESH,'BackgroundColor',[1 0 0]);
4225
4226%------------------------------------------------------------------------
4227%------------------------------------------------------------------------
4228%   SELECTION AND EDITION OF PROJECTION OBJECTS
4229%------------------------------------------------------------------------
4230%------------------------------------------------------------------------
4231
4232% --- Executes on selection change in ListObject_1.
4233function ListObject_1_Callback(hObject, eventdata, handles)
4234list_str=get(handles.ListObject,'String');
4235UvData=get(handles.uvmat,'UserData');
4236ObjectData=UvData.ProjObject{get(handles.ListObject_1,'Value')};
4237
4238%% update the projection plot on uvmat
4239ProjData= proj_field(UvData.Field,ObjectData);%project the current input field on object ObjectData
4240plot_field(ProjData,handles.PlotAxes,read_GUI(handles.uvmat));% plot the projected field;
4241%replot all the objects within the new projected field
4242for IndexObj=1:numel(list_str)
4243        hobject=UvData.ProjObject{IndexObj}.DisplayHandle.uvmat;
4244        if isempty(hobject) || ~ishandle(hobject)
4245            hobject=handles.PlotAxes;
4246        end
4247        if isequal(IndexObj,get(handles.ListObject,'Value'))
4248            objectcolor='m'; %paint in magenta the currently selected object in ListObject
4249        else
4250            objectcolor='b';
4251        end
4252        UvData.ProjObject{IndexObj}.DisplayHandle.uvmat=plot_object(UvData.ProjObject{IndexObj},ObjectData,hobject,objectcolor);%draw the object in uvmat     
4253end
4254set(handles.uvmat,'UserData',UvData)
4255
4256%% display the object parameters if the GUI set_object is already opened
4257if ~get(handles.CheckViewObject,'Value')
4258    ZBounds=0; % default
4259    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4260        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4261        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4262    end
4263    ObjectData.Name=list_str{get(handles.ListObject_1,'Value')};
4264    hset_object=set_object(ObjectData,[],ZBounds);
4265    set(hset_object,'name','set_object')
4266    set(handles.CheckViewObject,'Value',1)% show that the selected object in ListObject_1 is currently visualised
4267end
4268
4269%  desactivate the edit object mode
4270set(handles.CheckEditObject,'Value',0)
4271% set(handles.CheckEditObject,'BackgroundColor',[0.7,0.7,0.7])
4272
4273%------------------------------------------------------------------------
4274% --- Executes on selection change in ListObject.
4275function ListObject_Callback(hObject, eventdata, handles)
4276%------------------------------------------------------------------------
4277list_str=get(handles.ListObject,'String');
4278IndexObj=get(handles.ListObject,'Value');%present object selection
4279UvData=get(handles.uvmat,'UserData');
4280if numel(UvData.ProjObject)<IndexObj
4281    return
4282end
4283ObjectData=UvData.ProjObject{IndexObj};
4284    ZBounds=0; % default
4285    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4286        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4287        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4288    end
4289
4290%% show object features if view_object isselected
4291if get(handles.CheckViewObject,'value')
4292    hset_object=set_object(ObjectData,[],ZBounds);
4293    set(hset_object,'name','set_object')
4294end
4295
4296%%  desactivate the edit object mode for security
4297set(handles.CheckEditObject,'Value',0)
4298
4299%% update the  plot on view_field if view_field is already openened
4300hview_field=findobj(allchild(0),'tag','view_field');
4301if isempty(hview_field)
4302    hhview_field.PlotAxes=[];
4303else
4304    Data=get(hview_field,'UserData');
4305    hhview_field=guidata(hview_field);
4306    ProjData= proj_field(UvData.Field,ObjectData);%project the current interface field on ObjectData
4307    [PlotType,PlotParam]=plot_field(ProjData,hhview_field.PlotAxes,read_GUI(hview_field));%read plotting parameters on the uvmat interface
4308   
4309    %write_plot_param(hhview_field,PlotParam); %update the display of plotting parameters for the current object
4310    haxes=findobj(hview_field,'tag','axes3');
4311    pos=get(hview_field,'Position'); 
4312    if strcmp(get(haxes,'Visible'),'off')%sempty(PlotParam.Coordinates)% case of no plot display (pure text table)
4313        h_TableDisplay=findobj(hview_field,'tag','TableDisplay');
4314        pos_table=get(h_TableDisplay,'Position');
4315        set(hview_field,'Position',[pos(1)+pos(3)-pos_table(3) pos(2)+pos(4)-pos_table(4) pos_table(3) pos_table(4)])
4316        drawnow% needed to change position before the next command
4317        set(hview_field,'UserData',Data);% restore the previously stored GUI position after GUI resizing
4318    else
4319%         set(hview_field,'Position',Data.GUISize)% return to the previously stored GUI position and size
4320    end
4321end
4322
4323%% update the color of the graphic object representation: the selected object in magenta, others in blue
4324update_object_color(handles.PlotAxes,hhview_field.PlotAxes,UvData.ProjObject{IndexObj}.DisplayHandle.uvmat)
4325
4326%------------------------------------------------------------------------
4327%--- update the color representation of objects (indicating the selected ones)
4328function update_object_color(axes_uvmat,axes_view_field,DisplayHandle)
4329%------------------------------------------------------------------------
4330if isempty(axes_view_field)% case with no view_field plot
4331hother=[findobj(axes_uvmat,'Tag','proj_object');findobj(axes_uvmat,'Tag','DeformPoint')];%find all the proj object and deform point representations
4332else
4333hother=[findobj(axes_uvmat,'Tag','proj_object') ;findobj(axes_view_field,'Tag','proj_object');... %find all the proj object representations
4334findobj(axes_uvmat,'Tag','DeformPoint'); findobj(axes_view_field,'Tag','DeformPoint')];%find all the deform point representations
4335end
4336for iobj=1:length(hother)
4337    if isequal(get(hother(iobj),'Type'),'rectangle')||isequal(get(hother(iobj),'Type'),'patch')
4338        set(hother(iobj),'EdgeColor','b')
4339        if isequal(get(hother(iobj),'FaceColor'),'m')
4340            set(hother(iobj),'FaceColor','b')
4341        end
4342    elseif isequal(get(hother(iobj),'Type'),'image')
4343        Acolor=get(hother(iobj),'CData');
4344        Acolor(:,:,1)=zeros(size(Acolor,1),size(Acolor,2));
4345        set(hother(iobj),'CData',Acolor);
4346    else
4347        set(hother(iobj),'Color','b')
4348    end
4349    set(hother(iobj),'Selected','off')
4350end
4351if ishandle(DisplayHandle)
4352    linetype=get(DisplayHandle,'Type');
4353    if isequal(linetype,'line')
4354        set(DisplayHandle,'Color','m'); %set the selected object to magenta color
4355    elseif isequal(linetype,'rectangle')
4356        set(DisplayHandle,'EdgeColor','m'); %set the selected object to magenta color
4357    elseif isequal(linetype,'patch')
4358        set(DisplayHandle,'FaceColor','m'); %set the selected object to magenta color
4359    end
4360    SubObjectData=get(DisplayHandle,'UserData');
4361    if isfield(SubObjectData,'SubObject') & ishandle(SubObjectData.SubObject)
4362        for iobj=1:length(SubObjectData.SubObject)
4363            hsub=SubObjectData.SubObject(iobj);
4364            if isequal(get(hsub,'Type'),'rectangle')
4365                set(hsub,'EdgeColor','m'); %set the selected object to magenta color
4366            elseif isequal(get(hsub,'Type'),'image')
4367                Acolor=get(hsub,'CData');
4368                Acolor(:,:,1)=Acolor(:,:,3);
4369                set(hsub,'CData',Acolor);
4370            else
4371                set(hsub,'Color','m')
4372            end
4373        end
4374    end
4375    if isfield(SubObjectData,'DeformPoint') & ishandle(SubObjectData.DeformPoint)
4376        set(SubObjectData.DeformPoint,'Color','m')
4377    end
4378end
4379
4380%-------------------------------------------------------------------
4381% --- Executes on selection change in CheckEditObject.
4382function CheckEditObject_Callback(hObject, eventdata, handles)
4383%-------------------------------------------------------------------
4384hset_object=findobj(allchild(0),'Tag','set_object');
4385if get(handles.CheckEditObject,'Value')
4386    %suppress the other options
4387    set(handles.MenuObject,'checked','off')
4388    set(handles.CheckZoom,'Value',0)
4389    CheckZoom_Callback(hObject, eventdata, handles)
4390    hgeometry_calib=findobj(allchild(0),'tag','geometry_calib');
4391    if ishandle(hgeometry_calib)
4392        hhgeometry_calib=guidata(hgeometry_calib);
4393        set(hhgeometry_calib.CheckEnableMouse,'Value',0)% desactivate mouse action in geometry_calib
4394        set(hhgeometry_calib.CheckEnableMouse,'BackgroundColor',[0.7 0.7 0.7])
4395    end
4396    set(handles.CheckViewObject,'value',1)
4397    CheckViewObject_Callback(hObject, eventdata, handles)
4398else % desactivate object edit mode
4399    if ~isempty(hset_object)% open the
4400        set(get(hset_object,'children'),'Enable','off')
4401        hSAVE=findobj(hset_object,'Tag','SAVE');
4402        set(hSAVE,'Enable','on')
4403    end
4404end
4405
4406
4407%------------------------------------------------------------------------
4408% --- Executes on button press in CheckViewObject.
4409function CheckViewObject_Callback(hObject, eventdata, handles)
4410%------------------------------------------------------------------------
4411check_view=get(handles.CheckViewObject,'Value');
4412
4413if check_view %activate set_object   
4414    IndexObj=get(handles.ListObject,'Value');
4415    list_object=get(handles.ListObject,'String');
4416    UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4417    UvData.ProjObject{IndexObj}.Name=list_object{IndexObj};
4418    if numel(UvData.ProjObject)<IndexObj;% error in UvData
4419        msgbox_uvmat('ERROR','invalid object list')
4420        return
4421    end
4422    ZBounds=0; % default
4423    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4424        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4425        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4426    end
4427    data=UvData.ProjObject{IndexObj};
4428    if ~isfield(data,'Type')% default plane
4429        data.Type='plane';
4430    end
4431    hset_object=set_object(data,[],ZBounds);
4432    set(hset_object,'name','set_object')
4433    hhset_object=guidata(hset_object);
4434    if get(handles.CheckEditObject,'Value')% edit mode
4435        set(get(hset_object,'children'),'Enable','on')
4436    else
4437        set(get(hset_object,'children'),'Enable','off')% deactivate the GUI except SAVE
4438        set(hhset_object.SAVE,'Enable','on')
4439    end
4440else
4441    hset_object=findobj(allchild(0),'tag','set_object');
4442    if ~isempty(hset_object)
4443        delete(hset_object)% delete existing version of set_object
4444    end
4445end
4446 
4447
4448%------------------------------------------------------------------------
4449% --- Executes on button press in CheckViewField.
4450function CheckViewField_Callback(hObject, eventdata, handles)
4451%------------------------------------------------------------------------
4452check_view=get(handles.CheckViewField,'Value');
4453
4454if check_view
4455    IndexObj=get(handles.ListObject,'Value');
4456    UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4457    if numel(UvData.ProjObject)<IndexObj(end);% error in UvData
4458        msgbox_uvmat('ERROR','invalid object list')
4459        return
4460    end
4461    ZBounds=0; % default
4462    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4463        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4464        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4465    end
4466    set(handles.ListObject,'Value',IndexObj);%restore ListObject selection after set_object deletion
4467    if ~isfield(UvData.ProjObject{IndexObj(1)},'Type')% default plane
4468        UvData.ProjObject{IndexObj(1)}.Type='plane';
4469    end
4470    list_object=get(handles.ListObject,'String');
4471    UvData.ProjObject{IndexObj(end)}.Name=list_object{IndexObj(end)};
4472   
4473    %% show the projection of the selected object on view_field
4474    ProjData= proj_field(UvData.Field,UvData.ProjObject{IndexObj});%project the current field on ObjectData
4475    hview_field=findobj(allchild(0),'tag','view_field');
4476    if isempty(hview_field)
4477        hview_field=view_field;
4478    end
4479    hhview_field=guidata(hview_field);
4480    [PlotType,PlotParam]=plot_field(ProjData,hhview_field.PlotAxes,read_GUI(hview_field));%read plotting parameters on the GUI view_field);
4481    errormsg=fill_GUI(PlotParam,hview_field);
4482    for list={'Scalar','Vectors'}
4483        if ~isfield(PlotParam,list{1})
4484            set(hhview_field.(list{1}),'Visible','off')
4485        end
4486    end
4487    %write_plot_param(hhview_field,PlotParam); %update the display of plotting parameters for the current object
4488    haxes=findobj(hview_field,'tag','axes3');
4489    pos=get(hview_field,'Position');
4490    if strcmp(get(haxes,'Visible'),'off')%sempty(PlotParam.Coordinates)% case of no plot display (pure text table)
4491        h_TableDisplay=findobj(hview_field,'tag','TableDisplay');
4492        pos_table=get(h_TableDisplay,'Position');
4493        set(hview_field,'Position',[pos(1)+pos(3)-pos_table(3) pos(2)+pos(4)-pos_table(4) pos_table(3) pos_table(4)])
4494    else
4495        Data=get(hview_field,'UserData');
4496%         set(hview_field,'Position',Data.GUISize)% restore the size of view_field for plots
4497    end
4498else
4499    hview_field=findobj(allchild(0),'tag','view_field');
4500    if ~isempty(hview_field)
4501        delete(hview_field)% delete existing version of set_object
4502    end
4503end
4504
4505
4506%------------------------------------------------------------------------
4507% --- Executes on button press in DeleteObject.
4508%------------------------------------------------------------------------
4509function DeleteObject_Callback(hObject, eventdata, handles)
4510
4511IndexObj=get(handles.ListObject,'Value');%projection object selected for view_field
4512IndexObj_1=get(handles.ListObject_1,'Value');%projection object selected for uvmat plot
4513if IndexObj>1 && ~isequal(IndexObj,IndexObj_1) % do not delete the object used for the uvmat plot
4514    delete_object(IndexObj)
4515end
4516
4517%'DeleteObject': delete a projection object, defined by its index in the Uvmat list or by its graphic handle
4518%------------------------------------------------------------------------
4519% function DeleteObject(hObject)
4520%
4521% INPUT:
4522% hObject: object index (if integer) or handle of the graphic object. If
4523%          hObject is a subobject, the parent object is detected and deleted.
4524
4525function delete_object(IndexObj)
4526
4527huvmat=findobj('tag','uvmat');%handles of the uvmat interface
4528UvData=get(huvmat,'UserData');
4529hlist_object=findobj(huvmat,'Tag','ListObject');%handles of the object list in the uvmat interface
4530list_str=get(hlist_object,'String');%objet list
4531if  ~isempty(UvData) && isfield(UvData, 'ProjObject') && length(UvData.ProjObject)>=IndexObj
4532    if isfield(UvData.ProjObject{IndexObj},'DisplayHandle') && isfield(UvData.ProjObject{IndexObj}.DisplayHandle,'uvmat')
4533        hdisplay=UvData.ProjObject{IndexObj}.DisplayHandle.uvmat;%handle of the object graphic representation in uvmat
4534        for iview=1:length(hdisplay)
4535            if ishandle(hdisplay(iview)) && ~isequal(hdisplay(iview),0)
4536                ObjectData=get(hdisplay(iview),'UserData');
4537                if isfield(ObjectData,'SubObject') && ~isempty(ObjectData.SubObject)
4538                    delete(ObjectData.SubObject(ishandle(ObjectData.SubObject)));% delete the graphic 'sub-objects (e.g. projection bounds)
4539                end
4540                if isfield(ObjectData,'DeformPoint')&& ~isempty(ObjectData.DeformPoint)
4541                    delete(ObjectData.DeformPoint(ishandle(ObjectData.DeformPoint)));% delete the graphic deformation points
4542                    delete(hdisplay(iview))% delete the main graphic representation of the object
4543                end
4544            end
4545            ishandle(hdisplay(iview))
4546        end
4547        for iobj=IndexObj+1:length(UvData.ProjObject)
4548            hdisplay=UvData.ProjObject{iobj}.DisplayHandle.uvmat;
4549            for iview=1:length(hdisplay)
4550                if ishandle(hdisplay(iview)) && ~isequal(hdisplay(iview),0)
4551                    PlotData=get(hdisplay(iview),'UserData');
4552                    PlotData.IndexObj=iobj-1;
4553                    set(hdisplay(iview),'UserData',PlotData);
4554                end
4555            end
4556        end
4557    end
4558    UvData.ProjObject(IndexObj)=[];
4559end
4560if numel(list_str)>=IndexObj
4561    list_str(IndexObj)=[];
4562end
4563set(huvmat,'UserData',UvData);
4564set(hlist_object,'String',list_str)
4565set(hlist_object,'Value',length(list_str))
4566hlist_object_1=findobj(huvmat,'Tag','ListObject_1');%handles of the first object list in the uvmat interface
4567old_index=get(hlist_object_1,'Value');
4568set(hlist_object_1,'String',list_str)
4569if IndexObj<=old_index
4570    set(hlist_object_1,'Value',old_index-1)
4571end
4572
4573%------------------------------------------------------------------------
4574%------------------------------------------------------------------------
4575%  II - TOOLS FROM THE UPPER MENU BAR
4576%------------------------------------------------------------------------
4577%------------------------------------------------------------------------
4578
4579%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4580% Export  Menu Callbacks
4581%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4582%------------------------------------------------------------------------
4583% --- Executes on button press in Menu/Export/field in workspace.
4584function MenuExportField_Callback(hObject, eventdata, handles)
4585%------------------------------------------------------------------------
4586global Data_uvmat
4587Data_uvmat=get(handles.uvmat,'UserData');
4588evalin('base','global Data_uvmat')%make CurData global in the workspace
4589display('current field :')
4590evalin('base','Data_uvmat') %display CurData in the workspace
4591commandwindow; %brings the Matlab command window to the front
4592
4593%------------------------------------------------------------------------
4594% --- Executes on button press in Menu/Export/extract figure.
4595function MenuExportFigure_Callback(hObject, eventdata, handles)
4596%------------------------------------------------------------------------
4597hfig=figure;
4598copyobj(handles.PlotAxes,hfig);
4599h=findobj(handles.PlotAxes,'tag','ima'); %look for image in the plot
4600if ~isempty(h)
4601    map=colormap(handles.PlotAxes);
4602    colormap(map);%transmit the current colormap to the zoom fig
4603    colorbar
4604end
4605
4606% --------------------------------------------------------------------
4607function MenuExportAxis_Callback(hObject, eventdata, handles)
4608ListFig=findobj(allchild(0),'Type','figure');
4609nb_option=0;
4610menu={};
4611for ilist=1:numel(ListFig)
4612    FigName=get(ListFig(ilist),'name');
4613    if isempty(FigName)
4614        FigName=['figure ' num2str(ListFig(ilist))];
4615    end
4616    if ~strcmp(FigName,'uvmat')
4617        ListAxes=findobj(ListFig(ilist),'Type','axes');
4618        ListTags=get(ListAxes,'Tag');
4619        if ~isempty(ListTags) && ~isempty(find(~strcmp('Colorbar',ListTags), 1))
4620            ListAxes=ListAxes(~strcmp('Colorbar',ListTags));
4621            if numel(ListAxes)==1
4622                nb_option=nb_option+1;
4623                menu{nb_option}=FigName ;
4624                AxesHandle(nb_option)=ListAxes;
4625            else
4626                nb_axis=0;
4627                for iaxes=1:numel(ListAxes)
4628                    nb_axis=nb_axis+1;
4629                    nb_option=nb_option+1;
4630                    menu{nb_option}=[FigName '_' num2str(nb_axis)];
4631                    AxesHandle(nb_option)=ListAxes(nb_axis);
4632                end
4633            end
4634        end
4635    end
4636end
4637if isempty(menu)
4638    answer=msgbox_uvmat('INPUT_Y-N','no existing plotting axes available, create new figure?');
4639    if strcmp(answer,'Yes')
4640        hfig=figure;
4641        copyobj(handles.PlotAxes,hfig);
4642    else
4643        return
4644    end
4645    map=colormap(handles.PlotAxes);
4646    colormap(map);%transmit the current colormap to the zoom fig
4647    colorbar
4648else
4649    answer=msgbox_uvmat('INPUT_MENU','select a figure/axis on which the current uvmat plot will be exported',menu);
4650    if isempty(answer)
4651        return
4652    else
4653        axes(AxesHandle(answer))
4654        hold on
4655        hchild=get(handles.PlotAxes,'children');
4656        copyobj(hchild,gca);
4657    end
4658end
4659
4660
4661%------------------------------------------------------------------------
4662% --------------------------------------------------------------------
4663function MenuExportMovie_Callback(hObject, eventdata, handles)
4664% --------------------------------------------------------------------
4665set(handles.MenuExportMovie,'BusyAction','queue')% activate the button
4666huvmat=get(handles.InputFileREFRESH,'parent');
4667UvData=get(huvmat,'UserData');
4668%[xx,xx,FileBase]=read_file_boxes(handles);
4669[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
4670FileBase=fullfile(RootPath,RootFile);
4671 %read the current input file name
4672prompt = {'movie file name';'frames per second';'frame resolution (*[512x384] pixels)';'axis position relative to the frame';'total frame number (starting from the current uvmat display)'};
4673dlg_title = 'select properties of the output avi movie';
4674num_lines= 1;
4675def     = {[FileBase '_out.avi'];'10';'1';'[0.03 0.05 0.95 0.92]';'10'};
4676answer = inputdlg(prompt,dlg_title,num_lines,def,'on');
4677aviname=answer{1};
4678fps=str2double(answer{2});
4679% check for existing file with output name aviname
4680if exist(aviname,'file')
4681    backup=aviname;
4682    testexist=2;
4683    while testexist==2
4684        backup=[backup '~'];
4685        testexist=exist(backup,'file');     
4686    end
4687    [success,message]=copyfile(aviname,backup);%make backup of the existing file
4688    if isequal(success,1)
4689        delete(aviname)%delete existing file
4690    else
4691        msgbox_uvmat('ERROR',message)
4692        return
4693    end
4694end
4695%create avi open
4696aviobj=avifile(aviname,'Compression','None','fps',fps);
4697
4698%display first view for tests
4699newfig=figure;
4700newaxes=copyobj(handles.PlotAxes,newfig);%new plotting axes in the new figure
4701set(newaxes,'Tag','movieaxes')
4702nbpix=[512 384]*str2double(answer{3});
4703set(gcf,'Position',[1 1 nbpix])% resolution XVGA
4704set(newaxes,'Position',eval(answer{4}));
4705map=colormap(handles.PlotAxes);
4706colormap(map);%transmit the current colormap to the zoom fig
4707msgbox_uvmat('INPUT_Y-N',{['adjust figure ' num2str(newfig) ' with its matlab edit menu '] ;...
4708        ['then press OK to get the avi movie as a copy of figure ' num2str(newfig) ' display']});
4709UvData.plotaxes=newaxes;% the axis in the new figure becomes the current main plotting axes
4710set(huvmat,'UserData',UvData);
4711increment=str2num(get(handles.num_IndexIncrement,'String')); %get the field increment d
4712set(handles.STOP,'Visible','on')
4713set(handles.speed,'Visible','on')
4714set(handles.speed_txt,'Visible','on')
4715set(handles.Movie,'BusyAction','queue')
4716
4717%imin=str2double(get(handles.i1,'String'));
4718imax=str2double(answer{5});
4719% if isfield(UvData,'Time')
4720htitle=get(newaxes,'Title');
4721xlim=get(newaxes,'XLim');
4722ylim=get(newaxes,'YLim');
4723set(htitle,'Position',[xlim(2)+0.07*(xlim(2)-xlim(1)) ylim(2)-0.05*(ylim(2)-ylim(1)) 0])
4724time_str=get(handles.TimeValue,'String');
4725set(htitle,'String',['t=' time_str])
4726set(handles.speed,'Value',1)
4727for i=1:imax
4728    if get(handles.speed,'Value')~=0 && isequal(get(handles.MenuExportMovie,'BusyAction'),'queue') % enable STOP command
4729            runpm(hObject,eventdata,handles,increment)% run plus
4730            drawnow
4731            time_str=get(handles.TimeValue,'String');
4732            if ishandle(htitle)
4733             set(htitle,'String',['t=' time_str])
4734            end
4735            mov=getframe(newfig);
4736            aviobj=addframe(aviobj,mov);
4737    end
4738end
4739aviobj=close(aviobj);
4740UvData=rmfield(UvData,'plotaxes');
4741set(huvmat,'UserData',UvData);
4742msgbox_uvmat('CONFIRMATION',{['movie ' aviname ' created '];['with ' num2str(imax) ' frames']})
4743
4744
4745%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4746% Projection Objects Menu Callbacks
4747%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4748
4749% -----------------------------------------------------------------------
4750function Menupoints_Callback(hObject, eventdata, handles)
4751%------------------------------------------------------------------------
4752data.Type='points';
4753data.ProjMode='projection';%default
4754data.ProjModeMenu={};% do not restrict ProjMode menus
4755create_object(data,handles)
4756
4757% -----------------------------------------------------------------------
4758% --- Callback of the Menu command line
4759%------------------------------------------------------------------------
4760function Menuline_Callback(hObject, eventdata, handles)
4761%------------------------------------------------------------------------
4762data.Type='line';
4763data.ProjMode='projection';%default
4764data.ProjModeMenu={};% do not restrict ProjMode menus
4765create_object(data,handles)
4766
4767% -----------------------------------------------------------------------
4768% --- Callback of the Menu command line_x
4769%------------------------------------------------------------------------
4770function Menuline_x_Callback(hObject, eventdata, handles)
4771
4772data.Type='line_x';
4773data.ProjMode='projection';%default
4774data.ProjModeMenu={};% do not restrict ProjMode menus
4775create_object(data,handles)
4776
4777% -----------------------------------------------------------------------
4778% --- Callback of the Menu command line_y
4779% -----------------------------------------------------------------------
4780function Menuline_y_Callback(hObject, eventdata, handles)
4781
4782data.Type='line_y';
4783data.ProjMode='projection';%default
4784data.ProjModeMenu={};% do not restrict ProjMode menus
4785create_object(data,handles)
4786
4787%------------------------------------------------------------------------
4788function Menupolyline_Callback(hObject, eventdata, handles)
4789%------------------------------------------------------------------------
4790data.Type='polyline';
4791data.ProjMode='projection';%default
4792data.ProjModeMenu={};% do not restrict ProjMode menus
4793create_object(data,handles)
4794
4795%------------------------------------------------------------------------
4796function Menupolygon_Callback(hObject, eventdata, handles)
4797%------------------------------------------------------------------------
4798data.Type='polygon';
4799data.ProjMode='inside';%default
4800data.ProjModeMenu={};% do not restrict ProjMode menus
4801create_object(data,handles)
4802
4803%------------------------------------------------------------------------
4804function Menurectangle_Callback(hObject, eventdata, handles)
4805%------------------------------------------------------------------------
4806data.Type='rectangle';
4807data.ProjMode='inside';%default
4808data.ProjModeMenu={};% do not restrict ProjMode menus
4809create_object(data,handles)
4810
4811%------------------------------------------------------------------------
4812function Menuellipse_Callback(hObject, eventdata, handles)
4813%------------------------------------------------------------------------
4814data.Type='ellipse';
4815data.ProjMode='inside';%default
4816data.ProjModeMenu={};% do not restrict ProjMode menus
4817create_object(data,handles)
4818
4819%------------------------------------------------------------------------
4820function MenuMaskObject_Callback(hObject, eventdata, handles)
4821%------------------------------------------------------------------------
4822data.Type='polygon';
4823data.TypeMenu={'polygon'};
4824data.ProjMode='mask_inside';%default
4825data.ProjModeMenu={'mask_inside';'mask_outside'};
4826create_object(data,handles)
4827
4828%------------------------------------------------------------------------
4829function Menuplane_Callback(hObject, eventdata, handles)
4830%------------------------------------------------------------------------
4831data.Type='plane';
4832data.ProjMode='projection';%default
4833data.ProjModeMenu={};% do not restrict ProjMode menus
4834create_object(data,handles)
4835
4836%------------------------------------------------------------------------
4837function Menuvolume_Callback(hObject, eventdata, handles)
4838%------------------------------------------------------------------------
4839data.Type='volume';
4840data.ProjMode='interp_lin';%default
4841data.ProjModeMenu={};
4842% set(handles.create,'Visible','on')
4843% set(handles.create,'Value',1)
4844% VOLUME_Callback(hObject,eventdata,handles)data.ProjModeMenu={};
4845create_object(data,handles)
4846
4847%------------------------------------------------------------------------
4848% --- generic function used for the creation of a projection object
4849function create_object(data,handles)
4850%------------------------------------------------------------------------
4851%% desactivate concurrent tools
4852set(handles.MenuRuler,'checked','off')%desactivate ruler
4853hgeometry_calib=findobj(allchild(0),'tag','geometry_calib');% search the GUI geometric calibration
4854if ishandle(hgeometry_calib)
4855    hhgeometry_calib=guidata(hgeometry_calib);
4856    set(hhgeometry_calib.CheckEnableMouse,'Value',0)% desactivate mouse action in geometry_calib
4857    set(hhgeometry_calib.CheckEnableMouse,'BackgroundColor',[0.7 0.7 0.7])
4858end
4859set(handles.CheckEditObject,'Value',0)  %desactivate the object edit mode
4860CheckEditObject_Callback([],[],handles)
4861set(handles.CheckViewObject,'Value',0) % desactivate view_object (new object created)
4862set(handles.CheckZoomFig,'Value',0) %desactivate zoom sub fig
4863set(handles.CheckZoom,'Value',0)    %desactivate the zoom action
4864set(handles.MenuObject,'checked','on')% indicate object creation for mouse pointer display
4865if ishandle(handles.UVMAT_title)
4866    delete(handles.UVMAT_title)     %delete the initial display of uvmat if no field has been entered yet
4867end
4868
4869%% initiate the new projection object
4870UvData=get(handles.uvmat,'UserData');
4871data.Name=data.Type;% default name=type
4872data.Coord=[0 0]; %default
4873check_plot=0;
4874if isfield(UvData,'Field')
4875    Field=UvData.Field;
4876    if isfield(Field,'NbDim')&& isequal(Field.NbDim,3)
4877         data.Coord=[0 0 0]; %default
4878    end
4879    if isfield(Field,'CoordUnit')
4880        data.CoordUnit=Field.CoordUnit;
4881    end
4882    if isfield(UvData.Field,'CoordMesh')&&~isempty(UvData.Field.CoordMesh)
4883        data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
4884        switch data.Type
4885            case {'line','polyline','points'}
4886                data.RangeY=UvData.Field.CoordMesh;
4887            case 'line_x'
4888                check_plot=1; %plot the line directly when set_object is opened
4889                data.Type='line';
4890                data.RangeX=UvData.Field.XMin ;
4891                data.RangeY=UvData.Field.CoordMesh;
4892                data.Coord=[UvData.Field.XMin (UvData.Field.YMin +UvData.Field.YMax)/2;...
4893                           UvData.Field.XMax (UvData.Field.YMin +UvData.Field.YMax)/2];% put line at the middle of the y axis
4894            case 'line_y'
4895                check_plot=1; %plot the line directly when set_object is opened
4896                data.Type='line';
4897                data.RangeX=UvData.Field.YMin ;
4898                data.RangeY=UvData.Field.CoordMesh;
4899                data.Coord=[(UvData.Field.XMin+UvData.Field.XMax)/2 UvData.Field.YMin;...
4900                            (UvData.Field.XMin +UvData.Field.XMax)/2 UvData.Field.YMax];% put line at the middle of the y axis
4901            case {'rectangle','ellipse'}
4902                data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
4903                data.RangeX=UvData.Field.CoordMesh;
4904                data.RangeY=UvData.Field.CoordMesh;
4905            otherwise
4906                data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
4907        end
4908        data.DX=UvData.Field.CoordMesh;
4909        data.DY=UvData.Field.CoordMesh;
4910    end
4911end
4912
4913hset_object=set_object(data,handles);% call the GUI set_object
4914hchild=get(hset_object,'children');
4915set(hchild,'enable','on')
4916set(handles.DeleteObject,'Visible','on')% make the object delete button visible
4917if check_plot
4918    hhset_object=guidata(hset_object);
4919    set_object('REFRESH_Callback',1,[],hhset_object);% call the GUI set_object
4920end
4921set(handles.CheckViewField,'Visible','on')
4922set(handles.DeleteObject,'Visible','on')
4923set(handles.ListObject_1,'Visible','on')
4924set(handles.ListObject_1_title,'Visible','on')
4925
4926%------------------------------------------------------------------------
4927function MenuBrowseObject_Callback(hObject, eventdata, handles)
4928%------------------------------------------------------------------------
4929%get the object file
4930fileinput=uigetfile_uvmat('pick an xml object file:',get(handles.RootPath,'String'),'.xml');
4931if ~isempty(fileinput)
4932    %read the file
4933    [data,heading]=xml2struct(fileinput);
4934    if ~strcmp(heading,'ProjObject')
4935        msgbox_uvmat('WARNING','The xml file does not have the heading ProjObject for projection objects')
4936    end
4937    ListObject=get(handles.ListObject,'String');
4938    ListObject=[ListObject;{data.Name}];
4939    IndexObj=length(ListObject);
4940    UvData=get(handles.uvmat,'UserData');
4941    UvData.ProjObject{IndexObj}=[]; %create a new empty object
4942    UvData.ProjObject{IndexObj}.DisplayHandle.uvmat=[]; %no plot handle before plot_field operation
4943    UvData.ProjObject{IndexObj}.DisplayHandle.view_field=[]; %no plot handle before plot_field operation
4944    set(handles.uvmat,'UserData',UvData)
4945    set(handles.CheckViewObject,'Value',1)
4946    set(handles.CheckViewField,'Value',1)
4947    hset_object=set_object(data);% call the set_object interface
4948    hhset_object=guidata(hset_object);
4949    set_object('REFRESH_Callback',hObject,eventdata,hhset_object);% plot projection
4950    set(handles.CheckEditObject,'Value',0); %suppress the object edit mode
4951    CheckEditObject_Callback([],[],handles)
4952    set(handles.DeleteObject,'Visible','on')
4953end
4954
4955%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4956% MenuTools Callbacks
4957%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4958%------------------------------------------------------------------------
4959function MenuCalib_Callback(hObject, eventdata, handles)
4960%------------------------------------------------------------------------
4961%% suppress the second field if exists
4962if get(handles.SubField,'Value')
4963    set(handles.SubField,'Value',0)
4964    SubField_Callback(hObject, eventdata, handles)
4965end
4966UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4967
4968%% suppress competing tools
4969set(handles.MenuRuler,'checked','off')%desactivate ruler
4970set(handles.CheckZoom,'Value',0)
4971set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
4972set(handles.ListObject,'Value',1)
4973
4974%% initiate display of the GUI geometry_calib
4975data=[]; %default
4976if isfield(UvData,'CoordType')
4977    data.CoordType=UvData.CoordType;
4978end
4979[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
4980FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];
4981set(handles.view_xml,'BackgroundColor',[1 1 0])%indicate the reading of the current xml file by geometry_calib
4982geometry_calib(FileName);% call the geometry_calib interface   
4983set(handles.view_xml,'BackgroundColor',[1 1 1])%indicate the end of reading of the current xml file by geometry_calib
4984set(handles.MenuCalib,'checked','on')% indicate that MenuCalib is activated, test used by mouse action
4985
4986
4987% --------------------------------------------------------------------
4988% --- set the slice plane ro the set of slice planes when volume scan is used
4989function MenuSetSlice_Callback(hObject, eventdata, handles)
4990% --------------------------------------------------------------------
4991%% suppress the second input field if exists
4992if get(handles.SubField,'Value')
4993    set(handles.SubField,'Value',0)
4994    SubField_Callback(hObject, eventdata, handles)
4995end
4996
4997UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4998check=0;
4999if isfield(UvData,'XmlData')&&isfield(UvData.XmlData{1},'GeometryCalib')&& isfield(UvData.XmlData{1}.GeometryCalib,'SliceCoord')
5000    GeometryCalib=UvData.XmlData{1}.GeometryCalib;
5001else
5002    msgbox_uvmat('ERROR','3D geometric calibration needed before defining slices')
5003    return
5004end   
5005SliceCoord=GeometryCalib.SliceCoord;
5006InterfaceCoord=min(SliceCoord(:,3));
5007if isfield(GeometryCalib,'InterfaceCoord')
5008    InterfaceCoord=GeometryCalib.InterfaceCoord(1,3);
5009end
5010NbSlice=size(SliceCoord,1);
5011CheckVolumeScan=0;
5012if isfield(GeometryCalib,'CheckVolumeScan')
5013    CheckVolumeScan=GeometryCalib.CheckVolumeScan;
5014end     
5015RefractionIndex=1.33;
5016if isfield(GeometryCalib,'RefractionIndex')
5017    RefractionIndex=GeometryCalib.RefractionIndex;
5018end     
5019SliceAngle=[0 0 0];
5020if isfield(GeometryCalib,'SliceAngle')
5021    SliceAngle=GeometryCalib.SliceAngle;
5022end
5023
5024%% create the GUI set_slice
5025set(0,'Unit','points')
5026ScreenSize=get(0,'ScreenSize');% get the size of the screen, to put the fig on the upper right
5027Width=350;% fig width in points (1/72 inch)
5028Height=min(0.8*ScreenSize(4),300);
5029Left=ScreenSize(3)- Width-40; %right edge close to the right, with margin=40
5030Bottom=ScreenSize(4)-Height-40; %put fig at top right
5031hfig=findobj(allchild(0),'Tag','set_slice');
5032if ~isempty(hfig),delete(hfig), end; %delete existing version of the GUI
5033hfig=figure('name','set_slices','tag','set_slice','MenuBar','none','NumberTitle','off','Unit','points','Position',[Left,Bottom,Width,Height],'UserData',GeometryCalib);
5034BackgroundColor=get(hfig,'Color');
5035hh=0.14; % box height (relative)
5036ii=0.01; % gap between uicontrols
5037
5038ww=(1-5*ii)/4; % box width (relative)
5039% first raw of the GUI
5040uicontrol('Style','text','Units','normalized', 'Position', [2*ii+ww 0.95-ii-0.25*hh ww hh/2],'BackgroundColor',BackgroundColor,...
5041    'String','first','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','center');%title
5042uicontrol('Style','text','Units','normalized', 'Position', [3*ii+2*ww 0.95-ii-0.25*hh ww hh/2],'BackgroundColor',BackgroundColor,...
5043    'String','last','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','center');%title
5044uicontrol('Style','text','Units','normalized', 'Position', [4*ii+3*ww 0.95-ii-0.25*hh ww hh/2],'BackgroundColor',BackgroundColor,...
5045    'String','surface','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','center');%title
5046%  raw 2 of the GUI
5047uicontrol('Style','text','Units','normalized', 'Position', [ii 0.95-2*ii-0.75*hh ww hh/2],'BackgroundColor',BackgroundColor,...
5048    'String','Z','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','right');%title
5049uicontrol('Style','edit','Units','normalized', 'Position', [2*ii+ww 0.95-2*ii-hh ww hh],'tag','num_Z_1','BackgroundColor',[1 1 1],...
5050    'String',num2str(SliceCoord(1,3)),'FontUnits','points','FontSize',12,'FontWeight','bold','TooltipString','''num_Z_1'': z position of first slice');%edit box
5051uicontrol('Style','edit','Units','normalized', 'Position', [3*ii+2*ww 0.95-2*ii-hh ww hh],'tag','num_Z_2','BackgroundColor',[1 1 1],...
5052    'String',num2str(SliceCoord(end,3)),'FontUnits','points','FontSize',12,'FontWeight','bold','TooltipString','''num_Z_2'': z position of last slice');%edit box
5053uicontrol('Style','edit','Units','normalized', 'Position', [4*ii+3*ww 0.95-2*ii-hh ww hh],'tag','num_H','BackgroundColor',[1 1 1],...
5054    'String',num2str(InterfaceCoord),'FontUnits','points','FontSize',12,'FontWeight','bold','TooltipString','''num_H'': z position of the water surface (=Z_1 in air)');%edit box
5055%  raw 3 of the GUI
5056uicontrol('Style','text','Units','normalized', 'Position', [2*ii+ww 0.95-3*ii-1.75*hh 2*ww hh/2],'BackgroundColor',BackgroundColor,'Tag','Refraction_title',...
5057    'String','refraction index','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','right');%title
5058uicontrol('Style','edit','Units','normalized', 'Position', [4*ii+3*ww 0.95-3*ii-2*hh ww hh],'tag','num_RefractionIndex','BackgroundColor',[1 1 1],...
5059    'String',num2str(RefractionIndex),'FontUnits','points','FontSize',12,'FontWeight','bold','TooltipString','''num_RefractionIndex'': refraction index of water');
5060%  raw 4 of the GUI
5061uicontrol('Style','text','Units','normalized', 'Position', [ii 0.95-4*ii-3.25*hh ww hh],'BackgroundColor',BackgroundColor,'Tag','NbSlice_title',...
5062    'String','NbSlice','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','right');%title
5063uicontrol('Style','edit','Units','normalized', 'Position', [2*ii+ww 0.95-4*ii-3*hh ww hh],'tag','num_NbSlice','BackgroundColor',[1 1 1],...
5064    'String',num2str(NbSlice),'FontUnits','points','FontSize',12,'FontWeight','bold','TooltipString','''num_NbSlice'':number of slices');%edit box
5065uicontrol('Style','checkbox','Units','normalized', 'Position', [3*ii+2*ww 0.95-4*ii-3*hh 2*ww hh],'tag','CheckVolumeScan','BackgroundColor',BackgroundColor,...
5066    'String','volume scan','Value',CheckVolumeScan,'FontUnits','points','FontSize',12,'FontWeight','bold','TooltipString','''CheckVolumeScan'':=1 for volume scan (z varies with j index)');
5067%  raw 5 of the GUI
5068uicontrol('Style','text','Units','normalized', 'Position', [2*ii+2*ww 0.95-5*ii-4.2*hh ww hh/2],'BackgroundColor',BackgroundColor,'Tag','Angle_title_1',...
5069    'String','x axis','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','center');%title
5070uicontrol('Style','text','Units','normalized', 'Position', [3*ii+3*ww 0.95-5*ii-4.2*hh ww hh/2],'BackgroundColor',BackgroundColor,'Tag','Angle_title_2',...
5071    'String','y axis','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','center');%title
5072%  raw 6 of the GUI
5073uicontrol('Style','text','Units','normalized', 'Position', [ii 0.95-5*ii-4.75*hh 2*ww hh/2],'BackgroundColor',BackgroundColor,'Tag','NbSlice_title',...
5074    'String','tilt angle','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','right');%title
5075uicontrol('Style','edit','Units','normalized', 'Position', [3*ii+2*ww 0.95-5*ii-5*hh ww hh],'tag','num_SliceAngle_1','BackgroundColor',[1 1 1],...
5076    'String',num2str(SliceAngle(1)),'FontUnits','points','FontSize',12,'FontWeight','bold','TooltipString','''num_SliceAngle_1'':slice angle of inclination around the x axis');%edit box
5077uicontrol('Style','edit','Units','normalized', 'Position', [4*ii+3*ww 0.95-5*ii-5*hh ww hh],'tag','num_SliceAngle_2','BackgroundColor',[1 1 1],...
5078    'String',num2str(SliceAngle(2)),'FontUnits','points','FontSize',12,'FontWeight','bold','TooltipString','''num_SliceAngle_1'':slice angle of inclination around the y axis');%edit box
5079%  raw 7 of the GUI: pushbuttons
5080wwp=(1-4*ii)/3; %width of the push buttons
5081uicontrol('Style','pushbutton','Units','normalized', 'Position', [ii ii wwp hh],'BackgroundColor',[1 0 0],'String','APPLY','Callback',@(hObject,eventdata)set_slice_APPLY_Callback(hObject,eventdata),...
5082    'FontWeight','bold','FontUnits','points','FontSize',12,'TooltipString','''APPLY'': apply the output to the current field series in uvmat');
5083uicontrol('Style','pushbutton','Units','normalized', 'Position', [2*ii+wwp ii wwp hh],'BackgroundColor',[1 0 0],'String','REPLICATE','Callback',@(hObject,eventdata)set_slice_REPLICATE_Callback(hObject,eventdata),...
5084    'FontWeight','bold','FontUnits','points','FontSize',12,'TooltipString','''REPLICATE'': replicate the output for a series of experiments');
5085uicontrol('Style','pushbutton','Units','normalized', 'Position', [3*ii+2*wwp ii wwp hh],'Callback',@(hObject,eventdata)set_slice_Cancel_Callback(hObject,eventdata),...
5086    'String','Cancel','FontWeight','bold','FontUnits','points','FontSize',12,'TooltipString','''Cancel'': quit GUI without action');
5087drawnow
5088
5089%------------------------------------------------------------------------
5090% function called by pressing APPLY in the GUI  set_slices
5091function set_slice_APPLY_Callback(hObject,eventdata)
5092%------------------------------------------------------------------------   
5093
5094%% get the uvmat GUI data and read the current xml file
5095huvmat=findobj(allchild(0),'Tag','uvmat');
5096hhuvmat=guidata(huvmat);
5097[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(hhuvmat);
5098FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];%name of the xml file for calibration
5099[RootPath,SubDir,RootFile,tild,tild,tild,tild,FileExt]=fileparts_uvmat(FileName);
5100XmlFile=find_imadoc(RootPath,SubDir,RootFile,FileExt);
5101[s,errormsg]=imadoc2struct(XmlFile,'GeometryCalib');
5102if~isempty(errormsg)
5103    msgbox_uvmat('ERROR',errormsg)
5104    return
5105end
5106GeometryCalib=s.GeometryCalib;
5107
5108%% read the content of the GUI set_slice
5109SliceData=read_GUI(get(hObject,'parent'));
5110GeometryCalib.NbSlice=SliceData.NbSlice;
5111GeometryCalib.CheckVolumeScan=SliceData.CheckVolumeScan;
5112Z_plane=linspace(SliceData.Z(1),SliceData.Z(2),SliceData.NbSlice);
5113GeometryCalib.SliceCoord=Z_plane'*[0 0 1];
5114GeometryCalib.SliceAngle=zeros(GeometryCalib.NbSlice,3);
5115GeometryCalib.SliceAngle(:,1)=SliceData.SliceAngle(1)*ones(GeometryCalib.NbSlice,1);%rotation around x axis (to generalise)
5116GeometryCalib.SliceAngle(:,2)=SliceData.SliceAngle(2)*ones(GeometryCalib.NbSlice,1);%rotation around y axis (to generalise)
5117GeometryCalib.SliceAngle(:,3)=0;
5118GeometryCalib.InterfaceCoord=[0 0 SliceData.H];
5119GeometryCalib.RefractionIndex=SliceData.RefractionIndex;
5120
5121%% store the result in the xml file used for calibration
5122errormsg=update_imadoc(GeometryCalib,XmlFile,'GeometryCalib');% introduce the calibration data in the xml file
5123if strcmp(errormsg,'')
5124    msgbox_uvmat('CONFIRMATION',['slice positions saved in ' XmlFile]);
5125else
5126    msgbox_uvmat('ERROR',errormsg);
5127end
5128
5129%% display image with new calibration in the currently opened uvmat interface
5130set(hhuvmat.CheckFixLimits,'Value',0)% put FixedLimits option to 'off' to plot the whole image
5131uvmat('InputFileREFRESH_Callback',huvmat,[],hhuvmat); %file input with xml reading  in uvmat, show the image in phys coordinates
5132
5133%------------------------------------------------------------------------
5134% function called by pressing REPLICATE in the GUI  set_slices
5135function set_slice_REPLICATE_Callback(hObject,eventdata)
5136%------------------------------------------------------------------------
5137
5138%% read the GUI set_slice
5139SliceData=read_GUI(get(hObject,'parent'));
5140
5141%% get info on the GUI uvmat
5142huvmat=findobj(allchild(0),'Tag','uvmat');
5143hhuvmat=guidata(huvmat);
5144[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(hhuvmat);
5145
5146%% open the GUI browse_data
5147answer=msgbox_uvmat('INPUT_TXT','Campaign to calibrate with slice position?',fileparts(RootPath));
5148if strcmp(answer,'Cancel')
5149    return
5150end
5151OutPut=browse_data(answer);
5152nbcalib=0;
5153for ilist=1:numel(OutPut.Experiment)
5154    SubDirBase=regexprep(OutPut.DataSeries{1},'\..+$','');
5155    XmlFile=fullfile(OutPut.Campaign,OutPut.Experiment{ilist},[SubDirBase '.xml']);
5156   
5157    % read the current xml file
5158    [s,errormsg]=imadoc2struct(XmlFile,'GeometryCalib');
5159    if ~isempty(errormsg)
5160        msgbox_uvmat('ERROR',['error in reading ' XmlFile ': ' errormsg])
5161        return
5162    end
5163    GeometryCalib=s.GeometryCalib;
5164    GeometryCalib.NbSlice=SliceData.NbSlice;
5165    GeometryCalib.VolumeScan=SliceData.CheckVolumeScan;
5166    Z_plane=linspace(SliceData.Z(1),SliceData.Z(2),SliceData.NbSlice);
5167    GeometryCalib.SliceCoord=Z_plane'*[0 0 1];
5168    GeometryCalib.SliceAngle=zeros(GeometryCalib.NbSlice,3);
5169    GeometryCalib.SliceAngle(:,1)=SliceData.SliceAngle(1)*ones(GeometryCalib.NbSlice,1);%rotation around x axis (to generalise)
5170    GeometryCalib.SliceAngle(:,2)=SliceData.SliceAngle(2)*ones(GeometryCalib.NbSlice,1);%rotation around y axis (to generalise)
5171    GeometryCalib.SliceAngle(:,3)=0;
5172    GeometryCalib.InterfaceCoord=[0 0 SliceData.H];
5173    GeometryCalib.RefractionIndex=SliceData.RefractionIndex;
5174   
5175    % update the current xml file
5176    errormsg=update_imadoc(GeometryCalib,XmlFile,'GeometryCalib');% introduce the calibration data in the xml file
5177    if ~strcmp(errormsg,'')
5178        msgbox_uvmat('ERROR',errormsg);
5179    else
5180        display([XmlFile ' updated with slice positions'])
5181        nbcalib=nbcalib+1;
5182    end
5183end
5184msgbox_uvmat('CONFIMATION',[SubDirBase ' calibrated with slice positions for ' num2str(nbcalib) ' experiments']);
5185
5186%------------------------------------------------------------------------
5187% function called by pressing Cancel in the GUI  set_slices
5188function set_slice_Cancel_Callback(hObject,eventdata)
5189%------------------------------------------------------------------------
5190hfig=get(hObject,'parent');
5191delete(hfig)
5192
5193%-----------------------------------------------------------------------
5194function MenuLIFCalib_Callback(hObject, eventdata, handles)
5195%------------------------------------------------------------------------
5196%% read UvData properties stored on the uvmat interface
5197UvData=get(handles.uvmat,'UserData');
5198if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
5199    XmlData=UvData.XmlData{1};
5200else
5201    msgbox_uvmat('ERROR','geometric calibration needed: use Tools/geometric calibration in the menu bar');
5202    return
5203end
5204
5205%% read lines currently drawn
5206ListObj=UvData.ProjObject;
5207select=zeros(1,numel(ListObj));
5208for iobj=1:numel(ListObj);
5209    if isfield(ListObj{iobj},'Type') && strcmp(ListObj{iobj}.Type,'line')
5210        select(iobj)=1;
5211    end
5212end
5213val=find(select);
5214if numel(val)<2
5215    msgbox_uvmat('ERROR','light rays must be defined by at least two lines created by Projection object/line in the menu bar');
5216    return
5217else
5218    set(handles.ListObject,'Value',val);% show the selected lines on the list
5219    ObjectData=UvData.ProjObject(val);
5220    for iobj=1:length(ObjectData)
5221            xA(iobj)=ObjectData{iobj}.Coord(1,1);
5222            yA(iobj)=ObjectData{iobj}.Coord(1,2);
5223            xB(iobj)=ObjectData{iobj}.Coord(2,1);
5224            yB(iobj)=ObjectData{iobj}.Coord(2,2);
5225    end
5226end
5227
5228%% find the origin as intersection of the two first lines (see http://www.ahristov.com/tutorial/geometry-games/intersection-lines.html )
5229x1=xA(1);x2=xB(1);
5230x3=xA(2);x4=xB(2);
5231y1=yA(1);y2=yB(1);
5232y3=yA(2);y4=yB(2);
5233D = (x1-x2)*(y3-y4) -(y1-y2)*(x3-x4);
5234if D==0
5235    msgbox_uvmat('ERROR','the two lines are parallel');
5236    return
5237end
5238x0=((x3-x4)*(x1*y2-y1*x2)-(x1-x2)*(x3*y4-y3*x4))/D;
5239y0=((y3-y4)*(x1*y2-y1*x2)-(y1-y2)*(x3*y4-y3*x4))/D;
5240XmlData.Illumination.Origin=[x0 y0];
5241XmlData.PolarCentre=[x0 y0];
5242
5243%% display the current image in polar coordinates with origin at the  illumination source
5244currentdir=pwd; 
5245uvmatpath=fileparts(which('uvmat'));
5246cd(fullfile(uvmatpath,'transform_field'));
5247phys_polar=str2func('phys_polar');
5248cd(currentdir)
5249DataOut=phys_polar(UvData.Field,XmlData);
5250view_field(DataOut);
5251
5252%% use the third line for reference luminosity
5253if numel(val)==3
5254    x_ref=linspace(ObjectData{3}.Coord(1,1),ObjectData{3}.Coord(2,1),10);
5255    y_ref=linspace(ObjectData{3}.Coord(1,2),ObjectData{3}.Coord(2,2),10);
5256    x_ref=x_ref-x0;
5257    y_ref=y_ref-y0;
5258    [theta_ref,r_ref] = cart2pol(x_ref,y_ref);%theta_ref  and r_ref are the polar coordinates of the points on the line
5259    theta_ref=theta_ref*180/pi;
5260    figure
5261    plot(theta_ref,r_ref)
5262    azimuth_ima=linspace(DataOut.AY(1),DataOut.AY(2),size(DataOut.A,1));%profile of x index on the transformed image
5263    dist_source = interp1(theta_ref,r_ref,azimuth_ima);
5264    dist_source_pixel=round(size(DataOut.A,2)*(dist_source-DataOut.AX(1))/(DataOut.AX(2)-DataOut.AX(1)));
5265    line_nan= isnan(dist_source_pixel);
5266    dist_source_pixel(line_nan)=1;
5267    width=20; %number of pixels used for reference
5268    DataOut.A=double(DataOut.A);
5269    Anorm=zeros(size(DataOut.A));
5270    Aval=mean(mean(DataOut.A));
5271    for iline=1:size(DataOut.A,1)
5272        lum(iline)=mean(DataOut.A(iline,dist_source_pixel(iline):dist_source_pixel(iline)+width));
5273        Anorm(iline,:)=uint16(Aval*DataOut.A(iline,:)/lum(iline));
5274    end
5275    lum(line_nan)=NaN;
5276    figure
5277    plot(1:size(DataOut.A,1),lum)
5278end
5279ImaName=regexprep([get(handles.RootFile,'String') get(handles.FileIndex,'String')],'//','');
5280NewImageName=fullfile(get(handles.RootPath,'String'),'polar',[ImaName get(handles.FileExt,'String')]);
5281imwrite(Anorm,NewImageName,'BitDepth',16)
5282
5283%% record the origin in the xml file
5284XmlFileName=find_imadoc(get(handles.RootPath,'String'),get(handles.SubDir,'String'),get(handles.RootFile,'String'),get(handles.FileExt,'String'));
5285answer=msgbox_uvmat('INPUT_Y-N','save the illumination origin in the current xml file?');
5286if strcmp(answer,'Yes')
5287    t=xmltree(XmlFileName); %read the file
5288    title=get(t,1,'name');
5289    if ~strcmp(title,'ImaDoc')
5290        msgbox_uvmat('ERROR','wrong xml file');
5291        return
5292    end
5293    % backup the output file if it already exist, and read it
5294    backupfile=XmlFileName;
5295    testexist=2;
5296    while testexist==2
5297        backupfile=[backupfile '~'];
5298        testexist=exist(backupfile,'file');
5299    end
5300    [success,message]=copyfile(XmlFileName,backupfile);%make backup
5301    if success~=1
5302        errormsg=['errror in xml file backup: ' message];
5303        return
5304    end
5305    uid_illumination=find(t,'ImaDoc/Illumination');
5306    if isempty(uid_illumination)  %if GeometryCalib does not already exists, create it
5307        [t,uid_illumination]=add(t,1,'element','Illumination');
5308    end
5309    uid_origin=find(t,'ImaDoc/Illumination/Origin');
5310    if ~isempty(uid_origin)  %if GeometryCalib does not already exists, create it
5311         t=delete(t,uid_origin);
5312    end
5313    % save the illumination origin
5314    t=struct2xml(XmlData.Illumination,t,uid_illumination);
5315    save(t,XmlFileName);
5316end
5317   
5318
5319
5320%------------------------------------------------------------------------
5321function MenuMask_Callback(hObject, eventdata, handles)
5322%------------------------------------------------------------------------
5323UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
5324ListObj=UvData.ProjObject;
5325select=zeros(1,numel(ListObj));
5326for iobj=1:numel(ListObj);
5327    if strcmp(ListObj{iobj}.ProjMode,'mask_inside')||strcmp(ListObj{iobj}.ProjMode,'mask_outside')
5328        select(iobj)=1;
5329    end
5330end
5331val=find(select);
5332if isempty(val)
5333    msgbox_uvmat('ERROR','polygons must be first created by Projection object/mask polygon in the menu bar');
5334    return
5335else
5336    set(handles.ListObject,'Value',val);
5337    flag=1;
5338    if ~isfield(UvData.Field,'A')
5339            msgbox_uvmat('ERROR','an image needs to be opened to set the mask size');
5340    return
5341    end
5342    npx=size(UvData.Field.A,2);
5343    npy=size(UvData.Field.A,1);
5344    xi=0.5:npx-0.5;
5345    yi=0.5:npy-0.5;
5346    [Xi,Yi]=meshgrid(xi,yi);
5347        for iobj=1:length(UvData.ProjObject)
5348            ObjectData=UvData.ProjObject{iobj};
5349            if isfield(ObjectData,'ProjMode') &&(isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside'));
5350                flagobj=1;
5351                testphys=0; %coordinates in pixels by default
5352                if isfield(ObjectData,'CoordUnit') && ~isequal(ObjectData.CoordUnit,'pixel')
5353                    if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
5354                        Calib=UvData.XmlData{1}.GeometryCalib;
5355                        testphys=1;
5356                    end
5357                end
5358                if isfield(ObjectData,'Coord')&& isfield(ObjectData,'Type')
5359                    if isequal(ObjectData.Type,'polygon')
5360                        X=ObjectData.Coord(:,1);
5361                        Y=ObjectData.Coord(:,2);
5362                        if testphys
5363                            pos=[X Y zeros(size(X))];
5364                            if isfield(Calib,'SliceCoord') && length(Calib.SliceCoord)>=3
5365                                if isfield(Calib,'SliceAngle')&&~isequal(Calib.SliceAngle,[0 0 0])
5366                                    om=norm(Calib.SliceAngle);%norm of rotation angle in radians
5367                                    OmAxis=Calib.SliceAngle/om; %unit vector marking the rotation axis
5368                                    cos_om=cos(pi*om/180);
5369                                    sin_om=sin(pi*om/180);
5370                                    pos=cos_om*pos+sin_om*cross(OmAxis,pos)+(1-cos_om)*(OmAxis*pos')*OmAxis;
5371                                end
5372                                pos(:,1)=pos(:,1)+Calib.SliceCoord(1);
5373                                pos(:,2)=pos(:,2)+Calib.SliceCoord(2);
5374                                pos(:,3)=pos(:,3)+Calib.SliceCoord(3);
5375                            end                           
5376                            [X,Y]=px_XYZ(Calib,pos(:,1),pos(:,2),pos(:,3));
5377                        end
5378                        flagobj=~inpolygon(Xi,Yi,X',Y');%=0 inside the polygon, 1 outside
5379                    elseif isequal(ObjectData.Type,'ellipse')
5380                        if testphys
5381                            %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
5382                        end
5383                        RangeX=max(ObjectData.RangeX);
5384                        RangeY=max(ObjectData.RangeY);
5385                        X2Max=RangeX*RangeX;
5386                        Y2Max=RangeY*RangeY;
5387                        distX=(Xi-ObjectData.Coord(1,1));
5388                        distY=(Yi-ObjectData.Coord(1,2));
5389                        flagobj=(distX.*distX/X2Max+distY.*distY/Y2Max)>1;
5390                    elseif isequal(ObjectData.Type,'rectangle')
5391                        if testphys
5392                            %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
5393                        end
5394                        distX=abs(Xi-ObjectData.Coord(1,1));
5395                        distY=abs(Yi-ObjectData.Coord(1,2));
5396                        flagobj=distX>max(ObjectData.RangeX) | distY>max(ObjectData.RangeY);
5397                    end
5398                    if isequal(ObjectData.ProjMode,'mask_outside')
5399                        flagobj=~flagobj;
5400                    end
5401                    flag=flag & flagobj;
5402                end
5403            end
5404        end
5405    %mask name
5406    RootPath=get(handles.RootPath,'String');
5407    SubDir=get(handles.SubDir,'String');
5408    RootFile=get(handles.RootFile,'String');
5409    if ~isempty(RootFile)&&(isequal(RootFile(1),'/')|| isequal(RootFile(1),'\'))
5410        RootFile(1)=[];
5411    end
5412    list=get(handles.masklevel,'String');
5413    masknumber=num2str(length(list));
5414    maskindex=get(handles.masklevel,'Value');
5415    mask_name=fullfile_uvmat(RootPath,[SubDir '.mask'],'mask','.png','_1',maskindex);
5416    imflag=uint8(255*(0.392+0.608*flag));% =100 for flag=0 (vectors not computed when 20<imflag<200)
5417    imflag=flipdim(imflag,1);
5418
5419    %display the mask
5420    hfigmask=figure;
5421    set(hfigmask,'Name','mask image')
5422    vec=linspace(0,1,256);%define a linear greyscale colormap
5423    map=[vec' vec' vec'];
5424    colormap(map)
5425    image(imflag);
5426    answer=msgbox_uvmat('INPUT_TXT','mask file name:', mask_name);
5427    if ~strcmp(answer,'Cancel')
5428        mask_dir=fileparts(answer);
5429        if ~exist(mask_dir,'dir')
5430            [xx,msg1]=mkdir(mask_dir);
5431            if ~strcmp(msg1,'')
5432                errormsg=['cannot create ' mask_dir ': ' msg1];%error message for directory creation
5433                return
5434            end
5435        end
5436        imwrite(imflag,answer,'BitDepth',8);
5437    end
5438    set(handles.ListObject,'Value',1)
5439end
5440
5441%------------------------------------------------------------------------
5442%-- open the GUI set_grid.fig to create grid
5443function MenuGrid_Callback(hObject, eventdata, handles)
5444%------------------------------------------------------------------------
5445%suppress the other options if grid is chosen
5446set(handles.edit_vect,'Value',0)
5447edit_vect_Callback(hObject, eventdata, handles)
5448set(handles.ListObject,'Value',1)     
5449
5450%prepare display of the set_grid GUI
5451[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
5452FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];
5453UvData=get(handles.uvmat,'UserData');
5454% CoordList=get(handles.TransformName,'String');
5455% val=get(handles.TransformName,'Value');
5456set_grid(FileName,UvData.Field);% call the set_object interface
5457
5458
5459%------------------------------------------------------------------------
5460function MenuRuler_Callback(hObject, eventdata, handles)
5461%------------------------------------------------------------------------
5462if strcmp(get(handles.MenuRuler,'checked'),'on')
5463    set(handles.MenuRuler,'checked','off')%desactivate if activated
5464else
5465    set(handles.MenuRuler,'checked','on')%activate if selected
5466    set(handles.CheckZoom,'Value',0)
5467    CheckZoom_Callback(handles.uvmat, [], handles)
5468    UvData=get(handles.uvmat,'UserData');
5469    UvData.MouseAction='ruler';
5470    set(handles.uvmat,'UserData',UvData);
5471end
5472
5473%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5474% MenuRun Callbacks
5475%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5476
5477%------------------------------------------------------------------------
5478% open the GUI 'series'
5479function MenuSeries_Callback(hObject, eventdata, handles)
5480%------------------------------------------------------------------------
5481Param=read_param(handles);
5482series(Param); %run the series interface
5483
5484% --------------------------------------------------------------------
5485function MenuPIV_Callback(hObject, eventdata, handles)
5486    Param=read_param(handles);
5487%     Param.ActionName='civ_series';
5488hseries=series(Param);
5489hhseries=guidata(hseries);
5490ActionMenu=get(hhseries.ActionName,'String');
5491index_action=find(strcmp('civ_series',ActionMenu));
5492set(hhseries.ActionName,'Value',index_action);
5493series('ActionName_Callback',hObject,eventdata,hhseries); %file input with xml reading  in uvmat, show the image in phys coordinates
5494
5495
5496%------------------------------------------------------------------------
5497% -- open the GUI civ.fig for PIV
5498function MenuCIVx_Callback(hObject, eventdata, handles)
5499%------------------------------------------------------------------------
5500 [RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
5501 FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];
5502civ(FileName);% interface de civ(not in the uvmat file)
5503
5504function Param=read_param(handles)
5505   
5506[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
5507Param.FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];%first input file name
5508if isequal(get(handles.SubField,'Value'),1)
5509    [RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
5510    FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];
5511    if ~isequal(FileName_1,Param.FileName)
5512        Param.FileName_1=FileName_1;%second input file name if relevant
5513    end
5514end
5515Param.NomType=get(handles.NomType,'String');
5516Param.NomType_1=get(handles.NomType_1,'String');
5517Param.CheckFixPair=get(handles.CheckFixPair,'Value');
5518UvData=get(handles.uvmat,'UserData');
5519if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'Time')
5520    Param.Time=UvData.XmlData{1}.Time;
5521end
5522if isequal(get(handles.scan_i,'Value'),1)
5523    Param.incr_i=str2num(get(handles.num_IndexIncrement,'String'));
5524elseif isequal(get(handles.scan_j,'Value'),1)
5525    Param.incr_j=str2num(get(handles.num_IndexIncrement,'String'));
5526end
5527
5528%% transfer fields and coordinate names
5529Param.list_fields=get(handles.FieldName,'String');% list menu fields
5530FieldName=Param.list_fields{get(handles.FieldName,'Value')};
5531ind_image=find(strcmp('image',Param.list_fields));
5532if ~isempty(ind_image) && numel(Param.list_fields)>1
5533    Param.list_fields(ind_image)=[]; %suppress  'image' option
5534end
5535Param.index_fields=find(strcmp(FieldName,Param.list_fields));% selected string index
5536Param.list_fields_1=get(handles.FieldName_1,'String');% list menu fields
5537if ischar(Param.list_fields_1),Param.list_fields_1={Param.list_fields_1};end
5538FieldName_1=Param.list_fields_1{get(handles.FieldName_1,'Value')};
5539ind_image=find(strcmp('image',Param.list_fields_1));
5540if ~isempty(ind_image) && numel(Param.list_fields_1)>1
5541    Param.list_fields_1(ind_image)=[]; %suppress  'image' option
5542end
5543Param.index_fields_1=find(strcmp(FieldName_1,Param.list_fields_1));% selected string index
5544TransformList=get(handles.TransformName,'String');
5545Param.TransformName=TransformList{get(handles.TransformName,'Value')};
5546Param.Coord_x_str=get(handles.Coord_x,'String');
5547Param.Coord_x_val=get(handles.Coord_x,'Value');
5548Param.Coord_y_str=get(handles.Coord_y,'Data');
5549
5550% --------------------------------------------------------------------
5551function MenuHelp_Callback(hObject, eventdata, handles)
5552% --------------------------------------------------------------------
5553web('http://servforge.legi.grenoble-inp.fr/projects/soft-uvmat/wiki/UvmatHelp')
5554
5555% path_to_uvmat=which ('uvmat');% check the path of uvmat
5556% pathelp=fileparts(path_to_uvmat);
5557% helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
5558% if isempty(dir(helpfile)), msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
5559% else
5560%     addpath (fullfile(pathelp,'uvmat_doc'))
5561%     web(helpfile);
5562% end
5563
5564% --- Executes on selection change in Coord_y.
5565function Coord_y_Callback(hObject, eventdata, handles)
5566
5567% --- Executes on selection change in Coord_x.
5568function Coord_x_Callback(hObject, eventdata, handles)
5569
5570
5571% --- Executes on button press in CheckColorBar.
5572function CheckColorBar_Callback(hObject, eventdata, handles)
5573
5574
5575
5576function TransformPath_Callback(hObject, eventdata, handles)
5577% hObject    handle to TransformPath (see GCBO)
5578% eventdata  reserved - to be defined in a future version of MATLAB
5579% handles    structure with handles and user data (see GUIDATA)
5580
5581% Hints: get(hObject,'String') returns contents of TransformPath as text
5582%        str2double(get(hObject,'String')) returns contents of TransformPath as a double
5583
5584
5585%TODO: use to modify fill_GUI
5586%'write_plot_param': update the plotting parameters on the uvmat or view_field interface after a plotting operation
5587function write_plot_param(handles,PlotParam)
5588%% coordinates
5589if isempty(PlotParam.Coordinates)
5590    set(handles.Coordinates,'Visible','off')
5591    set(handles.PlotAxes,'Visible','off')
5592    set(handles.text_display,'Visible','off')
5593    set(handles.TableDisplay,'Visible','on')
5594else
5595    set(handles.Coordinates,'Visible','on')
5596    set(handles.PlotAxes,'Visible','on')
5597    set(handles.text_display,'Visible','on')
5598    if isfield(handles,'TableDisplay')
5599    set(handles.TableDisplay,'Visible','off')
5600    end
5601    Coordinates=PlotParam.Coordinates;
5602    if isfield(Coordinates,'CheckFixAspectRatio')
5603        if Coordinates.CheckFixAspectRatio
5604            set(handles.CheckFixAspectRatio,'Value',1)
5605        else
5606            set(handles.CheckFixAspectRatio,'Value',0)
5607 
5608        end
5609    end
5610    if isfield(Coordinates,'AspectRatio')
5611        set(handles.num_AspectRatio,'String',num2str(Coordinates.AspectRatio))
5612    end
5613    if isfield(Coordinates,'MinX')
5614        set(handles.num_MinX,'String',num2str(Coordinates.MinX,4));
5615        set(handles.num_MaxX,'String',num2str(Coordinates.MaxX,4));
5616        set(handles.num_MinY,'String',num2str(Coordinates.MinY,4));
5617        set(handles.num_MaxY,'String',num2str(Coordinates.MaxY,4));
5618    else
5619        set(handles.num_MinX,'String','');
5620        set(handles.num_MaxX,'String','');
5621        set(handles.num_MinY,'String','');
5622        set(handles.num_MaxY,'String','');
5623    end
5624end
5625
5626%% scalar or image parameters
5627if isfield(PlotParam,'Scalar')
5628    set(handles.Scalar,'Visible','on')
5629    if isfield(PlotParam.Scalar,'MaxA')
5630        set(handles.num_MaxA,'String',num2str(PlotParam.Scalar.MaxA,3));
5631    end
5632    if isfield(PlotParam.Scalar,'MinA')
5633        set(handles.num_MinA,'String',num2str(PlotParam.Scalar.MinA,3));
5634    end   
5635    if isfield(PlotParam.Scalar,'IncrA')
5636        set(handles.num_IncrA,'String',num2str(PlotParam.Scalar.IncrA,3))
5637    end
5638    set(handles.CheckBW,'Value',PlotParam.Scalar.CheckBW)
5639    if isfield(PlotParam.Scalar,'Opacity')&&isfield(handles,'num_Opacity')
5640        set(handles.num_Opacity,'String',num2str(PlotParam.Scalar.Opacity))
5641    end
5642else
5643    set(handles.Scalar,'Visible','off')
5644end
5645
5646%% parameter for vector field
5647if isfield(PlotParam,'Vectors')
5648    set(handles.Vectors,'Visible','on')
5649    if isfield(PlotParam.Vectors,'VecScale')
5650        set(handles.num_VecScale,'String',num2str(PlotParam.Vectors.VecScale,3))
5651    end
5652    if isfield(PlotParam.Vectors,'MinC')&& isfield(PlotParam.Vectors,'MaxC')
5653        MinC=PlotParam.Vectors.MinC;
5654        MaxC=PlotParam.Vectors.MaxC;
5655        set(handles.num_MinVec,'String', num2str(MinC,3));
5656        set(handles.num_MaxVec,'String',num2str(MaxC,3));
5657        list=get(handles.ColorCode,'String');
5658        ichoice=get(handles.ColorCode,'Value');
5659        color_option=list{ichoice};
5660        test3color=strcmp(color_option,'rgb')||strcmp(color_option,'bgr');
5661        if test3color% need to update color thresholds
5662            set(handles.num_ColCode1,'Visible','on')
5663            set(handles.num_ColCode2,'Visible','on')
5664            set(handles.Slider1,'Visible','on')
5665            set(handles.Slider2,'Visible','on')
5666            set(handles.num_ColCode1,'String',num2str(PlotParam.Vectors.ColCode1,3))
5667            set(handles.num_ColCode2,'String',num2str(PlotParam.Vectors.ColCode2,3))
5668            set(handles.Slider1,'Value',(PlotParam.Vectors.ColCode1-MinC)/(MaxC-MinC))
5669            set(handles.Slider2,'Value',(PlotParam.Vectors.ColCode2-MinC)/(MaxC-MinC))
5670        else
5671            set(handles.num_ColCode1,'Visible','off')
5672            set(handles.num_ColCode2,'Visible','off')
5673            set(handles.Slider1,'Visible','off')
5674            set(handles.Slider2,'Visible','off')
5675        end
5676    end
5677else
5678    set(handles.Vectors,'Visible','off')
5679    if isfield(handles,'edit_vect')
5680        set(handles.edit_vect,'Visible','off')
5681        set(handles.record,'Visible','off')
5682    end
5683end
5684
5685% --------------------------------------------------------------------
5686% --- Executes on button press in CheckTable.
5687% --------------------------------------------------------------------
5688function CheckTable_Callback(hObject, eventdata, handles)
5689if get(handles.CheckTable,'Value')
5690    set(handles.TableDisplay,'Visible','on')
5691else
5692    set(handles.TableDisplay,'Visible','off')
5693end
Note: See TracBrowser for help on using the repository browser.