source: trunk/src/uvmat.m @ 460

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

cleaning and bugs corrected

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