source: trunk/src/uvmat.m @ 684

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

corrections in proj_field: reducing the field of an image, and read_field: reading norm of vectors on gridded mesh

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