source: trunk/src/uvmat.m @ 638

Last change on this file since 638 was 638, checked in by sommeria, 8 years ago

bug with mask corrected in uvmat. Update of browser in series

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