source: trunk/src/uvmat.m @ 507

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

various improvments and corrections
dtatatree_browser tested

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