source: trunk/src/uvmat.m @ 669

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

a few bugs corrected

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