source: trunk/src/uvmat.m @ 646

Last change on this file since 646 was 646, checked in by sommeria, 7 years ago

various update, bugs to be expected

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