source: trunk/src/uvmat.m @ 540

Last change on this file since 540 was 540, checked in by sommeria, 12 years ago

bugs corrected

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