source: trunk/src/uvmat.m @ 421

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

bugs corrections and improvements following tutorial presentation

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