source: trunk/src/uvmat.m @ 520

Last change on this file since 520 was 520, checked in by sommeria, 9 years ago

new bugs corrected

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