source: trunk/src/uvmat.m @ 591

Last change on this file since 591 was 591, checked in by sommeria, 11 years ago

various updates, in particular modification of series to do calculations in the cluster

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