source: trunk/src/uvmat.m @ 683

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

bug for movie reading correcteed in uvmat

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    dt=(UvData.XmlData{1}.Time(num_i2+1,num_j2+1)-UvData.XmlData{1}.Time(num_i1+1,num_j1+1));
1909    if  isfield(UvData,'TimeUnit')
1910        set(handles.Dt_txt,'String',['Dt=' num2str(1000*dt,3) '  m' UvData.TimeUnit] )
1911    else
1912        set(handles.Dt_txt,'String',['Dt=' num2str(1000*dt,3) '  10^(-3)'] )
1913    end
1914else
1915    set(handles.Dt_txt,'String','')
1916end
1917
1918%% get the first image
1919%Field.AName='image';
1920if index==1
1921    Field_a=UvData.Field;% movie on the second field
1922else
1923    Field_a=UvData.Field_1;% movie on the first field
1924end
1925
1926%% read the second image
1927MovieObject=[];
1928if numel(UvData.MovieObject)>=index
1929    MovieObject=UvData.MovieObject{index};
1930end
1931[Field_b,ParamOut,errormsg] = read_field(imaname_1,UvData.FileType{index},MovieObject,num_frame);
1932
1933%px to phys or other transform on field
1934transform=get(handles.TransformPath,'UserData');
1935if  ~isempty(transform)
1936    if isfield(UvData,'XmlData') && numel(UvData.XmlData)>=index %use geometry calib recorded from the ImaDoc xml file as first priority
1937        if index==2
1938        Field_a=transform(Field_a,UvData.XmlData{index});%the first field has been stored without transform
1939        end
1940        Field_b=transform(Field_b,UvData.XmlData{index});
1941    end
1942end
1943
1944% make movie until movie speed is set to 0 or STOP is activated
1945hima=findobj(handles.PlotAxes,'Tag','ima');% %handles.PlotAxes =main plotting window (A GENERALISER)
1946set(handles.STOP,'Visible','on')
1947set(handles.speed,'Visible','on')
1948set(handles.speed_txt,'Visible','on')
1949set(handles.i2,'BackgroundColor',[1 1 1])% mark the edit box in white to indicate its use as input
1950set(handles.j2,'BackgroundColor',[1 1 1])% mark the edit box in white to indicate its use as input
1951set(handles.FileIndex,'BackgroundColor',[1 1 1])% mark the edit box in white to indicate its use as input
1952while get(handles.speed,'Value')~=0 && isequal(get(handles.movie_pair,'BusyAction'),'queue')%isequal(get(handles.run0,'BusyAction'),'queue'); % enable STOP command
1953    % read and plot the series of images in non erase mode
1954    set(hima,'CData',Field_b.A);
1955    pause(1.02-get(handles.speed,'Value'));% wait for next image
1956    set(hima,'CData',Field_a.A);
1957    pause(1.02-get(handles.speed,'Value'));% wait for next image
1958end
1959set(handles.movie_pair,'BackgroundColor',[1 0 0])%paint the command button in red
1960set(handles.movie_pair,'Value',0)
1961set(handles.Dt_txt,'String','')
1962
1963%------------------------------------------------------------------------
1964% --- Executes on button press in run0.
1965function run0_Callback(hObject, eventdata, handles)
1966%------------------------------------------------------------------------
1967set(handles.run0,'BackgroundColor',[1 1 0])%paint the command button in yellow
1968drawnow
1969[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
1970[tild,tild,tild,i1,i2,j1,j2]=fileparts_uvmat(FileIndex);% check back the indices used
1971if isempty(i2), set(handles.i2,'String',''); end % suppress the second index display if not used
1972if isempty(j2), set(handles.j2,'String',''); end
1973filename=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];
1974filename_1='';%default
1975FileIndex_1='';
1976if get(handles.SubField,'Value')
1977    [RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
1978    filename_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];
1979end
1980num_i1=stra2num(get(handles.i1,'String'));
1981num_i2=stra2num(get(handles.i2,'String'));
1982num_j1=stra2num(get(handles.j1,'String'));
1983num_j2=stra2num(get(handles.j2,'String'));
1984[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
1985if isempty(j1_1)% case of movies, the index is not given by file index
1986    j1_1=num_j1;
1987end
1988
1989errormsg=refresh_field(handles,filename,filename_1,num_i1,num_i2,num_j1,num_j2,i1_1,i2_1,j1_1,j2_1);
1990
1991if ~isempty(errormsg)
1992      msgbox_uvmat('ERROR',errormsg);
1993else
1994    set(handles.i1,'BackgroundColor',[1 1 1])
1995    set(handles.i2,'BackgroundColor',[1 1 1])
1996    set(handles.j1,'BackgroundColor',[1 1 1])
1997    set(handles.j2,'BackgroundColor',[1 1 1])
1998    set(handles.FileIndex,'BackgroundColor',[1 1 1])
1999    set(handles.FileIndex_1,'BackgroundColor',[1 1 1]) 
2000    set(handles.run0,'BackgroundColor',[1 0 0])
2001end   
2002
2003%------------------------------------------------------------------------
2004% --- read the input files and refresh all the plots, including projection.
2005% OUTPUT:
2006%  errormsg: error message char string  =[] by default
2007% INPUT:
2008% FileName: first input file (=[] in the absence of input file)
2009% FileName_1: second input file (=[] in the asbsence of second input file)
2010% num_i1,num_i2,num_j1,num_j2; frame indices
2011% i1_1,i2_1,j1_1,j2_1: frame indices for the second input file  (needed if FileName_1 is not empty)
2012%------------------------------------------------------------------------
2013function errormsg=refresh_field(handles,FileName,FileName_1,num_i1,num_i2,num_j1,num_j2,i1_1,i2_1,j1_1,j2_1)
2014%------------------------------------------------------------------------
2015
2016%% initialisation
2017if ~exist('Field','var')
2018    Field={};
2019end
2020UvData=get(handles.uvmat,'UserData');
2021if ishandle(handles.UVMAT_title) %remove title panel on uvmat
2022    delete(handles.UVMAT_title)
2023end
2024
2025%% determine the main input file information for action
2026if ~exist(FileName,'file')
2027    errormsg=['input file ' FileName ' does not exist'];
2028    return
2029end
2030NomType=get(handles.NomType,'String');
2031NomType_1='';
2032if strcmp(get(handles.NomType_1,'Visible'),'on')
2033    NomType_1=get(handles.NomType_1,'String');
2034end
2035%update the z position index
2036mode_slice=get(handles.slices,'String');
2037if strcmp(mode_slice,'volume')
2038    z_index=num_j1;
2039    set(handles.z_index,'String',num2str(z_index))
2040else
2041    nbslice=str2num(get(handles.num_NbSlice,'String'));
2042    z_index=mod(num_i1-1,nbslice)+1;
2043    set(handles.z_index,'String',num2str(z_index))
2044end
2045% refresh menu for save_mask if relevant
2046masknumber=get(handles.masklevel,'String');
2047if length(masknumber)>=z_index
2048    set(handles.masklevel,'Value',z_index)
2049end
2050
2051%% test for need of tps
2052check_proj_tps=0;
2053if  (strcmp(UvData.FileType{1},'civdata')||strcmp(UvData.FileType{1},'civx'))
2054    for iobj=1:numel(UvData.ProjObject)
2055        if isfield(UvData.ProjObject{iobj},'ProjMode')&& strcmp(UvData.ProjObject{iobj}.ProjMode,'interp_tps')
2056            check_proj_tps=1;
2057            break
2058        end
2059    end
2060end
2061
2062%% read the first input field
2063ParamIn.ColorVar='';%default variable name for vector color
2064frame_index=1;%default
2065FieldName='';%default
2066VelType='';%default
2067switch UvData.FileType{1}
2068    case {'civx','civdata','netcdf'};
2069        list_fields=get(handles.FieldName,'String');% list menu fields
2070        FieldName= list_fields{get(handles.FieldName,'Value')}; % selected field
2071        if ~strcmp(FieldName,'get_field...')
2072            if get(handles.FixVelType,'Value')
2073                VelTypeList=get(handles.VelType,'String');
2074                VelType=VelTypeList{get(handles.VelType,'Value')};
2075            end
2076        end
2077        % case of input vector field, get the scalar used for vector color
2078        if ~isempty(regexp(FieldName,'^vec('))
2079            list_code=get(handles.ColorCode,'String');% list menu fields
2080            index_code=get(handles.ColorCode,'Value');% selected string index
2081            if  ~strcmp(list_code{index_code},'black') &&  ~strcmp(list_code{index_code},'white')
2082                list_code=get(handles.ColorScalar,'String');% list menu fields
2083                index_code=get(handles.ColorScalar,'Value');% selected string index
2084                ParamIn.ColorVar= list_code{index_code}; % selected field
2085            end
2086        end
2087    case {'video','mmreader'}
2088        ParamIn=UvData.MovieObject{1};     
2089        if strcmp(NomType,'*')
2090            frame_index=num_i1;%frame index from a single movies or multimage
2091        else
2092            frame_index=num_j1;% frame index from a set of indexed movies
2093        end
2094    case 'multimage'
2095        if ~strcmp(NomType,'*')
2096            frame_index=num_j1;%frame index for movies or multimage
2097        else
2098            frame_index=num_i1;
2099        end
2100    case 'vol' %TODO: update
2101        if isfield(UvData.XmlData,'Npy') && isfield(UvData.XmlData,'Npx')
2102            ParamIn.Npy=UvData.XmlData.Npy;
2103            ParamIn.Npx=UvData.XmlData.Npx;
2104        else           
2105            errormsg='Npx and Npy need to be defined in the xml file for volume images .vol';
2106            return
2107        end
2108end
2109if isstruct (ParamIn)
2110    ParamIn.FieldName=FieldName;
2111    ParamIn.VelType=VelType;
2112    ParamIn.Coord_x=get(handles.Coord_x,'String');
2113    ParamIn.Coord_y=get(handles.Coord_y,'Data');
2114end
2115check_tps = 0;         
2116if strcmp(UvData.FileType{1},'civdata')&&~strcmp(ParamIn.FieldName,'velocity')&&~strcmp(ParamIn.FieldName,'get_field...')
2117       check_tps=1;%tps needed to get the requested field
2118end
2119[Field{1},ParamOut,errormsg] = read_field(FileName,UvData.FileType{1},ParamIn,frame_index);
2120if ~isempty(errormsg)
2121    errormsg=['uvmat / refresh_field / read_field( ' FileName ') / ' errormsg];
2122    return
2123end 
2124if isfield(ParamOut,'Npx')&& isfield(ParamOut,'Npy')
2125    set(handles.num_Npx,'String',num2str(ParamOut.Npx));% display image size on the interface
2126    set(handles.num_Npy,'String',num2str(ParamOut.Npy));
2127end
2128Field{1}.ZIndex=z_index; %used for multiplane 3D calibration
2129
2130%% choose and read a second field FileName_1 if defined
2131VelType_1=[];%default
2132FieldName_1=[];
2133ParamIn_1=[];
2134ParamOut_1=[];
2135frame_index_1=1;
2136if ~isempty(FileName_1)
2137    if ~exist(FileName_1,'file')
2138        errormsg=['second file ' FileName_1 ' does not exist'];
2139        return
2140    end
2141    switch UvData.FileType{2}
2142        case {'civx','civdata','netcdf'};
2143            list_fields=get(handles.FieldName_1,'String');% list menu fields
2144            if ischar(list_fields),list_fields={list_fields};end
2145            FieldName_1= list_fields{get(handles.FieldName_1,'Value')}; % selected field
2146            if ~strcmp(FieldName,'get_field...')
2147                if get(handles.FixVelType,'Value')
2148                    VelTypeList=get(handles.VelType_1,'String');
2149                    VelType_1=VelTypeList{get(handles.VelType_1,'Value')};% read the velocity type.
2150                end
2151            end
2152            if strcmp(FieldName_1,'velocity')&& strcmp(get(handles.ColorCode,'Visible'),'on')
2153                list_code=get(handles.ColorCode,'String');% list menu fields
2154                index_code=get(handles.ColorCode,'Value');% selected string index
2155                if  ~strcmp(list_code{index_code},'black') &&  ~strcmp(list_code{index_code},'white')
2156                    list_code=get(handles.ColorScalar,'String');% list menu fields
2157                    index_code=get(handles.ColorScalar,'Value');% selected string index
2158                    ParamIn_1.ColorVar= list_code{index_code}; % selected field for vector color display                 
2159                end
2160            end
2161        case {'video','mmreader'}
2162            ParamIn_1=UvData.MovieObject{2};
2163                        if ~strcmp(NomType_1,'*')
2164                frame_index_1=j1_1;%frame index for movies or multimage
2165            else
2166                frame_index_1=i1_1;
2167            end 
2168         case 'multimage'
2169            if strcmp(NomType_1,'*')%frame index for movies or multimage
2170                frame_index_1=i1_1;
2171            else
2172                frame_index_1=j1_1;
2173            end   
2174        case 'vol' %TODO: update
2175            if isfield(UvData.XmlData,'Npy') && isfield(UvData.XmlData,'Npx')
2176                ParamIn_1.Npy=UvData.XmlData.Npy;
2177                ParamIn_1.Npx=UvData.XmlData.Npx;
2178            else
2179                errormsg='Npx and Npy need to be defined in the xml file for volume images .vol';
2180                return
2181            end
2182    end
2183    if isequal(get(handles.NomType_1,'Visible'),'on')
2184    NomType_1=get(handles.NomType_1,'String');
2185    else
2186        NomType_1=get(handles.NomType,'String');
2187    end
2188    test_keepdata_1=0;% test for keeping the previous stored data if the input files are unchanged
2189    if ~isequal(NomType_1,'*')&& isfield(UvData,'FileName_1')
2190           test_keepdata_1= strcmp(FileName_1,UvData.FileName_1) ;
2191    end
2192    if test_keepdata_1
2193        Field{2}=UvData.Field_1;% keep the stored field
2194        ParamOut_1=UvData.ParamOut_1;
2195    else
2196        if isempty(ParamIn_1) || isstruct(ParamIn_1)
2197        ParamIn_1.FieldName=FieldName_1;
2198        ParamIn_1.VelType=VelType_1;
2199        %ParamIn_1.GUIName='get_field_1';
2200        end 
2201        [Field{2},ParamOut_1,errormsg] = read_field(FileName_1,UvData.FileType{2},ParamIn_1,frame_index_1);
2202        if ~isempty(errormsg)
2203            errormsg=['error in reading ' FieldName_1 ' in ' FileName_1 ': ' errormsg];
2204            return
2205        end
2206        if isstruct(ParamOut_1)&&~strcmp(ParamOut_1.FieldName,'get_field...')&& (strcmp(UvData.FileType{2},'civdata')||strcmp(UvData.FileType{2},'civx'))...
2207                &&~strcmp(ParamOut_1.FieldName,'velocity') && ~strcmp(ParamOut_1.FieldName,'get_field...')
2208            if ~check_proj_tps
2209            end
2210        end
2211    end
2212    Field{2}.ZIndex=z_index;%used for multi-plane 3D calibration
2213end
2214
2215%% update uvmat interface
2216if isfield(ParamOut,'Npx')
2217    set(handles.num_Npx,'String',num2str(ParamOut.Npx));% display image size on the interface
2218    set(handles.num_Npy,'String',num2str(ParamOut.Npy));
2219elseif isfield(ParamOut_1,'Npx')
2220    set(handles.num_Npx,'String',num2str(ParamOut_1.Npx));% display image size on the interface
2221    set(handles.num_Npy,'String',num2str(ParamOut_1.Npy));
2222end
2223
2224%% update the display menu for the first velocity type (first menuline)
2225test_veltype=0;
2226if (strcmp(UvData.FileType{1},'civx')||strcmp(UvData.FileType{1},'civdata'))&& ~strcmp(FieldName,'get_field...')
2227    test_veltype=1;
2228    set(handles.VelType,'Visible','on')
2229    set(handles.VelType_1,'Visible','on')
2230    set(handles.FixVelType,'Visible','on')
2231    menu=set_veltype_display(ParamOut.CivStage,UvData.FileType{1});
2232    index_menu=strcmp(ParamOut.VelType,menu);%look for VelType in  the menu
2233    index_val=find(index_menu,1);
2234    if isempty(index_val)
2235        index_val=1;
2236    end
2237    set(handles.VelType,'Value',index_val)
2238    if ~get(handles.SubField,'value')
2239        set(handles.VelType,'String',menu)
2240        set(handles.VelType_1,'Value',1)
2241        set(handles.VelType_1,'String',[{''};menu])
2242    end
2243else
2244    set(handles.VelType,'Visible','off')
2245end
2246
2247%% update the display menu for the second velocity type (second menuline)
2248test_veltype_1=0;
2249if isempty(FileName_1)
2250    %     set(handles.FieldName_1,'Value',1); %update the field menu
2251    %     if isstruct(ParamOut)
2252    %     set(handles.FieldName_1,'String',[{''};ParamOut.FieldList]); %update the field menu
2253    %     end
2254elseif ~test_keepdata_1
2255    if (~strcmp(UvData.FileType{2},'netcdf')&&~strcmp(UvData.FileType{2},'civdata')&&~strcmp(UvData.FileType{2},'civx'))|| isequal(FieldName_1,'get_field...')
2256        set(handles.VelType_1,'Visible','off')
2257    else
2258        test_veltype_1=1;
2259        set(handles.VelType_1,'Visible','on')
2260        menu=set_veltype_display(ParamOut_1.CivStage,UvData.FileType{2});
2261        index_menu=strcmp(ParamOut_1.VelType,menu);
2262        set(handles.VelType_1,'Value',1+find(index_menu,1))
2263        set(handles.VelType_1,'String',[{''};menu])
2264    end
2265    % update the second field menu: the same quantity
2266    if isstruct(ParamOut_1)
2267        % display the FieldName menu from the input file and pick the selected one:
2268        FieldList=get(handles.FieldName_1,'String');
2269        field_index=strcmp(ParamOut_1.FieldName,FieldList);
2270        if ~isempty(field_index)
2271            set(handles.FieldName_1,'Value',find(field_index,1))
2272        end
2273    end
2274end
2275if test_veltype||test_veltype_1
2276    set(handles.FixVelType,'Visible','on')
2277else
2278    set(handles.FixVelType,'Visible','off')
2279end
2280   
2281%% introduce w as background image by default for a new series (only for nbdim=2)
2282if ~isfield(UvData,'NewSeries')
2283    UvData.NewSeries=1;
2284end
2285%put W as background image by default if NbDim=2:
2286if  UvData.NewSeries && isequal(get(handles.SubField,'Value'),0) && isfield(Field{1},'W') && ~isempty(Field{1}.W) && ~isequal(Field{1}.NbDim,3);
2287        set(handles.SubField,'Value',1);
2288        set(handles.RootPath_1,'String','"')
2289        set(handles.RootFile_1,'String','"')
2290        set(handles.SubDir_1,'String','"');
2291         indices=fullfile_uvmat('','','','',NomType,num_i1,num_i2,num_j1,num_j2);
2292        set(handles.FileIndex_1,'String',indices)
2293        set(handles.FileExt_1,'String','"');
2294        set(handles.FieldName_1,'Visible','on');
2295        set(handles.FieldName_1,'Visible','on');
2296        set(handles.RootPath_1,'Visible','on')
2297        set(handles.RootFile_1,'Visible','on')
2298        set(handles.SubDir_1,'Visible','on');
2299        set(handles.FileIndex_1,'Visible','on');
2300        set(handles.FileExt_1,'Visible','on');
2301        set(handles.FieldName_1,'Visible','on');
2302        Field{1}.AName='w';
2303end           
2304
2305%% display time value of the current file
2306abstime=[];%default inputs
2307dt=[];
2308TimeUnit='';
2309if isfield(UvData,'TimeUnit')
2310TimeUnit=UvData.TimeUnit;%retrieve info from update_rootinfo
2311end
2312% time from xml file or video movie
2313TimeName=get(handles.TimeName,'String');% indicate that time is from xml
2314if strcmp(TimeName,'xml')||strcmp(TimeName,'video')
2315    if isempty(num_i2)||isnan(num_i2)
2316        num_i2=num_i1;
2317    end
2318    if isempty(num_j1)||isnan(num_j1)
2319        num_j1=1;
2320    end
2321    if isempty(num_j2)||isnan(num_j2)
2322        num_j2=num_j1;
2323    end
2324    siz=size(UvData.XmlData{1}.Time);
2325    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)
2326        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
2327        dt=(UvData.XmlData{1}.Time(num_i2+1,num_j2+1)-UvData.XmlData{1}.Time(num_i1+1,num_j1+1));
2328        Field{1}.Dt=dt;
2329        if isfield(UvData.XmlData{1},'TimeUnit')
2330            TimeUnit=UvData.XmlData{1}.TimeUnit;
2331        end
2332    end
2333end
2334
2335% get time in the input file, not defined in a xml file or movie
2336if isempty(abstime)
2337    if strcmp(TimeName,'civdata')||strcmp(TimeName,'civx')
2338        abstime=Field{1}.Time;
2339    elseif ~isempty(regexp(TimeName,'^att:'))||~isempty(regexp(TimeName,'^dim:'))||~isempty(regexp(TimeName,'^var:'))
2340        abstime=Field{1}.(TimeName(5:end));%the time is an attribute or variale selected by get_file
2341    end
2342    if isfield(Field{1},'Dt')
2343        dt=Field{1}.Dt;%dt read from the netcdf input file
2344        if isfield(Field{1},'TimeUnit')
2345            TimeUnit=Field{1}.TimeUnit;
2346        end
2347    elseif numel(Field)==2 && isfield(Field{2},'Dt')%dt obtained from the second field if not defined in the first
2348        dt=Field{2}.Dt;%dt read from the netcdf input file
2349        if isfield(Field{2},'TimeUnit')
2350            TimeUnit=Field{2}.TimeUnit;
2351        end
2352    end
2353end
2354set(handles.TimeValue,'String',num2str(abstime))
2355
2356%% display time value of the second current file if relevant
2357abstime_1=[];
2358if ~isempty(FileName_1)
2359    TimeName_1=get(handles.TimeName_1,'String');% indicate whether time is from xml or video
2360    % time from xml file or video movie as a second file series
2361    if strcmp(TimeName_1,'xml')||strcmp(TimeName_1,'video')
2362        if numel(UvData.XmlData)==2
2363            if isempty(i2_1)
2364                i2_1=num_i1;
2365            end
2366            if isempty(j1_1)
2367                j1_1=1;
2368            end
2369            if isempty(j2_1)
2370                j2_1=j1_1;
2371            end
2372            siz=size(UvData.XmlData{2}.Time);
2373            if ~isempty(i1_1) && siz(1)>=max(i1_1+1,i2_1+1) && siz(2)>=max(j1_1+1,j2_1+1)
2374                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
2375                Field{2}.Dt=(UvData.XmlData{2}.Time(i2_1+1,j2_1+1)-UvData.XmlData{2}.Time(i1_1+1,j1_1+1));
2376            end
2377        end
2378    end
2379   
2380    % get time in the input file of the second series, not defined in a xml file or movie
2381    if isempty(abstime_1) && numel(Field)==2
2382         if strcmp(TimeName_1,'civdata')||strcmp(TimeName_1,'civx')
2383        abstime_1=Field{2}.Time;
2384         elseif  ~isempty(regexp(TimeName_1,'^att:')) ||~isempty(regexp(TimeName_1,'^dim:'))||~isempty(regexp(TimeName_1,'^var:'))
2385        abstime_1=Field{2}.(TimeName_1(5:end));%the time is an attribute or variale selected by get_file
2386         end
2387    end
2388    set(handles.TimeValue_1,'String',num2str(abstime_1,5))
2389end
2390
2391if isempty(dt)||isequal(dt,0)
2392    set(handles.Dt_txt,'String','')
2393else
2394    if  isempty(TimeUnit)
2395        set(handles.Dt_txt,'String',['Dt=' num2str(1000*dt,3) '  10^(-3)'] )
2396    else
2397        set(handles.Dt_txt,'String',['Dt=' num2str(1000*dt,3) '  m' TimeUnit] )
2398    end
2399end
2400
2401%% Time title with unit
2402if isempty(abstime)&&isempty(abstime_1)
2403    Time_title='';
2404else
2405    Time_title='Time';
2406    if ~isempty(TimeUnit)
2407        Time_title=['Time (' TimeUnit ')'];
2408    end
2409end
2410set(handles.Time_title,'String',Time_title)
2411
2412%% store the current open names, fieldname and vel types in uvmat interface
2413UvData.FileName_1=FileName_1;
2414UvData.ParamOut_1=ParamOut_1;
2415if numel(Field)==2
2416UvData.Field_1=Field{2}; %store the second field for possible use at next RUN
2417end
2418
2419%% apply coordinate transform or other user fct
2420transform=get(handles.TransformPath,'UserData');
2421if isempty(transform)
2422    UvData.Field=Field{1};
2423else
2424    XmlData=[];%default
2425    XmlData_1=[];%default
2426    if isfield(UvData,'XmlData')%use geometry calib recorded from the ImaDoc xml file as first priority
2427        XmlData=UvData.XmlData{1};
2428        if numel(UvData.XmlData)==2
2429            XmlData_1=UvData.XmlData{2};
2430        end
2431    end
2432    switch nargin(transform)
2433        case 4
2434            if length(Field)==2
2435                UvData.Field=transform(Field{1},XmlData,Field{2},XmlData_1);
2436            else
2437                UvData.Field=transform(Field{1},XmlData);
2438            end
2439        case 3
2440            if length(Field)==2
2441                UvData.Field=transform(Field{1},XmlData,Field{2});
2442            else
2443                UvData.Field=transform(Field{1},XmlData);
2444            end
2445        case 2
2446            UvData.Field=transform(Field{1},XmlData);
2447        case 1
2448            UvData.Field=transform(Field{1});
2449    end
2450end
2451
2452%% calculate tps coefficients if needed
2453UvData.Field=tps_coeff_field(UvData.Field,check_proj_tps);
2454
2455%% get bounds and dimensions of the input field
2456UvData.Field=find_field_bounds(UvData.Field);
2457
2458if UvData.Field.NbDim>1
2459    % default projection plane
2460    if isempty(UvData.ProjObject{1})
2461        UvData.ProjObject{1}.Type='plane';%main plotting plane
2462        UvData.ProjObject{1}.ProjMode='projection';%main plotting plane
2463       % UvData.ProjObject{1}.Coord=[0 0 0];
2464        UvData.ProjObject{1}.DisplayHandle.uvmat=[]; %plane not visible in uvmat
2465        UvData.ProjObject{1}.DisplayHandle.view_field=[]; %plane not visible in uvmat
2466    end
2467    %% 3D case (menuvolume)
2468    if UvData.Field.NbDim==3% && UvData.NewSeries
2469        test_set_object=1;
2470        hset_object=findobj(allchild(0),'tag','set_object');% look for the set_object GUI
2471        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
2472        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
2473        if ~isempty(hset_object) %if set_object is detected
2474            delete(hset_object);% delete the GUI set_object if it does not fit
2475        end
2476        if test_set_object% reinitiate the GUI set_object
2477            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
2478            UvData.ProjObject{1}.NbDim=NbDim;%test for 3D objects
2479            UvData.ProjObject{1}.RangeZ=UvData.Field.CoordMesh;%main plotting plane
2480            UvData.ProjObject{1}.Coord(1,3)=(UvData.Field.ZMin+UvData.Field.ZMax)/2;%section at a middle plane chosen
2481            UvData.ProjObject{1}.Angle=[0 0 0];
2482            UvData.ProjObject{1}.HandlesDisplay=plot(0,0,'Tag','proj_object');% A REVOIR
2483            UvData.ProjObject{1}.Name='1-PLANE';
2484            UvData.ProjObject{1}.enable_plot=1;
2485            set_object(UvData.ProjObject{1},handles,ZBounds);
2486            set(handles.ListObject,'Value',1);
2487            set(handles.ListObject,'String',{'1-PLANE'});
2488            set(handles.CheckEditObject,'Value',1)% put the plane in edit mode to enable the z cursor
2489            CheckEditObject_Callback([],[], handles)
2490        end
2491        %multilevel case (single menuplane in a 3D space)
2492    elseif isfield(UvData,'Z')
2493        if isfield(UvData,'CoordType')&& isequal(UvData.CoordType,'phys') && isfield(UvData,'XmlData')
2494            XmlData=UvData.XmlData{1};
2495            if isfield(XmlData,'PlanePos')
2496                UvData.ProjObject{1}.Coord=XmlData.PlanePos(UvData.ZIndex,:);
2497            end
2498            if isfield(XmlData,'PlaneAngle')
2499                siz=size(XmlData.PlaneAngle);
2500                indangle=min(siz(1),UvData.ZIndex);%take first angle if a single angle is defined (translating scanning)
2501                UvData.ProjObject{1}.PlaneAngle=XmlData.PlaneAngle(indangle,:);
2502            end
2503        elseif isfield(UvData,'ZIndex')
2504            UvData.ProjObject{1}.ZObject=UvData.ZIndex;
2505        end
2506    end
2507end
2508
2509testnewseries=UvData.NewSeries;
2510UvData.NewSeries=0;% put to 0 the test for a new field series (set by RootPath_callback)
2511set(handles.uvmat,'UserData',UvData)
2512
2513%% reset the min and max of scalar if only the mask is displayed(TODO: check the need)
2514% if isfield(UvData,'Mask')&& ~isfield(UvData,'A')
2515%     set(handles.num_MinA,'String','0')
2516%     set(handles.num_MaxA,'String','255')
2517% end
2518
2519%% usual 1D (x,y) plots
2520if UvData.Field.NbDim<=1
2521    set(handles.Objects,'Visible','off')
2522    set(handles.ListObject_1_title,'Visible','off')
2523    set(handles.ListObject_1,'Visible','off')
2524    [PlotType,PlotParamOut]=plot_field(UvData.Field,handles.PlotAxes,read_GUI(handles.uvmat));
2525    errormsg=fill_GUI(PlotParamOut,handles.uvmat);
2526    for list={'Scalar','Vectors'}
2527        if ~isfield(PlotParamOut,list{1})
2528            set(handles.(list{1}),'Visible','off')
2529        end
2530    end
2531   
2532%% 2D or 3D fieldname are generally projected
2533else
2534    set(handles.Objects,'Visible','on')
2535    set(handles.ListObject_1_title,'Visible','on')
2536    set(handles.ListObject_1,'Visible','on')
2537   
2538    %% Plot the projections on the selected  projection objects
2539    % main projection object (uvmat display)
2540    list_object=get(handles.ListObject_1,'String');
2541    if isequal(list_object,{''})||isequal(list_object,' ')%refresh list of objects if the menu is empty
2542        set(handles.ListObject,'Value',1)
2543        set(handles.ListObject,'String',{'plane'})
2544        UvData.ProjObject{1}.Type='plane';%main plotting plane
2545        UvData.ProjObject{1}.ProjMode='projection';%main plotting plane
2546        UvData.ProjObject{1}.DisplayHandle.uvmat=[]; %plane not visible in uvmat
2547        UvData.ProjObject{1}.DisplayHandle.view_field=[]; %plane not visible in uvmat
2548        set(handles.ListObject_1,'Value',1)
2549        set(handles.ListObject_1,'String',{'plane'})
2550    end
2551    IndexObj=get(handles.ListObject_1,'Value');%selected projection object for main view
2552    if IndexObj> numel(UvData.ProjObject)
2553        IndexObj=1;%select the first object if the selected one does not exist
2554        set(handles.ListObject_1,'Value',1)
2555    end
2556    if get(handles.CheckViewField,'Value')
2557        IndexObj_2=get(handles.ListObject,'Value');%selected projection object for view_field
2558        if ~isequal(IndexObj_2,IndexObj(1))
2559            IndexObj(2)=IndexObj_2;
2560        end
2561    end
2562    plot_handles{1}=handles;
2563    if isfield(UvData,'plotaxes')%case of movies
2564        haxes(1)=UvData.plotaxes;
2565    else
2566        haxes(1)=handles.PlotAxes;
2567    end
2568    PlotParam{1}=read_GUI(handles.uvmat);
2569    %default settings if vectors not visible
2570    if ~isfield(PlotParam{1},'Vectors')
2571        PlotParam{1}.Vectors.MaxVec=1;
2572        PlotParam{1}.Vectors.MinVec=0;
2573        PlotParam{1}.Vectors.CheckFixVecColor=1;
2574        PlotParam{1}.Vectors.ColCode1=0.33;
2575        PlotParam{1}.Vectors.ColCode2=0.66;
2576        PlotParam{1}.Vectors.ColorScalar={''};
2577        PlotParam{1}.Vectors.ColorCode= {'rgb'};
2578    end
2579    PosColorbar{1}=UvData.OpenParam.PosColorbar;%prescribe the colorbar position on the uvmat interface
2580   
2581    %% second projection object (view_field display)
2582    if length( IndexObj)>=2
2583        view_field_handle=findobj(allchild(0),'tag','view_field');%handles of the view_field GUI
2584        if ~isempty(view_field_handle)
2585            plot_handles{2}=guidata(view_field_handle);
2586            haxes(2)=plot_handles{2}.PlotAxes;
2587            PlotParam{2}=read_GUI(view_field_handle);
2588           % PlotParam{2}=read_GUI(handles.uvmat);%read plotting parameters on the uvmat interface
2589            PosColorbar{2}='*'; %TODO: deal with colorbar position on view_field
2590        end
2591    end
2592   
2593    %% loop on the projection objects: one or two
2594   
2595    for imap=1:numel(IndexObj)
2596        iobj=IndexObj(imap);
2597        if numel(UvData.ProjObject)<iobj
2598            break
2599        end
2600        [ObjectData,errormsg]=proj_field(UvData.Field,UvData.ProjObject{iobj});% project field on the object
2601        if ~isempty(errormsg)
2602            return
2603        end
2604        if testnewseries
2605            PlotParam{imap}.Scalar.CheckBW=[]; %B/W option depends on the input field (image or scalar)
2606            if isfield(ObjectData,'CoordUnit')
2607                PlotParam{imap}.Coordinates.CheckFixAspectRatio=1;% set x and y scaling equal if CoordUnit is defined (common unit for x and y)
2608                PlotParam{imap}.Coordinates.AspectRatio=1; %set aspect ratio to 1
2609            end
2610        end
2611        %use of mask (TODO: check)
2612        if isfield(ObjectData,'NbDim') && isequal(ObjectData.NbDim,2) && isfield(ObjectData,'Mask') && isfield(ObjectData,'A')
2613            flag_mask=double(ObjectData.Mask>200);%=0 for masked regions
2614            AX=ObjectData.AX;%x coordiantes for the scalar field
2615            AY=ObjectData.AY;%y coordinates for the scalar field
2616            MaskX=ObjectData.MaskX;%x coordiantes for the mask
2617            MaskY=ObjectData.MaskY;%y coordiantes for the mask
2618            if ~isequal(MaskX,AX)||~isequal(MaskY,AY)
2619                nxy=size(flag_mask);
2620                sizpx=(ObjectData.MaskX(end)-ObjectData.MaskX(1))/(nxy(2)-1);%size of a mask pixel
2621                sizpy=(ObjectData.MaskY(1)-ObjectData.MaskY(end))/(nxy(1)-1);
2622                x_mask=ObjectData.MaskX(1):sizpx:ObjectData.MaskX(end); % pixel x coordinates for image display
2623                y_mask=ObjectData.MaskY(1):-sizpy:ObjectData.MaskY(end);% pixel x coordinates for image display
2624                %project on the positions of the scalar
2625                npxy=size(ObjectData.A);
2626                dxy(1)=(ObjectData.AY(end)-ObjectData.AY(1))/(npxy(1)-1);%grid mesh in y
2627                dxy(2)=(ObjectData.AX(end)-ObjectData.AX(1))/(npxy(2)-1);%grid mesh in x
2628                xi=ObjectData.AX(1):dxy(2):ObjectData.AX(end);
2629                yi=ObjectData.AY(1):dxy(1):ObjectData.AY(end);
2630                [XI,YI]=meshgrid(xi,yi);% creates the matrix of regular coordinates
2631                flag_mask = interp2(x_mask,y_mask,flag_mask,XI,YI);
2632            end
2633            AClass=class(ObjectData.A);
2634            ObjectData.A=flag_mask.*double(ObjectData.A);
2635            ObjectData.A=feval(AClass,ObjectData.A);
2636        end
2637        if ~isempty(ObjectData)
2638            %PlotType='none'; %default
2639            if imap==2 && isempty(view_field_handle)
2640                view_field(ObjectData)
2641            else
2642              %  ObjectData.VarAttribute{5}.Role='scalar';TODO    CORRECT
2643                [PlotType,PlotParamOut]=plot_field(ObjectData,haxes(imap),PlotParam{imap},PosColorbar{imap});
2644                if imap==1
2645                    errormsg=fill_GUI(PlotParamOut,handles.uvmat);
2646                else
2647                    errormsg=fill_GUI(PlotParamOut,view_field_handle);
2648                end
2649                for list={'Scalar','Vectors'}
2650                    if ~isfield(PlotParamOut,list{1})
2651                        set(plot_handles{imap}.(list{1}),'Visible','off')
2652                    end
2653                end
2654                if isfield(Field,'CoordMesh')&&~isempty(Field.CoordMesh)
2655                    ObjectData.CoordMesh=Field.CoordMesh; % gives an estimated mesh size (useful for mouse action on the plot)
2656                end
2657            end
2658        end
2659    end
2660   
2661    %% update the mask
2662    if isequal(get(handles.CheckMask,'Value'),1)%if the mask option is on
2663        update_mask(handles);
2664    end
2665   
2666    %% prepare the menus of histograms and plot them (histogram of the whole volume in 3D case)
2667    menu_histo=(UvData.Field.ListVarName)';%list of field variables to be displayed for the menu of histogram display
2668    ind_skip=[];
2669    % nb_histo=1;
2670    Ustring='';
2671    Vstring='';
2672    % suppress coordinates from the histogram menu
2673    for ivar=1:numel(menu_histo)%l loop on field variables:
2674        if isfield(UvData.Field,'VarAttribute') && numel(UvData.Field.VarAttribute)>=ivar && isfield(UvData.Field.VarAttribute{ivar},'Role')
2675            Role=UvData.Field.VarAttribute{ivar}.Role;
2676            switch Role
2677                case {'coord_x','coord_y','coord_z','dimvar'}
2678                    ind_skip=[ind_skip ivar];
2679                case {'vector_x'}
2680                    Ustring=UvData.Field.ListVarName{ivar};
2681                    ind_skip=[ind_skip ivar];
2682                case {'vector_y'}
2683                    Vstring=UvData.Field.ListVarName{ivar};
2684                    ind_skip=[ind_skip ivar];
2685            end
2686        end
2687        DimCell=UvData.Field.VarDimName{ivar};
2688        DimName='';
2689        if ischar(DimCell)
2690            DimName=DimCell;
2691        elseif iscell(DimCell)&& numel(DimCell)==1
2692            DimName=DimCell{1};
2693        end
2694        if strcmp(DimName,menu_histo{ivar})
2695            ind_skip=[ind_skip ivar];
2696        end
2697    end
2698    menu_histo(ind_skip)=[];% remove skipped items
2699    if ~isempty(Ustring)
2700        menu_histo=[{[Ustring ',' Vstring]};menu_histo];% add U, V at the beginning if they exist
2701    end
2702   
2703    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2704    % display menus and plot histograms
2705    test_v=0;
2706    if ~isempty(menu_histo)
2707        set(handles.histo1_menu,'Value',1)
2708        set(handles.histo1_menu,'String',menu_histo)
2709        histo1_menu_Callback(handles.histo1_menu, [], handles)% plot first histogram
2710    end
2711end
2712ResizeFcn(handles.uvmat,[],handles)
2713
2714%------------------------------------------------------------------------
2715function histo1_menu_Callback(hObject, eventdata, handles)
2716%--------------------------------------------
2717histo_menu=get(handles.histo1_menu,'String');
2718histo_value=get(handles.histo1_menu,'Value');
2719FieldName=histo_menu{histo_value};
2720
2721UvData=get(handles.uvmat,'UserData');
2722Field=UvData.Field;
2723r=regexp(FieldName,'(?<var1>.*)(?<sep>,)(?<var2>.*)','names');
2724FieldName_2='';
2725if ~isempty(r)
2726    FieldName=r.var1;
2727    FieldName_2=r.var2;
2728end
2729if ~isfield(UvData.Field,FieldName)
2730    msgbox_uvmat('ERROR',['no field  ' FieldName ' for histogram'])
2731    return
2732end
2733FieldHisto=Field.(FieldName);
2734if isfield(Field,'FF') && ~isempty(Field.FF) && isequal(size(Field.FF),size(FieldHisto))
2735    indsel=find(Field.FF==0);%find values marked as false
2736    if ~isempty(indsel)
2737        FieldHisto=FieldHisto(indsel);
2738        if ~isempty(FieldName_2)
2739            FieldHisto(:,:,2)=Field.(FieldName_2)(indsel);
2740        end
2741    end
2742elseif ~isempty(FieldName_2)
2743    FieldHisto(:,:,2)=Field.(FieldName_2);
2744end
2745if isempty(Field)
2746    msgbox_uvmat('ERROR',['empty field ' FieldName])
2747else
2748    nxy=size(FieldHisto);
2749    Amin=double(min(min(min(FieldHisto))));%min of field value
2750    Amax=double(max(max(max(FieldHisto))));%max of field value
2751    if isequal(Amin,Amax)
2752        cla(handles.HistoAxes)
2753    else
2754        Histo.ListVarName={FieldName,'histo'};
2755        if isfield(Field,'NbDim') && isequal(Field.NbDim,3)
2756            Histo.VarDimName={FieldName,FieldName}; %dimensions for the histogram
2757        else
2758            if numel(nxy)==2
2759                Histo.VarDimName={FieldName,FieldName}; %dimensions for the histogram
2760            else
2761                Histo.VarDimName={FieldName,{FieldName,'component'}}; %dimensions for the histogram
2762            end
2763        end
2764        %unit
2765        units=[]; %default
2766        for ivar=1:numel(Field.ListVarName)
2767            if strcmp(Field.ListVarName{ivar},FieldName)
2768                if isfield(Field,'VarAttribute') && numel(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'units')
2769                    units=Field.VarAttribute{ivar}.units;
2770                    break
2771                end
2772            end
2773        end
2774        if ~isempty(units)
2775            Histo.VarAttribute{1}.units=units;
2776        end
2777        eval(['Histo.' FieldName '=linspace(Amin,Amax,50);'])%absissa values for histo
2778        if isfield(Field,'NbDim') && isequal(Field.NbDim,3)
2779            C=reshape(double(FieldHisto),1,[]);% reshape in a vector
2780            Histo.histo(:,1)=hist(C, Histo.(FieldName));  %calculate histogram
2781        else
2782            for col=1:size(FieldHisto,3)
2783                B=FieldHisto(:,:,col);
2784                C=reshape(double(B),1,nxy(1)*nxy(2));% reshape in a vector
2785                Histo.histo(:,col)=hist(C, Histo.(FieldName));  %calculate histogram
2786            end
2787        end
2788        plot_field(Histo,handles.HistoAxes);
2789        hlegend=legend;
2790        if isempty(FieldName_2)
2791        set(hlegend,'String',FieldName)
2792        else
2793            set(hlegend,'String',{FieldName;FieldName_2})
2794        end
2795    end
2796end
2797
2798%------------------------------------------------------------------------
2799% --- translate coordinate to matrix index
2800%------------------------------------------------------------------------
2801function [indx,indy]=pos2ind(x0,rangx0,nxy)
2802indx=1+round((nxy(2)-1)*(x0-rangx0(1))/(rangx0(2)-rangx0(1)));% index x of pixel 
2803indy=1+round((nxy(1)-1)*(y12-rangy0(1))/(rangy0(2)-rangy0(1)));% index y of pixel
2804
2805%------------------------------------------------------------------------
2806% --- Executes on button press in 'CheckZoom'.
2807%------------------------------------------------------------------------
2808function CheckZoom_Callback(hObject, eventdata, handles)
2809
2810if get(handles.CheckZoom,'Value')
2811    set(handles.CheckFixLimits,'Value',1)% propose by default fixed limits for the plotting axes
2812    set(handles.CheckZoomFig,'Value',0)%desactivate zoom fig
2813end
2814
2815%------------------------------------------------------------------------
2816% --- Executes on button press in CheckZoomFig.
2817%------------------------------------------------------------------------
2818function CheckZoomFig_Callback(hObject, eventdata, handles)
2819
2820if get(handles.CheckZoomFig,'Value')
2821    set(handles.CheckZoom,'value',0)
2822end
2823
2824%------------------------------------------------------------------------
2825% --- Executes on button press in 'CheckFixLimits'.
2826%------------------------------------------------------------------------
2827function CheckFixLimits_Callback(hObject, eventdata, handles)
2828
2829if ~get(handles.CheckFixLimits,'Value')
2830    update_plot(handles)
2831    set(handles.CheckZoom,'Value',0)
2832end
2833
2834%------------------------------------------------------------------------
2835% --- Executes on button press in CheckFixAspectRatio.
2836function CheckFixAspectRatio_Callback(hObject, eventdata, handles)
2837%------------------------------------------------------------------------
2838
2839if get(handles.CheckFixAspectRatio,'Value')
2840    update_plot(handles);
2841else
2842    update_plot(handles);
2843end
2844
2845%------------------------------------------------------------------------
2846function num_AspectRatio_Callback(hObject, eventdata, handles)
2847%------------------------------------------------------------------------
2848set(handles.CheckFixAspectRatio,'Value',1)% select the fixed aspect ratio button
2849update_plot(handles);
2850
2851%------------------------------------------------------------------------
2852%----Executes on button press in 'record': records the current flags of manual correction.
2853%------------------------------------------------------------------------
2854function record_Callback(hObject, eventdata, handles)
2855
2856[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
2857FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
2858[erread,message]=fileattrib(FileName);
2859if ~isempty(message) && ~isequal(message.UserWrite,1)
2860     msgbox_uvmat('ERROR',['no writting access to ' FileName])
2861     return
2862end
2863MenuVelType=get(handles.VelType,'String');
2864test_civ2=strcmp(MenuVelType{get(handles.VelType,'Value')},'civ2');
2865test_civ1=strcmp(MenuVelType{get(handles.VelType,'Value')},'civ1');
2866if ~test_civ2 && ~test_civ1
2867    msgbox_uvmat('ERROR','manual correction only possible for CIV1 or CIV2 velocity fields')
2868end
2869if test_civ2
2870    nbname='nb_vec_2';
2871   flagname='Civ2_FF';
2872   CivStage=5;
2873end
2874if test_civ1
2875    nbname='nb_vec_1';
2876   flagname='Civ1_FF';
2877    CivStage=2;
2878end
2879%write fix flags in the netcdf file
2880UvData=get(handles.uvmat,'UserData');
2881hhh=which('netcdf.open');% look for built-in matlab netcdf library
2882if ~isequal(hhh,'')% case of  builtin Matlab netcdf library
2883    nc=netcdf.open(FileName,'NC_WRITE');
2884    netcdf.reDef(nc);
2885    netcdf.putAtt(nc,netcdf.getConstant('NC_GLOBAL'),'CivStage',CivStage);
2886    dimid = netcdf.inqDimID(nc,nbname);
2887    try
2888        varid = netcdf.inqVarID(nc,flagname);% look for already existing fixflag variable
2889    catch
2890        varid=netcdf.defVar(nc,flagname,'double',dimid);%create fixflag variable if it does not exist
2891    end
2892    netcdf.endDef(nc);
2893    netcdf.putVar(nc,varid,UvData.PlotAxes.FF);
2894    netcdf.close(nc); 
2895else %old netcdf library
2896    netcdf_toolbox(FileName,AxeData,attrname,nbname,flagname)
2897end
2898
2899%-------------------------------------------------------------------
2900%----Correct the netcdf file, using toolbox (old versions of Matlab).
2901%-------------------------------------------------------------------
2902function netcdf_toolbox(FileName,AxeData,attrname,nbname,flagname)
2903nc=netcdf(FileName,'write'); %open netcdf file
2904result=redef(nc);
2905eval(['nc.' attrname '=1;']);
2906theDim=nc(nbname) ;% get the number of velocity vectors
2907nb_vectors=size(theDim);
2908var_FixFlag=ncvar(flagname,nc);% var_FixFlag will be written as the netcdf variable vec_FixFlag
2909var_FixFlag(1:nb_vectors)=AxeData.FF;%
2910fin=close(nc);
2911
2912%-----------------------------------------------------------------------
2913% --- Executes on button press in SubField
2914%-----------------------------------------------------------------------
2915function SubField_Callback(hObject, eventdata, handles)
2916
2917if get(handles.SubField,'Value')==0% if the subfield button is desactivated 
2918    desable_subfield(handles)
2919    transform_fct_list=get(handles.TransformName,'String');
2920    transform_fct=transform_fct_list(get(handles.TransformName,'Value'));
2921    if strcmp(transform_fct,'sub_field')
2922        set(handles.TransformName,'Value',1)%suppress the sub_field transform
2923        TransformName_Callback(hObject, eventdata, handles);
2924    else
2925        run0_Callback(hObject, eventdata, handles)
2926    end 
2927else
2928    fileinput_1=uigetfile_uvmat('select a second input file:',get(handles.RootPath,'String'));
2929    if isempty(fileinput_1)
2930        set(handles.SubField,'Value',0)
2931    else       
2932        % refresh the current displayed field
2933        display_file_name(handles,fileinput_1,2)
2934       
2935        %update list of recent files in the menubar
2936        MenuFile_1=fileinput_1;
2937        MenuFile_2=get(handles.MenuFile_1,'Label');
2938        MenuFile_3=get(handles.MenuFile_2,'Label');
2939        MenuFile_4=get(handles.MenuFile_3,'Label');
2940        MenuFile_5=get(handles.MenuFile_4,'Label');
2941        set(handles.MenuFile_1,'Label',MenuFile_1)
2942        set(handles.MenuFile_2,'Label',MenuFile_2)
2943        set(handles.MenuFile_3,'Label',MenuFile_3)
2944        set(handles.MenuFile_4,'Label',MenuFile_4)
2945        set(handles.MenuFile_5,'Label',MenuFile_5)
2946    end
2947end
2948
2949%-----------------------------------------------------------------------
2950% --- desactivate display used for a second file series
2951%-----------------------------------------------------------------------
2952function desable_subfield(handles)
2953   
2954set(handles.RootPath_1,'String','')
2955set(handles.RootFile_1,'String','')
2956set(handles.SubDir_1,'String','');
2957set(handles.FileIndex_1,'String','');
2958set(handles.FileExt_1,'String','');
2959set(handles.RootPath_1,'Visible','off')
2960set(handles.RootFile_1,'Visible','off')
2961set(handles.SubDir_1,'Visible','off');
2962set(handles.NomType_1,'Visible','off');
2963set(handles.FileIndex_1,'Visible','off');
2964set(handles.FileExt_1,'Visible','off');
2965set(handles.TimeName_1,'String','');
2966set(handles.TimeName_1,'Visible','off');
2967set(handles.TimeValue_1,'String','');
2968set(handles.TimeValue_1,'Visible','off');
2969set(handles.FieldName_1,'Value',1);%set to blank state
2970set(handles.VelType_1,'Value',1);%set to blank state
2971set(handles.num_Opacity,'String','')% desactivate opacity setting
2972FieldList=get(handles.FieldName,'String');
2973if numel(FieldList)>1   % if a choice of fields exists
2974    set(handles.FieldName_1,'Value',1)% set second field choice to blank
2975    set(handles.FieldName_1,'String',[{''};FieldList])% reproduce the menu FieldName plus a blank option
2976else
2977    set(handles.FieldName_1,'String',{''})% set second field choice to blank
2978end
2979if ~strcmp(get(handles.VelType,'Visible'),'on')
2980    set(handles.VelType_1,'Visible','off')
2981end
2982UvData=get(handles.uvmat,'UserData');
2983if isfield(UvData,'XmlData_1')
2984    UvData=rmfield(UvData,'XmlData_1');
2985end
2986set(handles.uvmat,'UserData',UvData);
2987
2988%------------------------------------------------------------------------
2989% --- read the data displayed for the input rootfile windows (new): TODO use read_GUI
2990%------------------------------------------------------------------------
2991function [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles)
2992
2993InputFile=read_GUI(handles.InputFile);
2994RootPath=InputFile.RootPath;
2995SubDir=regexprep(InputFile.SubDir,'/|\','');
2996RootFile=regexprep(InputFile.RootFile,'/|\','');
2997FileIndices=InputFile.FileIndex;
2998FileExt=InputFile.FileExt;
2999
3000
3001%------------------------------------------------------------------------
3002% ---- read the data displayed for the second input rootfile windows
3003%------------------------------------------------------------------------
3004function [RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1,NomType_1]=read_file_boxes_1(handles)
3005
3006RootPath_1=get(handles.RootPath_1,'String'); % read the data from the file1_input window
3007if isequal(get(handles.RootPath_1,'Visible'),'off') || isequal(RootPath_1,'"')
3008    RootPath_1=get(handles.RootPath,'String');
3009end;
3010SubDir_1=get(handles.SubDir_1,'String');
3011if isequal(get(handles.SubDir_1,'Visible'),'off')|| isequal(SubDir_1,'"')
3012    SubDir_1=get(handles.SubDir,'String');
3013end
3014SubDir_1=regexprep(SubDir_1,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3015RootFile_1=get(handles.RootFile_1,'String');
3016if isequal(get(handles.RootFile_1,'Visible'),'off') || isequal(RootFile_1,'"')
3017    RootFile_1=get(handles.RootFile,'String');
3018end
3019RootFile_1=regexprep(RootFile_1,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3020FileIndex_1=get(handles.FileIndex_1,'String');
3021if isequal(get(handles.FileIndex_1,'Visible'),'off')|| isequal(FileIndex_1,'"')
3022    FileIndex_1=get(handles.FileIndex,'String');
3023end
3024FileExt_1=get(handles.FileExt_1,'String');
3025if isequal(get(handles.FileExt_1,'Visible'),'off') || isequal(FileExt_1,'"')
3026    FileExt_1=get(handles.FileExt,'String');%read FileExt by default
3027end
3028NomType_1=get(handles.NomType_1,'String');
3029if isequal(get(handles.NomType_1,'Visible'),'off') || isequal(NomType_1,'"')
3030    NomType_1=get(handles.NomType,'String');%read FileExt by default
3031end
3032%------------------------------------------------------------------------
3033% --- Executes on menu selection FieldName
3034function FieldName_Callback(hObject, eventdata, handles)
3035%------------------------------------------------------------------------
3036
3037%% read data from uvmat
3038UvData=get(handles.uvmat,'UserData');
3039list_fields=get(handles.FieldName,'String');% list menu fields
3040index_fields=get(handles.FieldName,'Value');% selected string index
3041field= list_fields{index_fields(1)}; % selected string
3042[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
3043FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3044[tild,tild,tild,i1,i2,j1,j2,tild,NomType]=fileparts_uvmat(['xxx' get(handles.FileIndex,'String') FileExt]);
3045
3046switch field
3047   
3048    case 'get_field...'
3049        %% fill the coordinates and variables from selections in get_field
3050        ParamIn=[];
3051        % in case of civ data, we use the civ choice as default input for the GUI get_field
3052        if strcmp(get(handles.VelType,'Visible'),'on')
3053            ParamIn.SwitchVarIndexTime='attribute';
3054            ListVelType=get(handles.VelType,'String');
3055            VelType=ListVelType{get(handles.VelType,'Value')};
3056            switch VelType
3057                case 'civ1'
3058                    ParamIn.TimeAttrName='Civ1_Time';
3059                    ParamIn.vector_x='Civ1_U';
3060                    ParamIn.vector_y='Civ1_V';
3061                    ParamIn.vec_color='Civ1_C';
3062                case 'filter1'
3063                    ParamIn.TimeAttrName='Civ1_Time';
3064                    ParamIn.vector_x='Civ1_U_smooth';
3065                    ParamIn.vector_y='Civ1_V_smooth';
3066                case 'civ2'
3067                    ParamIn.TimeAttrName='Civ2_Time';
3068                    ParamIn.vector_x='Civ2_U';
3069                    ParamIn.vector_y='Civ2_V';
3070                case 'filter2'
3071                    ParamIn.TimeAttrName='Civ2_Time';
3072                    ParamIn.vector_x='Civ2_U_smooth';
3073                    ParamIn.vector_y='Civ2_V_smooth';
3074                    ParamIn.vec_color='Civ2_C';
3075            end
3076        end
3077       
3078        % VelType menu desactivated
3079        set(handles.FixVelType,'visible','off')
3080        set(handles.VelType,'Visible','off')
3081       
3082        %read selection from get_field
3083        [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
3084        FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3085        GetFieldData=get_field(FileName,ParamIn);% inport field names from the GUI get_field
3086        FieldList={};
3087        VecColorList={};
3088        switch GetFieldData.FieldOption
3089            case 'vectors'
3090                UName=GetFieldData.PanelVectors.vector_x;
3091                VName=GetFieldData.PanelVectors.vector_y;
3092                YName={GetFieldData.Coordinates.Coord_y};
3093                CName=GetFieldData.PanelVectors.vec_color;
3094                FieldList={['vec(' UName ',' VName ')'];...
3095                    ['norm(' UName ',' VName ')'];...
3096                    UName;VName};
3097                VecColorList={['norm(' UName ',' VName ')'];...
3098                    UName;VName};
3099                if ~isempty(CName)
3100                    VecColorList=[{CName};VecColorList];
3101                end
3102            case 'scalar'
3103                AName=GetFieldData.PanelScalar.scalar;
3104                YName={GetFieldData.Coordinates.Coord_y};
3105                FieldList={AName};
3106            case '1D plot'
3107                YName=GetFieldData.PanelOrdinate.ordinate;
3108            case 'civdata...'%reinitiate input, return to automatic civ data reading
3109                display_file_name(handles,FileName,1)
3110        end
3111        if ~strcmp(GetFieldData.FieldOption,'civdata...')
3112            XName=GetFieldData.Coordinates.Coord_x;
3113            TimeNameStr=GetFieldData.Time.SwitchVarIndexTime;
3114            if strcmp(TimeNameStr,'file index')
3115                set(handles.TimeName,'String','');
3116            else
3117                set(handles.TimeName,'String',[TimeNameStr(1:3) ':' GetFieldData.Time.TimeName]);
3118            end
3119            if strcmp(TimeNameStr,'variable')||strcmp(TimeNameStr,'dim index')% we scan a variable index, not a file index
3120                set(handles.NomType,'String','*')
3121                set(handles.RootFile,FileName)
3122            end
3123            %     set(handles.TimeValue,'String' SwitchVarIndexTime
3124            set(handles.Coord_x,'String',XName)
3125            if ischar(YName)
3126                YName={YName};
3127            end
3128            set(handles.Coord_y,'Data',YName)
3129            set(handles.FieldName,'Value',1)
3130            set(handles.FieldName,'String',[FieldList; {'get_field...'}]);
3131            set(handles.ColorScalar,'Value',1)
3132            set(handles.ColorScalar,'String',VecColorList);
3133            UvData.FileType{1}='netcdf';
3134            set(handles.uvmat,'UserData',UvData)
3135            run0_Callback(hObject, eventdata, handles)
3136        end
3137       
3138    case 'image'
3139        %% look for image corresponding to civ data
3140        if  isfield(UvData.Field,'Civ2_ImageA')%get the corresponding input image in the netcdf file
3141            imagename=UvData.Field.Civ2_ImageA;
3142        elseif isfield(UvData.Field,'Civ1_ImageA')%
3143            imagename=UvData.Field.Civ1_ImageA;
3144        else
3145            SubDirBase=regexprep(SubDir,'\..*','');%take the root part of SubDir, before the first dot '.'
3146            imagename=fullfile_uvmat(RootPath,SubDirBase,RootFile,'.png',NomType,i1,[],j1,[]);
3147        end
3148        if ~exist(imagename,'file')
3149            imagename=uigetfile_uvmat('Pick an image file',imagename,'image');
3150            if isempty(imagename)
3151                return
3152            end
3153        end
3154        % display the selected field and related information
3155        display_file_name(handles,imagename)%display the image
3156    otherwise
3157        run0_Callback(hObject, eventdata, handles)
3158end
3159
3160%----------------------------------------------------------------
3161% --- Executes on menu selection FieldName
3162function FieldName_1_Callback(hObject, eventdata, handles)
3163%-------------------------------------------------
3164
3165%%%%%% TODO: modify like FieldName_Callback
3166%% read input data
3167check_new=~get(handles.SubField,'Value'); %check_new=1 if a second field was not previously entered
3168UvData=get(handles.uvmat,'UserData');
3169if check_new && isfield(UvData,'XmlData')
3170    UvData.XmlData{2}=UvData.XmlData{1};
3171end
3172if isfield(UvData,'Field_1')
3173    UvData=rmfield(UvData,'Field_1');% remove the stored second field (a new one needs to be read)
3174end
3175UvData.FileName_1='';% desactivate the use of a constant second file
3176list_fields=get(handles.FieldName,'String');% list menu fields
3177field= list_fields{get(handles.FieldName,'Value')}; % selected string
3178list_fields=get(handles.FieldName_1,'String');% list menu fields
3179field_1= list_fields{get(handles.FieldName_1,'Value')}; % selected string for the second field
3180if isempty(field_1)%||(numel(UvData.FileType)>=2 && strcmp(UvData.FileType{2},'image'))
3181    set(handles.SubField,'Value',0)
3182    SubField_Callback(hObject, eventdata, handles)
3183    return
3184else
3185    set(handles.SubField,'Value',1)%state that a second field is now entered
3186end
3187
3188%% read the rootfile input display
3189[RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
3190FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];
3191[tild,tild,tild,i1,i2,j1,j2]=fileparts_uvmat(get(handles.FileIndex,'String'));
3192switch field_1
3193    case 'get_field...'
3194        set_veltype_display(0) % no veltype display
3195        hget_field=findobj(allchild(0),'name','get_field_1');
3196        if ~isempty(hget_field)
3197            delete(hget_field)
3198        end
3199        hget_field=get_field(FileName_1);
3200        set(hget_field,'name','get_field_1')
3201        hhget_field=guidata(hget_field);
3202        set(hhget_field.list_fig,'Value',1)
3203        set(hhget_field.list_fig,'String',{'uvmat'})
3204        if check_new
3205            UvData.FileType{2}=UvData.FileType{1};
3206            set(handles.FileIndex_1,'String',get(handles.FileIndex,'String'))
3207              set(handles.uvmat,'UserData',UvData)
3208        end
3209    case 'image'
3210        %% look for image corresponding to civ data
3211        imagename='';
3212        if  isfield(UvData.Field,'Civ2_ImageA')%get the corresponding input image in the netcdf file
3213            imagename=UvData.Field.Civ2_ImageA;
3214        elseif isfield(UvData.Field,'Civ1_ImageA')%
3215            imagename=UvData.Field.Civ1_ImageA;
3216        else
3217            SubDirBase=regexprep(SubDir,'\..*','');%take the root part of SubDir, before the first dot '.'
3218            imagename=fullfile_uvmat(RootPath,SubDirBase,RootFile,'.png',NomType,i1,[],j1,[]);
3219        end
3220        if ~exist(imagename,'file')
3221            imagename=uigetfile_uvmat('Pick an image file',imagename,'image');
3222           
3223        end
3224        if isempty(imagename)
3225            set(handles.SubField,'Value',0)
3226            return
3227        else
3228            display_file_name(handles,imagename,2)%display the image as second field
3229        end
3230    otherwise
3231        check_refresh=1;
3232        if check_new% if a second field was not previously entered, we just read another field in the first input file
3233            set(handles.FileIndex_1,'String',get(handles.FileIndex,'String'))
3234            set(handles.FileExt_1,'String',get(handles.FileExt,'String'))
3235           
3236            UvData.FileType{2}=UvData.FileType{1};
3237            UvData.XmlData{2}= UvData.XmlData{1};
3238            transform=get(handles.TransformPath,'UserData');
3239             if (~isa(transform,'function_handle')||nargin(transform)<3)
3240                set(handles.uvmat,'UserData',UvData)
3241                set(handles.TransformName,'value',2); % set transform fct to 'sub_field' if the current fct does not accept two input fields
3242                TransformName_Callback(hObject, eventdata, handles)% activate transform_fct_Callback and refresh current plot
3243                 check_refresh=0;
3244             end             
3245        end
3246        if ~isequal(field,'image')
3247            set(handles.TitleNpxy,'Visible','off')% visible npx,pxcm... buttons
3248            set(handles.num_Npx,'Visible','off')
3249            set(handles.num_Npy,'Visible','off')
3250        end
3251        set(handles.uvmat,'UserData',UvData)
3252 
3253        if check_refresh && ~(isfield(UvData,'NewSeries')&&isequal(UvData.NewSeries,1))
3254            run0_Callback(hObject, eventdata, handles)
3255        end
3256end
3257
3258%------------------------------------------------------------------------
3259% --- set the visibility of relevant velocity type menus:
3260function menu=set_veltype_display(Civ,FileType)
3261%------------------------------------------------------------------------
3262if ~exist('FileType','var')
3263    FileType='civx';
3264end
3265switch FileType
3266    case 'civx'
3267        menu={'civ1';'interp1';'filter1';'civ2';'interp2';'filter2'};
3268        if isequal(Civ,0)
3269            imax=0;
3270        elseif isequal(Civ,1) || isequal(Civ,2)
3271            imax=1;
3272        elseif isequal(Civ,3)
3273            imax=3;
3274        elseif isequal(Civ,4) || isequal(Civ,5)
3275            imax=4;
3276        elseif isequal(Civ,6) %patch2
3277            imax=6;
3278        end
3279    case 'civdata'
3280        menu={'civ1';'filter1';'civ2';'filter2'};
3281        if isequal(Civ,0)
3282            imax=0;
3283        elseif isequal(Civ,1) || isequal(Civ,2)
3284            imax=1;
3285        elseif isequal(Civ,3)
3286            imax=2;
3287        elseif isequal(Civ,4) || isequal(Civ,5)
3288            imax=3;
3289        elseif isequal(Civ,6) %patch2
3290            imax=4;
3291        end
3292end
3293menu=menu(1:imax);
3294
3295%------------------------------------------------------------------------
3296% --- Executes on button press in FixVelType.
3297function FixVelType_Callback(hObject, eventdata, handles)
3298%------------------------------------------------------------------------
3299% refresh the current plot if the fixed  veltype is unselected
3300if ~get(handles.FixVelType,'Value')
3301    run0_Callback(hObject, eventdata, handles)
3302end
3303
3304%------------------------------------------------------------------------
3305% --- Executes on button press in VelType.
3306function VelType_Callback(hObject, eventdata, handles)
3307%------------------------------------------------------------------------
3308set(handles.FixVelType,'Value',1)
3309run0_Callback(hObject, eventdata, handles)
3310
3311%------------------------------------------------------------------------
3312% --- Executes on choice selection in VelType_1.
3313function VelType_1_Callback(hObject, eventdata, handles)
3314%------------------------------------------------------------------------
3315set(handles.FixVelType,'Value',1)% the velocity type is now imposed by the GUI (not automatic)
3316UvData=get(handles.uvmat,'UserData');
3317set(handles.run0,'BackgroundColor',[1 1 0])%paint run0 button in yellow to indicate its activation
3318drawnow   
3319InputFile=read_GUI(handles.InputFile);% read the input file parameters
3320[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
3321[RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
3322FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];% name of the first input file
3323
3324check_refresh=0;
3325if isempty(InputFile.VelType_1)
3326        FileName_1='';% we plot the first input field without the second field
3327        set(handles.SubField,'Value',0)
3328        SubField_Callback(hObject, eventdata, handles)% activate SubField_Callback and refresh current plot, removing the second field
3329elseif get(handles.SubField,'Value')% if subfield is already 'on'
3330     FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];% name of the second input file
3331     check_refresh=1;%will refresh the current plot
3332else% we introduce the same file (with a different field) for the second series
3333     FileName_1=FileName;% we compare two fields in the same file
3334     UvData.FileType{2}=UvData.FileType{1};
3335     UvData.XmlData{2}= UvData.XmlData{1};
3336     set(handles.SubField,'Value',1)
3337     transform=get(handles.TransformPath,'UserData');
3338     if (~isa(transform,'function_handle')||nargin(transform)<3)
3339        set(handles.uvmat,'UserData',UvData)
3340        set(handles.TransformName,'value',2); % set transform fct to 'sub_field' if the current fct does not accept two input fields
3341        TransformName_Callback(hObject, eventdata, handles)% activate transform_fct_Callback and refresh current plot
3342     else
3343         check_refresh=1;
3344     end 
3345end
3346
3347% refresh the current plot if it has not been done previously
3348if check_refresh
3349    UvData.FileName_1='';% desactivate the use of a constant second file
3350    set(handles.uvmat,'UserData',UvData)
3351    num_i1=stra2num(get(handles.i1,'String'));
3352    num_i2=stra2num(get(handles.i2,'String'));
3353    num_j1=stra2num(get(handles.j1,'String'));
3354    num_j2=stra2num(get(handles.j2,'String'));
3355    [tild,tild,tild,i1_1,i2_1,j1_1,j2_1]=fileparts_uvmat(['xx' FileIndex_1]);
3356    errormsg=refresh_field(handles,FileName,FileName_1,num_i1,num_i2,num_j1,num_j2,i1_1,i2_1,j1_1,j2_1);
3357    if ~isempty(errormsg)
3358        msgbox_uvmat('ERROR',errormsg);
3359    else
3360        set(handles.i1,'BackgroundColor',[1 1 1])
3361        set(handles.i2,'BackgroundColor',[1 1 1])
3362        set(handles.j1,'BackgroundColor',[1 1 1])
3363        set(handles.j2,'BackgroundColor',[1 1 1])
3364        set(handles.FileIndex,'BackgroundColor',[1 1 1])
3365        set(handles.FileIndex_1,'BackgroundColor',[1 1 1])
3366    end
3367    set(handles.run0,'BackgroundColor',[1 0 0])
3368end
3369
3370
3371%------------------------------------------------------------------------
3372% --- reset civ buttons
3373function reset_vel_type(handles_civ0,handle1)
3374%------------------------------------------------------------------------
3375for ibutton=1:length(handles_civ0)
3376    set(handles_civ0(ibutton),'BackgroundColor',[0.831 0.816 0.784])
3377    set(handles_civ0(ibutton),'Value',0)
3378end
3379if exist('handle1','var')%handles of selected button
3380        set(handle1,'BackgroundColor',[1 1 0]) 
3381end
3382
3383%-----------------------------------------------------------------------
3384% --- Executes on button press in MENUVOLUME.
3385function VOLUME_Callback(hObject, eventdata, handles)
3386%-----------------------------------------------------------------------
3387%errordlg('command VOL not implemented yet')
3388if ishandle(handles.UVMAT_title)
3389    delete(handles.UVMAT_title)
3390end
3391UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
3392if isequal(get(handles.VOLUME,'Value'),1)
3393    set(handles.CheckZoom,'Value',0)
3394%     set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
3395    set(handles.edit_vect,'Value',0)
3396    edit_vect_Callback(hObject, eventdata, handles)
3397    set(handles.CheckEditObject,'Value',0)
3398%     set(handles.CheckEditObject,'BackgroundColor',[0.7 0.7 0.7])
3399%     set(handles.cal,'Value',0)
3400%     set(handles.cal,'BackgroundColor',[0 1 0])
3401    set(handles.edit_vect,'Value',0)
3402    edit_vect_Callback(hObject, eventdata, handles)
3403    %initiate set_object GUI
3404    data.Name='VOLUME';
3405    if isfield(UvData,'CoordType')
3406        data.CoordType=UvData.CoordType;
3407    end
3408    if isfield(UvData.Field,'CoordMesh')&~isempty(UvData.Field.CoordMesh)
3409        data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
3410        data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
3411        data.DX=UvData.Field.CoordMesh;
3412        data.DY=UvData.Field.CoordMesh;
3413    elseif isfield(UvData.Field,'AX')&isfield(UvData.Field,'AY')& isfield(UvData.Field,'A')%only image
3414        np=size(UvData.Field.A);
3415        meshx=(UvData.Field.AX(end)-UvData.Field.AX(1))/np(2);
3416        meshy=abs(UvData.Field.AY(end)-UvData.Field.AY(1))/np(1);
3417        data.RangeY=max(meshx,meshy);
3418        data.RangeX=max(meshx,meshy);
3419        data.DX=max(meshx,meshy);
3420    end
3421    data.ParentButton=handles.VOLUME;
3422    PlotHandles=get_plot_handles(handles);%get the handles of the interface elements setting the plotting parameters
3423    [hset_object,UvData.sethandles]=set_object(data,PlotHandles);% call the set_object interface with action on haxes,
3424                                                      % associate the set_object interface handle to the plotting axes
3425    %set(hset_object,'Position',get(handles.uvmat,'Position')+UvData.OpenParam.PosSetObject)
3426    UvData.MouseAction='create_object';
3427else
3428    set(handles.VOLUME,'BackgroundColor',[0 1 0])
3429end
3430set(handles.uvmat,'UserData',UvData)
3431
3432%-------------------------------------------------------
3433function edit_vect_Callback(hObject, eventdata, handles)
3434%-------------------------------------------------------
3435%
3436if isequal(get(handles.edit_vect,'Value'),1)
3437    VelTypeMenu=get(handles.VelType,'String');
3438    VelType=VelTypeMenu{get(handles.VelType,'Value')};
3439    if ~strcmp(VelType,'civ2') && ~strcmp(VelType,'civ1')
3440        msgbox_uvmat('ERROR','manual correction only possible for CIV1 or CIV2 velocity fields')
3441    end
3442    set(handles.record,'Visible','on')
3443    set(handles.edit_vect,'BackgroundColor',[1 1 0])
3444    set(handles.CheckEditObject,'Value',0)
3445    set(handles.CheckZoom,'Value',0)
3446%     set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
3447%     set(handles.CheckEditObject,'BackgroundColor',[0.7 0.7 0.7])
3448    set(gcf,'Pointer','arrow')
3449else
3450    set(handles.record,'Visible','off')
3451    set(handles.edit_vect,'BackgroundColor',[0.7 0.7 0.7])
3452end
3453
3454%----------------------------------------------
3455function save_mask_Callback(hObject, eventdata, handles)
3456%-----------------------------------------------------------------------
3457UvData=get(handles.uvmat,'UserData');
3458
3459flag=1;
3460npx=size(UvData.Field.A,2);
3461npy=size(UvData.Field.A,1);
3462xi=0.5:npx-0.5;
3463yi=0.5:npy-0.5;
3464[Xi,Yi]=meshgrid(xi,yi);
3465if isfield(UvData,'ProjObject')
3466    for iobj=1:length(UvData.ProjObject)
3467        ObjectData=UvData.ProjObject{iobj};
3468        if isfield(ObjectData,'ProjMode') &&(isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside'));
3469            flagobj=1;
3470            testphys=0; %coordinates in pixels by default
3471            if isfield(ObjectData,'CoordType') && isequal(ObjectData.CoordType,'phys')
3472                if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
3473                    Calib=UvData.XmlData{1}.GeometryCalib;
3474                    testphys=1;
3475                end
3476            end
3477            if isfield(ObjectData,'Coord')& isfield(ObjectData,'Style')
3478                if isequal(ObjectData.Type,'polygon')
3479                    X=ObjectData.Coord(:,1);
3480                    Y=ObjectData.Coord(:,2);
3481                    if testphys
3482                        [X,Y]=px_XYZ(Calib,X,Y,0);% to generalise with 3D cases
3483                    end
3484                    flagobj=~inpolygon(Xi,Yi,X',Y');%=0 inside the polygon, 1 outside                 
3485                elseif isequal(ObjectData.Type,'ellipse')
3486                    if testphys
3487                        %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
3488                    end
3489                    RangeX=max(ObjectData.RangeX);
3490                    RangeY=max(ObjectData.RangeY);
3491                    X2Max=RangeX*RangeX;
3492                    Y2Max=RangeY*RangeY;
3493                    distX=(Xi-ObjectData.Coord(1,1));
3494                    distY=(Yi-ObjectData.Coord(1,2));
3495                    flagobj=(distX.*distX/X2Max+distY.*distY/Y2Max)>1;
3496                elseif isequal(ObjectData.Type,'rectangle')
3497                    if testphys
3498                        %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
3499                    end
3500                    distX=abs(Xi-ObjectData.Coord(1,1));
3501                    distY=abs(Yi-ObjectData.Coord(1,2));
3502                    flagobj=distX>max(ObjectData.RangeX) | distY>max(ObjectData.RangeY);
3503                end
3504                if isequal(ObjectData.ProjMode,'mask_outside')
3505                    flagobj=~flagobj;
3506                end
3507                flag=flag & flagobj;
3508            end
3509        end
3510    end
3511end
3512% flag=~flag;
3513%mask name
3514RootPath=get(handles.RootPath,'String');
3515RootFile=get(handles.RootFile,'String');
3516RootFile=regexprep(RootFile,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3517filebase=fullfile(RootPath,RootFile);
3518list=get(handles.masklevel,'String');
3519masknumber=num2str(length(list));
3520maskindex=get(handles.masklevel,'Value');
3521mask_name=fullfile_uvmat(RootPath,SubDir,[RootFile '_' masknumber 'mask'],'.png','_1',maskindex);
3522%mask_name=name_generator([filebase '_' masknumber 'mask'],maskindex,1,'.png','_i');
3523imflag=uint8(255*(0.392+0.608*flag));% =100 for flag=0 (vectors not computed when 20<imflag<200)
3524imflag=flipdim(imflag,1);
3525% imflag=uint8(255*flag);% =0 for flag=0 (vectors=0 when 20<imflag<200)
3526msgbox_uvmat('CONFIRMATION',[mask_name ' saved'])
3527imwrite(imflag,mask_name,'BitDepth',8);
3528
3529%display the mask
3530figure;
3531vec=linspace(0,1,256);%define a linear greyscale colormap
3532map=[vec' vec' vec'];
3533colormap(map)
3534
3535image(imflag);
3536
3537%------------------------------------------------------------------------
3538%------------------------------------------------------------------------
3539%  - FUNCTIONS FOR SETTING PLOTTING PARAMETERS
3540
3541%------------------------------------------------------------------------
3542%------------------------------------------------------------------------
3543% --- Executes on selection change in TransformName.
3544
3545function TransformName_Callback(hObject, eventdata, handles)
3546%------------------------------------------------------------------------
3547UvData=get(handles.uvmat,'UserData');
3548menu=get(handles.TransformName,'String');%refresh
3549ichoice=get(handles.TransformName,'Value');%item number in the menu
3550transform_name=menu{ichoice};% choice of the transform fct
3551list_path=get(handles.TransformName,'UserData');
3552
3553%% add a new item to the menu if the option 'more...' has been selected
3554prev_path=fullfile(get(handles.TransformPath,'String'));
3555if ~exist(prev_path,'dir')
3556    prev_path=fullfile(fileparts(which('uvmat')),'transform_field');
3557end
3558if strcmp(transform_name,'more...');
3559    transform_fct_chosen=uigetfile_uvmat('Pick the transform function',prev_path,'.m');
3560    if ~isempty(transform_fct_chosen)
3561        [PathName,transform_name]=fileparts(transform_fct_chosen);
3562        ichoice=find(strcmp(transform_name,menu),1);%look for the selected fct in the existing menu
3563        if isempty(ichoice)% if the item is not found, add it to the menu (before 'more...' and select it)
3564            menu=[menu(1:end-1);{transform_name};{'more...'}];
3565            ichoice=numel(menu)-1;
3566        end
3567        list_path{ichoice}=PathName;%update the list fo fct paths
3568        set(handles.TransformName,'String',menu)
3569        set(handles.TransformName,'Value',ichoice)
3570       
3571        % save the new menu in the personal file 'uvmat_perso.mat'
3572        dir_perso=prefdir;%personal Matalb directory
3573        profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
3574        if exist(profil_perso,'file')
3575            nb_builtin=UvData.OpenParam.NbBuiltin;% number of 'builtin' (basic) transform fcts in uvmat
3576            if nb_builtin<numel(list_path)
3577                for ilist=nb_builtin+1:numel(list_path)
3578                    transform_fct{ilist-nb_builtin}=[fullfile(list_path{ilist},menu{ilist}) '.m'];
3579                end
3580                save (profil_perso,'transform_fct','-append'); %store the root name for future opening of uvmat
3581            end
3582        end
3583    end
3584end
3585
3586%% create the function handle of the selected fct
3587if isempty(list_path{ichoice})% case of no selected fct
3588    transform_handle=[];
3589else
3590    if ~exist(list_path{ichoice},'dir')
3591        msgbox_uvmat('ERROR','invalid fct path: select the transform fct again with the option more...')
3592        return
3593    end
3594    current_dir=pwd;%current working dir
3595    cd(list_path{ichoice})
3596    transform_handle=str2func(transform_name);
3597    cd(current_dir)
3598end
3599set(handles.TransformPath,'String',list_path{ichoice})
3600set(handles.TransformPath,'UserData',transform_handle)
3601set(handles.TransformName,'UserData',list_path)
3602
3603%% update the ToolTip string of the menu TransformName with the first line of the selected fct file
3604if isempty(list_path{ichoice})% case of no selected fct
3605    set(handles.TransformName,'ToolTipString','transform_fct:choose a transform function')
3606else
3607    try
3608        [fid,errormsg] =fopen([fullfile(list_path{ichoice},transform_name) '.m']);
3609        InputText=textscan(fid,'%s',1,'delimiter','\n');
3610        fclose(fid)
3611        set(handles.TransformName,'ToolTipString',['transform_fct: ' InputText{1}{1}])% put the first line of the selected function as tooltip help
3612    end
3613end
3614
3615%% adapt the GUI to the input/output conditions of the selected transform fct
3616DataOut=[];
3617CoordUnit='';
3618CoordUnitPrev='';
3619if isfield(UvData,'Field')&&isfield(UvData.Field,'CoordUnit')
3620    CoordUnitPrev=UvData.Field.CoordUnit;
3621end
3622if ~isempty(list_path{ichoice})
3623    if nargin(transform_handle)>1 && isfield(UvData,'XmlData')&&~isempty(UvData.XmlData)
3624        XmlData=UvData.XmlData{1};
3625        DataOut=feval(transform_handle,'*',XmlData);
3626        if isfield(DataOut,'CoordUnit')% set the requested coord unit (info used to possibly delete the current projection objects)
3627            CoordUnit=DataOut.CoordUnit;
3628        end
3629        if isfield(DataOut,'InputFieldType')% to be used to impose a type of input file (eg. for image transform)
3630            UvData.InputFieldType=DataOut.InputFieldType;
3631        end
3632        if isfield(DataOut,'XmlData')%  used to add transform parameters at selection of the transform fct
3633            ListFields=fieldnames(DataOut.XmlData);
3634            for ilist=1:numel(ListFields)
3635            UvData.XmlData{1}.(ListFields{ilist})=DataOut.XmlData.(ListFields{ilist});
3636            end
3637        end
3638    else
3639        DataOut=feval(transform_handle,'*');
3640    end
3641end
3642
3643
3644%% delete drawn objects if the output CooordUnit is different from the previous one
3645if ~strcmp(CoordUnit,CoordUnitPrev)
3646    set(handles.CheckFixLimits,'Value',0)
3647% set(handles.CheckFixLimits,'BackgroundColor',[0.7 0.7 0.7])
3648    hother=findobj('Tag','proj_object');%find all the proj objects
3649    for iobj=1:length(hother)
3650        delete_object(hother(iobj))
3651    end
3652    hother=findobj('Tag','DeformPoint');%find all the proj objects
3653    for iobj=1:length(hother)
3654        delete_object(hother(iobj))
3655    end
3656    hh=findobj('Tag','calib_points');
3657    if ~isempty(hh)
3658        delete(hh)
3659    end
3660    hhh=findobj('Tag','calib_marker');
3661    if ~isempty(hhh)
3662        delete(hhh)
3663    end
3664    set(handles.ListObject,'Value',1)
3665    set(handles.ListObject,'String',{''})
3666    set(handles.ListObject_1,'Value',1)
3667    set(handles.ListObject_1,'String',{''})
3668    set(handles.CheckViewObject,'value',0)
3669    CheckViewObject_Callback(hObject, eventdata, handles)
3670    set(handles.CheckViewField,'value',0)
3671    CheckViewField_Callback(hObject, eventdata, handles)
3672    set(handles.CheckEditObject,'Value',0)
3673    CheckEditObject_Callback(hObject, eventdata, handles)
3674    UvData.ProjObject={[]};
3675end
3676set(handles.uvmat,'UserData',UvData)
3677
3678%% refresh the current plot
3679if isempty(list_path{ichoice}) || nargin(transform_handle)<3
3680    set(handles.SubField,'Value',0)
3681    SubField_Callback(hObject, eventdata, handles)
3682else
3683    run0_Callback(hObject, eventdata, handles)
3684end
3685
3686%------------------------------------------------
3687%CALLBACKS FOR PLOTTING PARAMETERS
3688%-------------------------------------------------
3689%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3690% Plot coordinates
3691%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3692%------------------------------------------------------------------------
3693function num_MinX_Callback(hObject, eventdata, handles)
3694%------------------------------------------------------------------------
3695set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3696% set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3697update_plot(handles);
3698
3699%------------------------------------------------------------------------
3700function num_MaxX_Callback(hObject, eventdata, handles)
3701%------------------------------------------------------------------------
3702set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3703% set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3704update_plot(handles);
3705
3706%------------------------------------------------------------------------
3707function num_MinY_Callback(hObject, eventdata, handles)
3708%------------------------------------------
3709set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3710% set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3711update_plot(handles);
3712
3713%------------------------------------------------------------------------
3714function num_MaxY_Callback(hObject, eventdata, handles)
3715%------------------------------------------------------------------------
3716set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3717% set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3718update_plot(handles);
3719
3720%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3721% Scalar or image representation
3722%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3723%------------------------------------------------------------------------
3724function num_MinA_Callback(hObject, eventdata, handles)
3725%------------------------------------------
3726set(handles.CheckFixScalar,'Value',1) %suppress auto mode
3727% set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3728MinA=str2double(get(handles.num_MinA,'String'));
3729MaxA=str2double(get(handles.num_MaxA,'String'));
3730if MinA>MaxA% switch minA and maxA in case of error
3731    MinA_old=MinA;
3732    MinA=MaxA;
3733    MaxA=MinA_old;
3734    set(handles.num_MinA,'String',num2str(MinA,5));
3735    set(handles.num_MaxA,'String',num2str(MaxA,5));
3736end
3737update_plot(handles);
3738
3739%------------------------------------------------------------------------
3740function num_MaxA_Callback(hObject, eventdata, handles)
3741%------------------------------------------------------------------------
3742set(handles.CheckFixScalar,'Value',1) %suppress auto mode
3743% set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3744MinA=str2double(get(handles.num_MinA,'String'));
3745MaxA=str2double(get(handles.num_MaxA,'String'));
3746if MinA>MaxA% switch minA and maxA in case of error
3747        MinA_old=MinA;
3748    MinA=MaxA;
3749    MaxA=MinA_old;
3750    set(handles.num_MinA,'String',num2str(MinA,5));
3751    set(handles.num_MaxA,'String',num2str(MaxA,5));
3752end
3753update_plot(handles);
3754
3755%------------------------------------------------------------------------
3756function CheckFixScalar_Callback(hObject, eventdata, handles)
3757%------------------------------------------------------------------------
3758test=get(handles.CheckFixScalar,'Value');
3759if test
3760%     set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3761else
3762%     set(handles.CheckFixScalar,'BackgroundColor',[0.7 0.7 0.7])
3763    update_plot(handles);
3764end
3765
3766%-------------------------------------------------------------------
3767function CheckBW_Callback(hObject, eventdata, handles)
3768%-------------------------------------------------------------------
3769update_plot(handles);
3770
3771%-------------------------------------------------------------------
3772function num_Opacity_Callback(hObject, eventdata, handles)
3773update_plot(handles);
3774%-------------------------------------------------------------------
3775
3776%-------------------------------------------------------------------
3777function ListContour_Callback(hObject, eventdata, handles)
3778%-------------------------------------------------------------------
3779val=get(handles.ListContour,'Value');
3780if val==2
3781    set(handles.interval_txt,'Visible','on')
3782    set(handles.num_IncrA,'Visible','on')
3783else
3784    set(handles.interval_txt,'Visible','off')
3785    set(handles.num_IncrA,'Visible','off')
3786end
3787update_plot(handles);
3788
3789%-------------------------------------------------------------------
3790function num_IncrA_Callback(hObject, eventdata, handles)
3791%-------------------------------------------------------------------
3792update_plot(handles);
3793
3794
3795%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3796% Vector representation
3797%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3798%-------------------------------------------------------------------
3799function CheckHideWarning_Callback(hObject, eventdata, handles)
3800%-------------------------------------------------------------------
3801update_plot(handles);
3802
3803%-------------------------------------------------------------------
3804function CheckHideFalse_Callback(hObject, eventdata, handles)
3805%-------------------------------------------------------------------
3806update_plot(handles);
3807
3808%-------------------------------------------------------------------
3809function num_VecScale_Callback(hObject, eventdata, handles)
3810%-------------------------------------------------------------------
3811set(handles.CheckFixVectors,'Value',1);
3812set(handles.CheckFixVectors,'BackgroundColor',[1 1 0])
3813update_plot(handles);
3814
3815%-------------------------------------------------------------------
3816function CheckFixVectors_Callback(hObject, eventdata, handles)
3817%-------------------------------------------------------------------
3818test=get(handles.CheckFixVectors,'Value');
3819if test
3820%     set(handles.CheckFixVectors,'BackgroundColor',[1 1 0])
3821else
3822    update_plot(handles);
3823    %set(handles.num_VecScale,'String',num2str(ScalOut.num_VecScale,3))
3824%     set(handles.CheckFixVectors,'BackgroundColor',[0.7 0.7 0.7])
3825end
3826
3827%------------------------------------------------------------------------
3828% --- Executes on selection change in CheckDecimate4 (nb_vec/4).
3829%------------------------------------------------------------------------
3830function CheckDecimate4_Callback(hObject, eventdata, handles)
3831
3832if isequal(get(handles.CheckDecimate4,'Value'),1)
3833    set(handles.CheckDecimate16,'Value',0)
3834end
3835update_plot(handles);
3836
3837%------------------------------------------------------------------------
3838% --- Executes on selection change in CheckDecimate16 (nb_vec/16).
3839%------------------------------------------------------------------------
3840function CheckDecimate16_Callback(hObject, eventdata, handles)
3841
3842if isequal(get(handles.CheckDecimate16,'Value'),1)
3843    set(handles.CheckDecimate4,'Value',0)
3844end
3845update_plot(handles);
3846
3847%------------------------------------------------------------------------
3848% --- Executes on selection change in ColorCode menu
3849function ColorCode_Callback(hObject, eventdata, handles)
3850%------------------------------------------------------------------------
3851% edit the choice for color code
3852update_color_code_boxes(handles);
3853update_plot(handles);
3854
3855%------------------------------------------------------------------------
3856function update_color_code_boxes(handles)
3857%------------------------------------------------------------------------
3858list_code=get(handles.ColorCode,'String');% list menu fields
3859colcode= list_code{get(handles.ColorCode,'Value')}; % selected field
3860enable_slider='off';%default
3861enable_bounds='off';%default
3862enable_scalar='off';%default
3863switch colcode
3864    case {'rgb','bgr'}
3865        enable_slider='on';
3866        enable_bounds='on';
3867        enable_scalar='on';
3868    case '64 colors'
3869        enable_bounds='on';
3870        enable_scalar='on';
3871end
3872set(handles.Slider1,'Visible',enable_slider)
3873set(handles.Slider2,'Visible', enable_slider)
3874set(handles.num_ColCode1,'Visible',enable_slider)
3875set(handles.num_ColCode2,'Visible',enable_slider)
3876set(handles.TitleColCode1,'Visible',enable_slider)
3877set(handles.TitleColCode2,'Visible',enable_slider)
3878set(handles.CheckFixVecColor,'Visible',enable_bounds)
3879set(handles.num_MinVec,'Visible',enable_bounds)
3880set(handles.num_MaxVec,'Visible',enable_bounds)
3881set(handles.ColorScalar,'Visible',enable_scalar)
3882set_vec_col_bar(handles)
3883
3884%------------------------------------------------------------------
3885% --- Executes on selection change in ColorScalar: choice of the color code.
3886function ColorScalar_Callback(hObject, eventdata, handles)
3887%------------------------------------------------------------------
3888% edit the choice for color code
3889list_scalar=get(handles.ColorScalar,'String');% list menu fields
3890col_scalar= list_scalar{get(handles.ColorScalar,'Value')}; % selected field
3891if isequal(col_scalar,'ima_cor')
3892    set(handles.CheckFixVecColor,'Value',1)%fixed scale by default
3893    ColorCode='rgb';
3894    set(handles.num_MinVec,'String','0')
3895    set(handles.num_MaxVec,'String','1')
3896    set(handles.num_ColCode1,'String','0.333')
3897    set(handles.num_ColCode2,'String','0.666')
3898else
3899    set(handles.CheckFixVecColor,'Value',0)%auto scale between min,max by default
3900    ColorCode='64 colors';
3901end
3902ColorCodeList=get(handles.ColorCode,'String');
3903ichoice=find(strcmp(ColorCode,ColorCodeList),1);
3904set(handles.ColorCode,'Value',ichoice)% set color code in the menu
3905
3906update_color_code_boxes(handles);
3907%replot the current graph
3908run0_Callback(hObject, eventdata, handles)
3909
3910%----------------------------------------------------------------
3911% -- Executes on slider movement to set the color code
3912%
3913function Slider1_Callback(hObject, eventdata, handles)
3914%------------------------------------------------------------------
3915slider1=get(handles.Slider1,'Value');
3916min_val=str2num(get(handles.num_MinVec,'String'));
3917max_val=str2num(get(handles.num_MaxVec,'String'));
3918col=min_val+(max_val-min_val)*slider1;
3919set(handles.num_ColCode1,'String',num2str(col))
3920if(get(handles.Slider2,'Value') < col)%move also the second slider at the same value if needed
3921    set(handles.Slider2,'Value',col)
3922    set(handles.num_ColCode2,'String',num2str(col))
3923end
3924set_vec_col_bar(handles)
3925update_plot(handles);
3926
3927%----------------------------------------------------------------
3928% Executes on slider movement to set the color code
3929%----------------------------------------------------------------
3930function Slider2_Callback(hObject, eventdata, handles)
3931slider2=get(handles.Slider2,'Value');
3932min_val=str2num(get(handles.num_MinVec,'String'));
3933max_val=str2num(get(handles.num_MaxVec,'String'));
3934col=min_val+(max_val-min_val)*slider2;
3935set(handles.num_ColCode2,'String',num2str(col))
3936if(get(handles.Slider1,'Value') > col)%move also the first slider at the same value if needed
3937    set(handles.Slider1,'Value',col)
3938    set(handles.num_ColCode1,'String',num2str(col))
3939end
3940set_vec_col_bar(handles)
3941update_plot(handles);
3942
3943%----------------------------------------------------------------
3944% --- Execute on return carriage on the edit box corresponding to slider 1
3945%----------------------------------------------------------------
3946function num_ColCode1_Callback(hObject, eventdata, handles)
3947set_vec_col_bar(handles)
3948update_plot(handles);
3949
3950%----------------------------------------------------------------
3951% --- Execute on return carriage on the edit box corresponding to slider 2
3952%----------------------------------------------------------------
3953function num_ColCode2_Callback(hObject, eventdata, handles)
3954set_vec_col_bar(handles)
3955update_plot(handles);
3956%------------------------------------------------------------------------
3957%-------------------------------------------------------
3958% --- Executes on button press in CheckFixVecColor.
3959%-------------------------------------------------------
3960function VecColBar_Callback(hObject, eventdata, handles)
3961set_vec_col_bar(handles)
3962
3963%------------------------------------------------------------------------
3964% --- Executes on button press in CheckFixVecColor.
3965function CheckFixVecColor_Callback(hObject, eventdata, handles)
3966%------------------------------------------------------------------------
3967if ~get(handles.CheckFixVecColor,'Value')
3968    update_plot(handles);
3969end
3970
3971%------------------------------------------------------------------------
3972% --- Executes on selection change in num_MaxVec.
3973function num_MinVec_Callback(hObject, eventdata, handles)
3974%------------------------------------------------------------------------
3975num_MaxVec_Callback(hObject, eventdata, handles)
3976
3977%------------------------------------------------------------------------
3978% --- Executes on selection change in num_MaxVec.
3979function num_MaxVec_Callback(hObject, eventdata, handles)
3980%------------------------------------------------------------------------
3981set(handles.CheckFixVecColor,'Value',1)
3982CheckFixVecColor_Callback(hObject, eventdata, handles)
3983min_val=str2num(get(handles.num_MinVec,'String'));
3984max_val=str2num(get(handles.num_MaxVec,'String'));
3985slider1=get(handles.Slider1,'Value');
3986slider2=get(handles.Slider2,'Value');
3987colcode1=min_val+(max_val-min_val)*slider1;
3988colcode2=min_val+(max_val-min_val)*slider2;
3989set(handles.num_ColCode1,'String',num2str(colcode1))
3990set(handles.num_ColCode2,'String',num2str(colcode2))
3991update_plot(handles);
3992
3993%------------------------------------------------------------------------
3994% --- update the display of color code for vectors (on vecColBar)
3995function set_vec_col_bar(handles)
3996%------------------------------------------------------------------------
3997%get the image of the color display button 'VecColBar' in pixels
3998set(handles.VecColBar,'Unit','pixel');
3999pos_vert=get(handles.VecColBar,'Position');
4000set(handles.VecColBar,'Unit','Normalized');
4001width=ceil(pos_vert(3));
4002height=ceil(pos_vert(4));
4003
4004%get slider indications
4005list=get(handles.ColorCode,'String');
4006ichoice=get(handles.ColorCode,'Value');
4007colcode.ColorCode=list{ichoice};
4008colcode.MinVec=str2num(get(handles.num_MinVec,'String'));
4009colcode.MaxVec=str2num(get(handles.num_MaxVec,'String'));
4010test3color=strcmp(colcode.ColorCode,'rgb') || strcmp(colcode.ColorCode,'bgr');
4011if test3color
4012    colcode.ColCode1=str2num(get(handles.num_ColCode1,'String'));
4013    colcode.ColCode2=str2num(get(handles.num_ColCode2,'String'));
4014end
4015vec_C=colcode.MinVec+(colcode.MaxVec-colcode.MinVec)*(0.5:width-0.5)/width;%sample of vec_C values from min to max
4016[colorlist,col_vec]=set_col_vec(colcode,vec_C);
4017oneheight=ones(1,height);
4018A1=colorlist(col_vec,1)*oneheight;
4019A2=colorlist(col_vec,2)*oneheight;
4020A3=colorlist(col_vec,3)*oneheight;
4021A(:,:,1)=A1';
4022A(:,:,2)=A2';
4023A(:,:,3)=A3';
4024set(handles.VecColBar,'Cdata',A)
4025
4026%-------------------------------------------------------------------
4027function update_plot(handles)
4028%-------------------------------------------------------------------
4029UvData=get(handles.uvmat,'UserData');
4030AxeData=UvData.PlotAxes;% retrieve the current plotted data
4031PlotParam=read_GUI(handles.uvmat);
4032[tild,PlotParamOut]= plot_field(AxeData,handles.PlotAxes,PlotParam);
4033errormsg=fill_GUI(PlotParamOut,handles.uvmat);
4034RUNColor=get(handles.run0,'BackgroundColor');%
4035if isequal(RUNColor,[1 0 1])% suppress magenta color (indicate that plot is  updated)
4036    set(handles.run0,'BackgroundColor',[1 0 0]);
4037end
4038
4039%------------------------------------------------------------------------
4040%------------------------------------------------------------------------
4041%   SELECTION AND EDITION OF PROJECTION OBJECTS
4042%------------------------------------------------------------------------
4043%------------------------------------------------------------------------
4044
4045% --- Executes on selection change in ListObject_1.
4046function ListObject_1_Callback(hObject, eventdata, handles)
4047list_str=get(handles.ListObject,'String');
4048UvData=get(handles.uvmat,'UserData');
4049ObjectData=UvData.ProjObject{get(handles.ListObject_1,'Value')};
4050
4051%% update the projection plot on uvmat
4052ProjData= proj_field(UvData.Field,ObjectData);%project the current input field on object ObjectData
4053plot_field(ProjData,handles.PlotAxes,read_GUI(handles.uvmat));% plot the projected field;
4054%replot all the objects within the new projected field
4055for IndexObj=1:numel(list_str)
4056        hobject=UvData.ProjObject{IndexObj}.DisplayHandle.uvmat;
4057        if isempty(hobject) || ~ishandle(hobject)
4058            hobject=handles.PlotAxes;
4059        end
4060        if isequal(IndexObj,get(handles.ListObject,'Value'))
4061            objectcolor='m'; %paint in magenta the currently selected object in ListObject
4062        else
4063            objectcolor='b';
4064        end
4065        UvData.ProjObject{IndexObj}.DisplayHandle.uvmat=plot_object(UvData.ProjObject{IndexObj},ObjectData,hobject,objectcolor);%draw the object in uvmat     
4066end
4067set(handles.uvmat,'UserData',UvData)
4068
4069%% display the object parameters if the GUI set_object is already opened
4070if ~get(handles.CheckViewObject,'Value')
4071    ZBounds=0; % default
4072    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4073        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4074        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4075    end
4076    ObjectData.Name=list_str{get(handles.ListObject_1,'Value')};
4077    set_object(ObjectData,[],ZBounds);
4078    set(handles.CheckViewObject,'Value',1)% show that the selected object in ListObject_1 is currently visualised
4079end
4080
4081%  desactivate the edit object mode
4082set(handles.CheckEditObject,'Value',0)
4083% set(handles.CheckEditObject,'BackgroundColor',[0.7,0.7,0.7])
4084
4085%------------------------------------------------------------------------
4086% --- Executes on selection change in ListObject.
4087function ListObject_Callback(hObject, eventdata, handles)
4088%------------------------------------------------------------------------
4089list_str=get(handles.ListObject,'String');
4090IndexObj=get(handles.ListObject,'Value');%present object selection
4091UvData=get(handles.uvmat,'UserData');
4092ObjectData=UvData.ProjObject{IndexObj};
4093    ZBounds=0; % default
4094    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4095        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4096        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4097    end
4098
4099%% show object features if view_object isselected
4100if get(handles.CheckViewObject,'value')
4101    set_object(ObjectData,[],ZBounds);
4102end
4103
4104%% The object  is displayed in set_object if this GUI is already opened
4105%
4106% hset_object=findobj(allchild(0),'tag','set_object');
4107% if ~isempty(hset_object)
4108%
4109%     ObjectData.Name=list_str{IndexObj};
4110%     set_object(ObjectData,[],ZBounds);
4111%     set(handles.CheckViewField,'Value',1)% show that the selected object in ListObject is currently visualised
4112% end
4113
4114%%  desactivate the edit object mode for security
4115set(handles.CheckEditObject,'Value',0)
4116
4117% set(handles.CheckEditObject,'BackgroundColor',[0.7,0.7,0.7])
4118
4119%% update the  plot on view_field if view_field is already openened
4120hview_field=findobj(allchild(0),'tag','view_field');
4121if isempty(hview_field)
4122    hhview_field.PlotAxes=[];
4123else
4124    Data=get(hview_field,'UserData');
4125    hhview_field=guidata(hview_field);
4126    ProjData= proj_field(UvData.Field,ObjectData);%project the current interface field on ObjectData
4127    [PlotType,PlotParam]=plot_field(ProjData,hhview_field.PlotAxes,read_GUI(hview_field));%read plotting parameters on the uvmat interface
4128   
4129    %write_plot_param(hhview_field,PlotParam); %update the display of plotting parameters for the current object
4130    haxes=findobj(hview_field,'tag','axes3');
4131    pos=get(hview_field,'Position'); 
4132    if strcmp(get(haxes,'Visible'),'off')%sempty(PlotParam.Coordinates)% case of no plot display (pure text table)
4133        h_TableDisplay=findobj(hview_field,'tag','TableDisplay');
4134        pos_table=get(h_TableDisplay,'Position');
4135        set(hview_field,'Position',[pos(1)+pos(3)-pos_table(3) pos(2)+pos(4)-pos_table(4) pos_table(3) pos_table(4)])
4136        drawnow% needed to change position before the next command
4137        set(hview_field,'UserData',Data);% restore the previously stored GUI position after GUI resizing
4138    else
4139%         set(hview_field,'Position',Data.GUISize)% return to the previously stored GUI position and size
4140    end
4141end
4142
4143%% update the color of the graphic object representation: the selected object in magenta, others in blue
4144update_object_color(handles.PlotAxes,hhview_field.PlotAxes,UvData.ProjObject{IndexObj}.DisplayHandle.uvmat)
4145
4146%------------------------------------------------------------------------
4147%--- update the color representation of objects (indicating the selected ones)
4148function update_object_color(axes_uvmat,axes_view_field,DisplayHandle)
4149%------------------------------------------------------------------------
4150if isempty(axes_view_field)% case with no view_field plot
4151hother=[findobj(axes_uvmat,'Tag','proj_object');findobj(axes_uvmat,'Tag','DeformPoint')];%find all the proj object and deform point representations
4152else
4153hother=[findobj(axes_uvmat,'Tag','proj_object') ;findobj(axes_view_field,'Tag','proj_object');... %find all the proj object representations
4154findobj(axes_uvmat,'Tag','DeformPoint'); findobj(axes_view_field,'Tag','DeformPoint')];%find all the deform point representations
4155end
4156for iobj=1:length(hother)
4157    if isequal(get(hother(iobj),'Type'),'rectangle')||isequal(get(hother(iobj),'Type'),'patch')
4158        set(hother(iobj),'EdgeColor','b')
4159        if isequal(get(hother(iobj),'FaceColor'),'m')
4160            set(hother(iobj),'FaceColor','b')
4161        end
4162    elseif isequal(get(hother(iobj),'Type'),'image')
4163        Acolor=get(hother(iobj),'CData');
4164        Acolor(:,:,1)=zeros(size(Acolor,1),size(Acolor,2));
4165        set(hother(iobj),'CData',Acolor);
4166    else
4167        set(hother(iobj),'Color','b')
4168    end
4169    set(hother(iobj),'Selected','off')
4170end
4171if ishandle(DisplayHandle)
4172    linetype=get(DisplayHandle,'Type');
4173    if isequal(linetype,'line')
4174        set(DisplayHandle,'Color','m'); %set the selected object to magenta color
4175    elseif isequal(linetype,'rectangle')
4176        set(DisplayHandle,'EdgeColor','m'); %set the selected object to magenta color
4177    elseif isequal(linetype,'patch')
4178        set(DisplayHandle,'FaceColor','m'); %set the selected object to magenta color
4179    end
4180    SubObjectData=get(DisplayHandle,'UserData');
4181    if isfield(SubObjectData,'SubObject') & ishandle(SubObjectData.SubObject)
4182        for iobj=1:length(SubObjectData.SubObject)
4183            hsub=SubObjectData.SubObject(iobj);
4184            if isequal(get(hsub,'Type'),'rectangle')
4185                set(hsub,'EdgeColor','m'); %set the selected object to magenta color
4186            elseif isequal(get(hsub,'Type'),'image')
4187                Acolor=get(hsub,'CData');
4188                Acolor(:,:,1)=Acolor(:,:,3);
4189                set(hsub,'CData',Acolor);
4190            else
4191                set(hsub,'Color','m')
4192            end
4193        end
4194    end
4195    if isfield(SubObjectData,'DeformPoint') & ishandle(SubObjectData.DeformPoint)
4196        set(SubObjectData.DeformPoint,'Color','m')
4197    end
4198end
4199
4200%-------------------------------------------------------------------
4201% --- Executes on selection change in CheckEditObject.
4202function CheckEditObject_Callback(hObject, eventdata, handles)
4203%-------------------------------------------------------------------
4204hset_object=findobj(allchild(0),'Tag','set_object');
4205if get(handles.CheckEditObject,'Value')
4206    %suppress the other options
4207    set(handles.CheckZoom,'Value',0)
4208    CheckZoom_Callback(hObject, eventdata, handles)
4209    hgeometry_calib=findobj(allchild(0),'tag','geometry_calib');
4210    if ishandle(hgeometry_calib)
4211        hhgeometry_calib=guidata(hgeometry_calib);
4212        set(hhgeometry_calib.CheckEnableMouse,'Value',0)% desactivate mouse action in geometry_calib
4213        set(hhgeometry_calib.CheckEnableMouse,'BackgroundColor',[0.7 0.7 0.7])
4214    end
4215    set(handles.CheckViewObject,'value',1)
4216    CheckViewObject_Callback(hObject, eventdata, handles)
4217else % desactivate object edit mode
4218    if ~isempty(hset_object)% open the
4219        set(get(hset_object,'children'),'Enable','off')
4220        hSAVE=findobj(hset_object,'Tag','SAVE');
4221        set(hSAVE,'Enable','on')
4222    end
4223end
4224
4225
4226%------------------------------------------------------------------------
4227% --- Executes on button press in CheckViewObject.
4228function CheckViewObject_Callback(hObject, eventdata, handles)
4229%------------------------------------------------------------------------
4230check_view=get(handles.CheckViewObject,'Value');
4231
4232if check_view %activate set_object   
4233    IndexObj=get(handles.ListObject,'Value');
4234    list_object=get(handles.ListObject,'String');
4235    UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4236    UvData.ProjObject{IndexObj}.Name=list_object{IndexObj};
4237    if numel(UvData.ProjObject)<IndexObj;% error in UvData
4238        msgbox_uvmat('ERROR','invalid object list')
4239        return
4240    end
4241    ZBounds=0; % default
4242    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4243        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4244        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4245    end
4246    data=UvData.ProjObject{IndexObj};
4247    if ~isfield(data,'Type')% default plane
4248        data.Type='plane';
4249    end
4250    hset_object=set_object(data,[],ZBounds);
4251    hhset_object=guidata(hset_object);
4252    if get(handles.CheckEditObject,'Value')% edit mode
4253        set(get(hset_object,'children'),'Enable','on')
4254    else
4255        set(get(hset_object,'children'),'Enable','off')% deactivate the GUI except SAVE
4256        set(hhset_object.SAVE,'Enable','on')
4257    end
4258else
4259    hset_object=findobj(allchild(0),'tag','set_object');
4260    if ~isempty(hset_object)
4261        delete(hset_object)% delete existing version of set_object
4262    end
4263end
4264 
4265
4266%------------------------------------------------------------------------
4267% --- Executes on button press in CheckViewField.
4268function CheckViewField_Callback(hObject, eventdata, handles)
4269%------------------------------------------------------------------------
4270check_view=get(handles.CheckViewField,'Value');
4271
4272if check_view
4273    IndexObj=get(handles.ListObject,'Value');
4274    UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4275    if numel(UvData.ProjObject)<IndexObj(end);% error in UvData
4276        msgbox_uvmat('ERROR','invalid object list')
4277        return
4278    end
4279    ZBounds=0; % default
4280    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4281        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4282        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4283    end
4284    set(handles.ListObject,'Value',IndexObj);%restore ListObject selection after set_object deletion
4285    if ~isfield(UvData.ProjObject{IndexObj(1)},'Type')% default plane
4286        UvData.ProjObject{IndexObj(1)}.Type='plane';
4287    end
4288    list_object=get(handles.ListObject,'String');
4289    UvData.ProjObject{IndexObj(end)}.Name=list_object{IndexObj(end)};
4290   
4291    %% show the projection of the selected object on view_field
4292    ProjData= proj_field(UvData.Field,UvData.ProjObject{IndexObj});%project the current field on ObjectData
4293    hview_field=findobj(allchild(0),'tag','view_field');
4294    if isempty(hview_field)
4295        hview_field=view_field;
4296    end
4297    hhview_field=guidata(hview_field);
4298    [PlotType,PlotParam]=plot_field(ProjData,hhview_field.PlotAxes,read_GUI(hview_field));%read plotting parameters on the GUI view_field);
4299    errormsg=fill_GUI(PlotParam,hview_field);
4300    for list={'Scalar','Vectors'}
4301        if ~isfield(PlotParam,list{1})
4302            set(hhview_field.(list{1}),'Visible','off')
4303        end
4304    end
4305    %write_plot_param(hhview_field,PlotParam); %update the display of plotting parameters for the current object
4306    haxes=findobj(hview_field,'tag','axes3');
4307    pos=get(hview_field,'Position');
4308    if strcmp(get(haxes,'Visible'),'off')%sempty(PlotParam.Coordinates)% case of no plot display (pure text table)
4309        h_TableDisplay=findobj(hview_field,'tag','TableDisplay');
4310        pos_table=get(h_TableDisplay,'Position');
4311        set(hview_field,'Position',[pos(1)+pos(3)-pos_table(3) pos(2)+pos(4)-pos_table(4) pos_table(3) pos_table(4)])
4312    else
4313        Data=get(hview_field,'UserData');
4314%         set(hview_field,'Position',Data.GUISize)% restore the size of view_field for plots
4315    end
4316else
4317    hview_field=findobj(allchild(0),'tag','view_field');
4318    if ~isempty(hview_field)
4319        delete(hview_field)% delete existing version of set_object
4320    end
4321end
4322
4323
4324%------------------------------------------------------------------------
4325% --- Executes on button press in DeleteObject.
4326%------------------------------------------------------------------------
4327function DeleteObject_Callback(hObject, eventdata, handles)
4328
4329IndexObj=get(handles.ListObject,'Value');%projection object selected for view_field
4330IndexObj_1=get(handles.ListObject_1,'Value');%projection object selected for uvmat plot
4331if IndexObj>1 && ~isequal(IndexObj,IndexObj_1) % do not delete the object used for the uvmat plot
4332    delete_object(IndexObj)
4333end
4334
4335%'DeleteObject': delete a projection object, defined by its index in the Uvmat list or by its graphic handle
4336%------------------------------------------------------------------------
4337% function DeleteObject(hObject)
4338%
4339% INPUT:
4340% hObject: object index (if integer) or handle of the graphic object. If
4341%          hObject is a subobject, the parent object is detected and deleted.
4342
4343function delete_object(IndexObj)
4344
4345huvmat=findobj('tag','uvmat');%handles of the uvmat interface
4346UvData=get(huvmat,'UserData');
4347hlist_object=findobj(huvmat,'Tag','ListObject');%handles of the object list in the uvmat interface
4348list_str=get(hlist_object,'String');%objet list
4349if  ~isempty(UvData) && isfield(UvData, 'ProjObject') && length(UvData.ProjObject)>=IndexObj
4350    if isfield(UvData.ProjObject{IndexObj},'DisplayHandle') && isfield(UvData.ProjObject{IndexObj}.DisplayHandle,'uvmat')
4351        hdisplay=UvData.ProjObject{IndexObj}.DisplayHandle.uvmat;%handle of the object graphic representation in uvmat
4352        for iview=1:length(hdisplay)
4353            if ishandle(hdisplay(iview)) && ~isequal(hdisplay(iview),0)
4354                ObjectData=get(hdisplay(iview),'UserData');
4355                if isfield(ObjectData,'SubObject') & ishandle(ObjectData.SubObject)
4356                    delete(ObjectData.SubObject);% delete the graphic 'sub-objects (e.g. projection bounds)
4357                end
4358                check_suppress= isfield(ObjectData,'DeformPoint') & ishandle(ObjectData.DeformPoint)
4359                delete(ObjectData.DeformPoint(check_suppress));% delete the graphic deformation points
4360                delete(hdisplay(iview))% delete the main graphic representation of the object
4361            end
4362            ishandle(hdisplay(iview))
4363        end
4364        for iobj=IndexObj+1:length(UvData.ProjObject)
4365            hdisplay=UvData.ProjObject{iobj}.DisplayHandle.uvmat;
4366            for iview=1:length(hdisplay)
4367                if ishandle(hdisplay(iview)) && ~isequal(hdisplay(iview),0)
4368                    PlotData=get(hdisplay(iview),'UserData');
4369                    PlotData.IndexObj=iobj-1;
4370                    set(hdisplay(iview),'UserData',PlotData);
4371                end
4372            end
4373        end
4374    end
4375    UvData.ProjObject(IndexObj)=[];
4376    if ~isempty(list_str)
4377        list_str(IndexObj)=[];
4378    end
4379end
4380set(huvmat,'UserData',UvData);
4381set(hlist_object,'String',list_str)
4382set(hlist_object,'Value',length(list_str))
4383hlist_object_1=findobj(huvmat,'Tag','ListObject_1');%handles of the first object list in the uvmat interface
4384old_index=get(hlist_object_1,'Value');
4385set(hlist_object_1,'String',list_str)
4386if IndexObj<=old_index
4387    set(hlist_object_1,'Value',old_index-1)
4388end
4389
4390%------------------------------------------------------------------------
4391%------------------------------------------------------------------------
4392%  II - TOOLS FROM THE UPPER MENU BAR
4393%------------------------------------------------------------------------
4394%------------------------------------------------------------------------
4395
4396%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4397% Export  Menu Callbacks
4398%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4399%------------------------------------------------------------------------
4400% --- Executes on button press in Menu/Export/field in workspace.
4401function MenuExportField_Callback(hObject, eventdata, handles)
4402%------------------------------------------------------------------------
4403global Data_uvmat
4404Data_uvmat=get(handles.uvmat,'UserData');
4405evalin('base','global Data_uvmat')%make CurData global in the workspace
4406display('current field :')
4407evalin('base','Data_uvmat') %display CurData in the workspace
4408commandwindow; %brings the Matlab command window to the front
4409
4410%------------------------------------------------------------------------
4411% --- Executes on button press in Menu/Export/extract figure.
4412function MenuExportFigure_Callback(hObject, eventdata, handles)
4413%------------------------------------------------------------------------
4414% huvmat=get(handles.MenuExport,'parent');
4415hfig=figure;
4416copyobj(handles.PlotAxes,hfig);
4417map=colormap(handles.PlotAxes);
4418colormap(map);%transmit the current colormap to the zoom fig
4419colorbar
4420
4421% --------------------------------------------------------------------
4422function MenuExportAxis_Callback(hObject, eventdata, handles)
4423ListFig=findobj(allchild(0),'Type','figure');
4424nb_option=0;
4425menu={};
4426for ilist=1:numel(ListFig)
4427    FigName=get(ListFig(ilist),'name');
4428    if isempty(FigName)
4429        FigName=['figure ' num2str(ListFig(ilist))];
4430    end
4431    if ~strcmp(FigName,'uvmat')
4432        ListAxes=findobj(ListFig(ilist),'Type','axes');
4433        ListTags=get(ListAxes,'Tag');
4434        if ~isempty(ListTags) && ~isempty(find(~strcmp('Colorbar',ListTags), 1))
4435            ListAxes=ListAxes(~strcmp('Colorbar',ListTags));
4436            if numel(ListAxes)==1
4437                nb_option=nb_option+1;
4438                menu{nb_option}=FigName ;
4439                AxesHandle(nb_option)=ListAxes;
4440            else
4441                nb_axis=0;
4442                for iaxes=1:numel(ListAxes)
4443                    nb_axis=nb_axis+1;
4444                    nb_option=nb_option+1;
4445                    menu{nb_option}=[FigName '_' num2str(nb_axis)];
4446                    AxesHandle(nb_option)=ListAxes(nb_axis);
4447                end
4448            end
4449        end
4450    end
4451end
4452if isempty(menu)
4453    answer=msgbox_uvmat('INPUT_Y-N','no existing plotting axes available, create new figure?');
4454    if strcmp(answer,'Yes')
4455        hfig=figure;
4456        copyobj(handles.PlotAxes,hfig);
4457    else
4458        return
4459    end
4460    map=colormap(handles.PlotAxes);
4461    colormap(map);%transmit the current colormap to the zoom fig
4462    colorbar
4463else
4464    answer=msgbox_uvmat('INPUT_MENU','select a figure/axis on which the current uvmat plot will be exported',menu);
4465    if isempty(answer)
4466        return
4467    else
4468        axes(AxesHandle(answer))
4469        hold on
4470        hchild=get(handles.PlotAxes,'children');
4471        copyobj(hchild,gca);
4472    end
4473end
4474
4475
4476%------------------------------------------------------------------------
4477% --------------------------------------------------------------------
4478function MenuExportMovie_Callback(hObject, eventdata, handles)
4479% --------------------------------------------------------------------
4480set(handles.MenuExportMovie,'BusyAction','queue')% activate the button
4481huvmat=get(handles.run0,'parent');
4482UvData=get(huvmat,'UserData');
4483%[xx,xx,FileBase]=read_file_boxes(handles);
4484[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
4485FileBase=fullfile(RootPath,RootFile);
4486 %read the current input file name
4487prompt = {'movie file name';'frames per second';'frame resolution (*[512x384] pixels)';'axis position relative to the frame';'total frame number (starting from the current uvmat display)'};
4488dlg_title = 'select properties of the output avi movie';
4489num_lines= 1;
4490def     = {[FileBase '_out.avi'];'10';'1';'[0.03 0.05 0.95 0.92]';'10'};
4491answer = inputdlg(prompt,dlg_title,num_lines,def,'on');
4492aviname=answer{1};
4493fps=str2double(answer{2});
4494% check for existing file with output name aviname
4495if exist(aviname,'file')
4496    backup=aviname;
4497    testexist=2;
4498    while testexist==2
4499        backup=[backup '~'];
4500        testexist=exist(backup,'file');     
4501    end
4502    [success,message]=copyfile(aviname,backup);%make backup of the existing file
4503    if isequal(success,1)
4504        delete(aviname)%delete existing file
4505    else
4506        msgbox_uvmat('ERROR',message)
4507        return
4508    end
4509end
4510%create avi open
4511aviobj=avifile(aviname,'Compression','None','fps',fps);
4512
4513%display first view for tests
4514newfig=figure;
4515newaxes=copyobj(handles.PlotAxes,newfig);%new plotting axes in the new figure
4516set(newaxes,'Tag','movieaxes')
4517nbpix=[512 384]*str2double(answer{3});
4518set(gcf,'Position',[1 1 nbpix])% resolution XVGA
4519set(newaxes,'Position',eval(answer{4}));
4520map=colormap(handles.PlotAxes);
4521colormap(map);%transmit the current colormap to the zoom fig
4522msgbox_uvmat('INPUT_Y-N',{['adjust figure ' num2str(newfig) ' with its matlab edit menu '] ;...
4523        ['then press OK to get the avi movie as a copy of figure ' num2str(newfig) ' display']});
4524UvData.plotaxes=newaxes;% the axis in the new figure becomes the current main plotting axes
4525set(huvmat,'UserData',UvData);
4526increment=str2num(get(handles.num_IndexIncrement,'String')); %get the field increment d
4527set(handles.STOP,'Visible','on')
4528set(handles.speed,'Visible','on')
4529set(handles.speed_txt,'Visible','on')
4530set(handles.Movie,'BusyAction','queue')
4531
4532%imin=str2double(get(handles.i1,'String'));
4533imax=str2double(answer{5});
4534% if isfield(UvData,'Time')
4535htitle=get(newaxes,'Title');
4536xlim=get(newaxes,'XLim');
4537ylim=get(newaxes,'YLim');
4538set(htitle,'Position',[xlim(2)+0.07*(xlim(2)-xlim(1)) ylim(2)-0.05*(ylim(2)-ylim(1)) 0])
4539time_str=get(handles.TimeValue,'String');
4540set(htitle,'String',['t=' time_str])
4541set(handles.speed,'Value',1)
4542for i=1:imax
4543    if get(handles.speed,'Value')~=0 && isequal(get(handles.MenuExportMovie,'BusyAction'),'queue') % enable STOP command
4544            runpm(hObject,eventdata,handles,increment)% run plus
4545            drawnow
4546            time_str=get(handles.TimeValue,'String');
4547            if ishandle(htitle)
4548             set(htitle,'String',['t=' time_str])
4549            end
4550            mov=getframe(newfig);
4551            aviobj=addframe(aviobj,mov);
4552    end
4553end
4554aviobj=close(aviobj);
4555UvData=rmfield(UvData,'plotaxes');
4556set(huvmat,'UserData',UvData);
4557msgbox_uvmat('CONFIRMATION',{['movie ' aviname ' created '];['with ' num2str(imax) ' frames']})
4558
4559
4560%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4561% Projection Objects Menu Callbacks
4562%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4563
4564% -----------------------------------------------------------------------
4565function Menupoints_Callback(hObject, eventdata, handles)
4566%------------------------------------------------------------------------
4567data.Type='points';
4568data.ProjMode='projection';%default
4569data.ProjModeMenu={};% do not restrict ProjMode menus
4570create_object(data,handles)
4571
4572% -----------------------------------------------------------------------
4573% --- Callback of the Menu command line
4574%------------------------------------------------------------------------
4575function Menuline_Callback(hObject, eventdata, handles)
4576%------------------------------------------------------------------------
4577data.Type='line';
4578data.ProjMode='projection';%default
4579data.ProjModeMenu={};% do not restrict ProjMode menus
4580create_object(data,handles)
4581
4582% -----------------------------------------------------------------------
4583% --- Callback of the Menu command line_x
4584%------------------------------------------------------------------------
4585function Menuline_x_Callback(hObject, eventdata, handles)
4586
4587data.Type='line_x';
4588data.ProjMode='projection';%default
4589data.ProjModeMenu={};% do not restrict ProjMode menus
4590create_object(data,handles)
4591
4592% -----------------------------------------------------------------------
4593% --- Callback of the Menu command line_y
4594% -----------------------------------------------------------------------
4595function Menuline_y_Callback(hObject, eventdata, handles)
4596
4597data.Type='line_y';
4598data.ProjMode='projection';%default
4599data.ProjModeMenu={};% do not restrict ProjMode menus
4600create_object(data,handles)
4601
4602%------------------------------------------------------------------------
4603function Menupolyline_Callback(hObject, eventdata, handles)
4604%------------------------------------------------------------------------
4605data.Type='polyline';
4606data.ProjMode='projection';%default
4607data.ProjModeMenu={};% do not restrict ProjMode menus
4608create_object(data,handles)
4609
4610%------------------------------------------------------------------------
4611function Menupolygon_Callback(hObject, eventdata, handles)
4612%------------------------------------------------------------------------
4613data.Type='polygon';
4614data.ProjMode='inside';%default
4615data.ProjModeMenu={};% do not restrict ProjMode menus
4616create_object(data,handles)
4617
4618%------------------------------------------------------------------------
4619function Menurectangle_Callback(hObject, eventdata, handles)
4620%------------------------------------------------------------------------
4621data.Type='rectangle';
4622data.ProjMode='inside';%default
4623data.ProjModeMenu={};% do not restrict ProjMode menus
4624create_object(data,handles)
4625
4626%------------------------------------------------------------------------
4627function Menuellipse_Callback(hObject, eventdata, handles)
4628%------------------------------------------------------------------------
4629data.Type='ellipse';
4630data.ProjMode='inside';%default
4631data.ProjModeMenu={};% do not restrict ProjMode menus
4632create_object(data,handles)
4633
4634%------------------------------------------------------------------------
4635function MenuMaskObject_Callback(hObject, eventdata, handles)
4636%------------------------------------------------------------------------
4637data.Type='polygon';
4638data.TypeMenu={'polygon'};
4639data.ProjMode='mask_inside';%default
4640data.ProjModeMenu={'mask_inside';'mask_outside'};
4641create_object(data,handles)
4642
4643%------------------------------------------------------------------------
4644function Menuplane_Callback(hObject, eventdata, handles)
4645%------------------------------------------------------------------------
4646data.Type='plane';
4647data.ProjMode='projection';%default
4648data.ProjModeMenu={};% do not restrict ProjMode menus
4649create_object(data,handles)
4650
4651%------------------------------------------------------------------------
4652function Menuvolume_Callback(hObject, eventdata, handles)
4653%------------------------------------------------------------------------
4654data.Type='volume';
4655data.ProjMode='interp_lin';%default
4656data.ProjModeMenu={};
4657% set(handles.create,'Visible','on')
4658% set(handles.create,'Value',1)
4659% VOLUME_Callback(hObject,eventdata,handles)data.ProjModeMenu={};
4660create_object(data,handles)
4661
4662%------------------------------------------------------------------------
4663% --- generic function used for the creation of a projection object
4664function create_object(data,handles)
4665%------------------------------------------------------------------------
4666%% desactivate concurrent tools
4667hgeometry_calib=findobj(allchild(0),'tag','geometry_calib');% search the GUI geometric calibration
4668if ishandle(hgeometry_calib)
4669    hhgeometry_calib=guidata(hgeometry_calib);
4670    set(hhgeometry_calib.CheckEnableMouse,'Value',0)% desactivate mouse action in geometry_calib
4671    set(hhgeometry_calib.CheckEnableMouse,'BackgroundColor',[0.7 0.7 0.7])
4672end
4673set(handles.CheckEditObject,'Value',0)  %desactivate the object edit mode
4674CheckEditObject_Callback([],[],handles)
4675set(handles.CheckViewObject,'Value',0) % desactivate view_object (new object created)
4676set(handles.CheckZoomFig,'Value',0) %desactivate zoom sub fig
4677set(handles.CheckZoom,'Value',0)    %desactivate the zoom action
4678if ishandle(handles.UVMAT_title)
4679    delete(handles.UVMAT_title)     %delete the initial display of uvmat if no field has been entered yet
4680end
4681
4682%% initiate the new projection object
4683UvData=get(handles.uvmat,'UserData');
4684data.Name=data.Type;% default name=type
4685data.Coord=[0 0]; %default
4686check_plot=0;
4687if isfield(UvData,'Field')
4688    Field=UvData.Field;
4689    if isfield(Field,'NbDim')&& isequal(Field.NbDim,3)
4690         data.Coord=[0 0 0]; %default
4691    end
4692    if isfield(Field,'CoordUnit')
4693        data.CoordUnit=Field.CoordUnit;
4694    end
4695    if isfield(UvData.Field,'CoordMesh')&&~isempty(UvData.Field.CoordMesh)
4696        data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
4697        switch data.Type
4698            case {'line','polyline','points'}
4699                data.RangeY=UvData.Field.CoordMesh;
4700            case 'line_x'
4701                check_plot=1; %plot the line directly when set_object is opened
4702                data.Type='line';
4703                data.RangeX=UvData.Field.XMin ;
4704                data.RangeY=UvData.Field.CoordMesh;
4705                data.Coord=[UvData.Field.XMin (UvData.Field.YMin +UvData.Field.YMax)/2;...
4706                           UvData.Field.XMax (UvData.Field.YMin +UvData.Field.YMax)/2];% put line at the middle of the y axis
4707            case 'line_y'
4708                check_plot=1; %plot the line directly when set_object is opened
4709                data.Type='line';
4710                data.RangeX=UvData.Field.YMin ;
4711                data.RangeY=UvData.Field.CoordMesh;
4712                data.Coord=[(UvData.Field.XMin+UvData.Field.XMax)/2 UvData.Field.YMin;...
4713                            (UvData.Field.XMin +UvData.Field.XMax)/2 UvData.Field.YMax];% put line at the middle of the y axis
4714            case {'rectangle','ellipse'}
4715                data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
4716                data.RangeX=UvData.Field.CoordMesh;
4717                data.RangeY=UvData.Field.CoordMesh;
4718            otherwise
4719                data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
4720        end
4721        data.DX=UvData.Field.CoordMesh;
4722        data.DY=UvData.Field.CoordMesh;
4723    end
4724end
4725
4726hset_object=set_object(data,handles);% call the GUI set_object
4727hchild=get(hset_object,'children');
4728set(hchild,'enable','on')
4729set(handles.DeleteObject,'Visible','on')% make the object delete button visible
4730if check_plot
4731    hhset_object=guidata(hset_object);
4732    set_object('REFRESH_Callback',1,[],hhset_object);% call the GUI set_object
4733end
4734
4735%------------------------------------------------------------------------
4736function MenuBrowseObject_Callback(hObject, eventdata, handles)
4737%------------------------------------------------------------------------
4738%get the object file
4739fileinput=uigetfile_uvmat('pick an xml object file:',get(handles.RootPath,'String'),'.xml');
4740if ~isempty(fileinput)
4741    %read the file
4742    [data,heading]=xml2struct(fileinput);
4743    if ~strcmp(heading,'ProjObject')
4744        msgbox_uvmat('WARNING','The xml file does not have the heading ProjObject for projection objects')
4745    end
4746    ListObject=get(handles.ListObject,'String');
4747    ListObject=[ListObject;{data.Name}];
4748    IndexObj=length(ListObject);
4749    UvData=get(handles.uvmat,'UserData');
4750    UvData.ProjObject{IndexObj}=[]; %create a new empty object
4751    UvData.ProjObject{IndexObj}.DisplayHandle.uvmat=[]; %no plot handle before plot_field operation
4752    UvData.ProjObject{IndexObj}.DisplayHandle.view_field=[]; %no plot handle before plot_field operation
4753    set(handles.uvmat,'UserData',UvData)
4754    set(handles.CheckViewObject,'Value',1)
4755    set(handles.CheckViewField,'Value',1)
4756    hset_object=set_object(data);% call the set_object interface
4757    hhset_object=guidata(hset_object);
4758    set_object('REFRESH_Callback',hObject,eventdata,hhset_object);% plot projection
4759    set(handles.CheckEditObject,'Value',0); %suppress the object edit mode
4760    CheckEditObject_Callback([],[],handles)
4761    set(handles.DeleteObject,'Visible','on')
4762end
4763
4764%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4765% MenuTools Callbacks
4766%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4767%------------------------------------------------------------------------
4768function MenuCalib_Callback(hObject, eventdata, handles)
4769%------------------------------------------------------------------------
4770
4771UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4772
4773%suppress competing options
4774set(handles.CheckZoom,'Value',0)
4775set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
4776set(handles.ListObject,'Value',1)     
4777% initiate display of GUI geometry_calib
4778data=[]; %default
4779if isfield(UvData,'CoordType')
4780    data.CoordType=UvData.CoordType;
4781end
4782[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
4783FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];
4784set(handles.view_xml,'Backgroundcolor',[1 1 0])%indicate the reading of the current xml file by geometry_calib
4785% pos_uvmat=get(handles.uvmat,'Position');
4786% pos_cal(1)=pos_uvmat(1)+UvData.OpenParam.PosGeometryCalib(1)*pos_uvmat(3);
4787% pos_cal(2)=pos_uvmat(2)+UvData.OpenParam.PosGeometryCalib(2)*pos_uvmat(4);
4788% pos_cal(3:4)=UvData.OpenParam.PosGeometryCalib(3:4).* pos_uvmat(3:4);
4789geometry_calib(FileName);% call the geometry_calib interface   
4790set(handles.view_xml,'Backgroundcolor',[1 1 1])%indicate the end of reading of the current xml file by geometry_calib
4791set(handles.MenuCalib,'checked','on')% indicate that MenuCalib is activated, test used by mouse action
4792
4793
4794%-----------------------------------------------------------------------
4795function MenuLIFCalib_Callback(hObject, eventdata, handles)
4796%------------------------------------------------------------------------
4797%% read UvData properties stored on the uvmat interface
4798UvData=get(handles.uvmat,'UserData');
4799if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
4800    XmlData=UvData.XmlData{1};
4801else
4802    msgbox_uvmat('ERROR','geometric calibration needed: use Tools/geometric calibration in the menu bar');
4803    return
4804end
4805
4806%% read lines currently drawn
4807ListObj=UvData.ProjObject;
4808select=zeros(1,numel(ListObj));
4809for iobj=1:numel(ListObj);
4810    if isfield(ListObj{iobj},'Type') && strcmp(ListObj{iobj}.Type,'line')
4811        select(iobj)=1;
4812    end
4813end
4814val=find(select);
4815if numel(val)<2
4816    msgbox_uvmat('ERROR','light rays must be defined by at least two lines created by Projection object/line in the menu bar');
4817    return
4818else
4819    set(handles.ListObject,'Value',val);% show the selected lines on the list
4820    ObjectData=UvData.ProjObject(val);
4821    for iobj=1:length(ObjectData)
4822%         if isfield(ObjectData{iobj},'Coord')
4823            xA(iobj)=ObjectData{iobj}.Coord(1,1);
4824            yA(iobj)=ObjectData{iobj}.Coord(1,2);
4825            xB(iobj)=ObjectData{iobj}.Coord(2,1);
4826            yB(iobj)=ObjectData{iobj}.Coord(2,2);
4827%         end
4828    end
4829end
4830
4831%% find the origin as intersection of the two first lines (see http://www.ahristov.com/tutorial/geometry-games/intersection-lines.html )
4832x1=xA(1);x2=xB(1);
4833x3=xA(2);x4=xB(2);
4834y1=yA(1);y2=yB(1);
4835y3=yA(2);y4=yB(2);
4836D = (x1-x2)*(y3-y4) -(y1-y2)*(x3-x4);
4837if D==0
4838    msgbox_uvmat('ERROR','the two lines are parallel');
4839    return
4840end
4841x0=((x3-x4)*(x1*y2-y1*x2)-(x1-x2)*(x3*y4-y3*x4))/D;
4842y0=((y3-y4)*(x1*y2-y1*x2)-(y1-y2)*(x3*y4-y3*x4))/D;
4843XmlData.Illumination.Origin=[x0 y0];
4844XmlData.PolarCentre=[x0 y0];
4845
4846%% display the current image in polar coordinates with origin at the  illumination source
4847currentdir=pwd; 
4848uvmatpath=fileparts(which('uvmat'));
4849cd(fullfile(uvmatpath,'transform_field'));
4850phys_polar=str2func('phys_polar');
4851cd(currentdir)
4852DataOut=phys_polar(UvData.Field,XmlData);
4853view_field(DataOut);
4854
4855%% use the third line for reference luminosity
4856if numel(val)==3
4857    x_ref=linspace(ObjectData{3}.Coord(1,1),ObjectData{3}.Coord(2,1),10);
4858    y_ref=linspace(ObjectData{3}.Coord(1,2),ObjectData{3}.Coord(2,2),10);
4859    x_ref=x_ref-x0;
4860    y_ref=y_ref-y0;
4861    [theta_ref,r_ref] = cart2pol(x_ref,y_ref);%theta_ref  and r_ref are the polar coordinates of the points on the line
4862    theta_ref=theta_ref*180/pi;
4863    figure
4864    plot(theta_ref,r_ref)
4865    azimuth_ima=linspace(DataOut.AY(1),DataOut.AY(2),size(DataOut.A,1));%profile of x index on the transformed image
4866    dist_source = interp1(theta_ref,r_ref,azimuth_ima);
4867    dist_source_pixel=round(size(DataOut.A,2)*(dist_source-DataOut.AX(1))/(DataOut.AX(2)-DataOut.AX(1)));
4868    line_nan= isnan(dist_source_pixel);
4869    dist_source_pixel(line_nan)=1;
4870    width=20; %number of pixels used for reference
4871    DataOut.A=double(DataOut.A);
4872    Anorm=zeros(size(DataOut.A));
4873    Aval=mean(mean(DataOut.A));
4874    for iline=1:size(DataOut.A,1)
4875        lum(iline)=mean(DataOut.A(iline,dist_source_pixel(iline):dist_source_pixel(iline)+width));
4876        Anorm(iline,:)=uint16(Aval*DataOut.A(iline,:)/lum(iline));
4877    end
4878    lum(line_nan)=NaN;
4879    figure
4880    plot(1:size(DataOut.A,1),lum)
4881end
4882ImaName=regexprep([get(handles.RootFile,'String') get(handles.FileIndex,'String')],'//','');
4883NewImageName=fullfile(get(handles.RootPath,'String'),'polar',[ImaName get(handles.FileExt,'String')]);
4884imwrite(Anorm,NewImageName,'BitDepth',16)
4885
4886%% record the origin in the xml file
4887XmlFileName=find_imadoc(get(handles.RootPath,'String'),get(handles.SubDir,'String'),get(handles.RootFile,'String'),get(handles.FileExt,'String'));
4888answer=msgbox_uvmat('INPUT_Y-N','save the illumination origin in the current xml file?');
4889if strcmp(answer,'Yes')
4890    t=xmltree(XmlFileName); %read the file
4891    title=get(t,1,'name');
4892    if ~strcmp(title,'ImaDoc')
4893        msgbox_uvmat('ERROR','wrong xml file');
4894        return
4895    end
4896    % backup the output file if it already exist, and read it
4897    backupfile=XmlFileName;
4898    testexist=2;
4899    while testexist==2
4900        backupfile=[backupfile '~'];
4901        testexist=exist(backupfile,'file');
4902    end
4903    [success,message]=copyfile(XmlFileName,backupfile);%make backup
4904    if success~=1
4905        errormsg=['errror in xml file backup: ' message];
4906        return
4907    end
4908    uid_illumination=find(t,'ImaDoc/Illumination');
4909    if isempty(uid_illumination)  %if GeometryCalib does not already exists, create it
4910        [t,uid_illumination]=add(t,1,'element','Illumination');
4911    end
4912    uid_origin=find(t,'ImaDoc/Illumination/Origin');
4913    if ~isempty(uid_origin)  %if GeometryCalib does not already exists, create it
4914         t=delete(t,uid_origin);
4915    end
4916    % save the illumination origin
4917    t=struct2xml(XmlData.Illumination,t,uid_illumination);
4918    save(t,XmlFileName);
4919end
4920   
4921
4922
4923%------------------------------------------------------------------------
4924function MenuMask_Callback(hObject, eventdata, handles)
4925%------------------------------------------------------------------------
4926UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4927ListObj=UvData.ProjObject;
4928select=zeros(1,numel(ListObj));
4929for iobj=1:numel(ListObj);
4930    if strcmp(ListObj{iobj}.ProjMode,'mask_inside')||strcmp(ListObj{iobj}.ProjMode,'mask_outside')
4931        select(iobj)=1;
4932    end
4933end
4934val=find(select);
4935if isempty(val)
4936    msgbox_uvmat('ERROR','polygons must be first created by Projection object/mask polygon in the menu bar');
4937    return
4938else
4939    set(handles.ListObject,'Value',val);
4940    flag=1;
4941    if ~isfield(UvData.Field,'A')
4942            msgbox_uvmat('ERROR','an image needs to be opened to set the mask size');
4943    return
4944    end
4945    npx=size(UvData.Field.A,2);
4946    npy=size(UvData.Field.A,1);
4947    xi=0.5:npx-0.5;
4948    yi=0.5:npy-0.5;
4949    [Xi,Yi]=meshgrid(xi,yi);
4950        for iobj=1:length(UvData.ProjObject)
4951            ObjectData=UvData.ProjObject{iobj};
4952            if isfield(ObjectData,'ProjMode') &&(isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside'));
4953                flagobj=1;
4954                testphys=0; %coordinates in pixels by default
4955                if isfield(ObjectData,'CoordUnit') && ~isequal(ObjectData.CoordUnit,'pixel')
4956                    if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
4957                        Calib=UvData.XmlData{1}.GeometryCalib;
4958                        testphys=1;
4959                    end
4960                end
4961                if isfield(ObjectData,'Coord')&& isfield(ObjectData,'Type')
4962                    if isequal(ObjectData.Type,'polygon')
4963                        X=ObjectData.Coord(:,1);
4964                        Y=ObjectData.Coord(:,2);
4965                        if testphys
4966                            pos=[X Y zeros(size(X))];
4967                            if isfield(Calib,'SliceCoord') && length(Calib.SliceCoord)>=3
4968                                if isfield(Calib,'SliceAngle')&&~isequal(Calib.SliceAngle,[0 0 0])
4969                                    om=norm(Calib.SliceAngle);%norm of rotation angle in radians
4970                                    OmAxis=Calib.SliceAngle/om; %unit vector marking the rotation axis
4971                                    cos_om=cos(pi*om/180);
4972                                    sin_om=sin(pi*om/180);
4973                                    pos=cos_om*pos+sin_om*cross(OmAxis,pos)+(1-cos_om)*(OmAxis*pos')*OmAxis;
4974                                end
4975                                pos(:,1)=pos(:,1)+Calib.SliceCoord(1);
4976                                pos(:,2)=pos(:,2)+Calib.SliceCoord(2);
4977                                pos(:,3)=pos(:,3)+Calib.SliceCoord(3);
4978                            end                           
4979                            [X,Y]=px_XYZ(Calib,pos(:,1),pos(:,2),pos(:,3));
4980                        end
4981                        flagobj=~inpolygon(Xi,Yi,X',Y');%=0 inside the polygon, 1 outside
4982                    elseif isequal(ObjectData.Type,'ellipse')
4983                        if testphys
4984                            %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
4985                        end
4986                        RangeX=max(ObjectData.RangeX);
4987                        RangeY=max(ObjectData.RangeY);
4988                        X2Max=RangeX*RangeX;
4989                        Y2Max=RangeY*RangeY;
4990                        distX=(Xi-ObjectData.Coord(1,1));
4991                        distY=(Yi-ObjectData.Coord(1,2));
4992                        flagobj=(distX.*distX/X2Max+distY.*distY/Y2Max)>1;
4993                    elseif isequal(ObjectData.Type,'rectangle')
4994                        if testphys
4995                            %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
4996                        end
4997                        distX=abs(Xi-ObjectData.Coord(1,1));
4998                        distY=abs(Yi-ObjectData.Coord(1,2));
4999                        flagobj=distX>max(ObjectData.RangeX) | distY>max(ObjectData.RangeY);
5000                    end
5001                    if isequal(ObjectData.ProjMode,'mask_outside')
5002                        flagobj=~flagobj;
5003                    end
5004                    flag=flag & flagobj;
5005                end
5006            end
5007        end
5008%     end
5009    %mask name
5010    RootPath=get(handles.RootPath,'String');
5011    SubDir=get(handles.SubDir,'String');
5012    RootFile=get(handles.RootFile,'String');
5013    if ~isempty(RootFile)&&(isequal(RootFile(1),'/')|| isequal(RootFile(1),'\'))
5014        RootFile(1)=[];
5015    end
5016    list=get(handles.masklevel,'String');
5017    masknumber=num2str(length(list));
5018    maskindex=get(handles.masklevel,'Value');
5019   % mask_name=fullfile_uvmat(RootPath,'',[RootFile '_' masknumber 'mask'],'.png','_1',maskindex);
5020    mask_name=fullfile_uvmat(RootPath,[SubDir '.mask'],'mask','.png','_1',maskindex);
5021    imflag=uint8(255*(0.392+0.608*flag));% =100 for flag=0 (vectors not computed when 20<imflag<200)
5022    imflag=flipdim(imflag,1);
5023
5024    %display the mask
5025    hfigmask=figure;
5026    set(hfigmask,'Name','mask image')
5027    vec=linspace(0,1,256);%define a linear greyscale colormap
5028    map=[vec' vec' vec'];
5029    colormap(map)
5030    image(imflag);
5031    answer=msgbox_uvmat('INPUT_TXT','mask file name:', mask_name);
5032    if ~strcmp(answer,'Cancel')
5033        mask_dir=fileparts(answer);
5034        if ~exist(mask_dir,'dir')
5035            [xx,msg1]=mkdir(mask_dir);
5036            if ~strcmp(msg1,'')
5037                errormsg=['cannot create ' mask_dir ': ' msg1];%error message for directory creation
5038                return
5039            end
5040        end
5041        imwrite(imflag,answer,'BitDepth',8);
5042    end
5043    set(handles.ListObject,'Value',1)
5044end
5045
5046%------------------------------------------------------------------------
5047%-- open the GUI set_grid.fig to create grid
5048function MenuGrid_Callback(hObject, eventdata, handles)
5049%------------------------------------------------------------------------
5050%suppress the other options if grid is chosen
5051set(handles.edit_vect,'Value',0)
5052edit_vect_Callback(hObject, eventdata, handles)
5053% set(handles.CheckEditObject,'BackgroundColor',[0.7 0.7 0.7])
5054set(handles.ListObject,'Value',1)     
5055
5056%prepare display of the set_grid GUI
5057[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
5058FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];
5059UvData=get(handles.uvmat,'UserData');
5060% CoordList=get(handles.TransformName,'String');
5061% val=get(handles.TransformName,'Value');
5062set_grid(FileName,UvData.Field);% call the set_object interface
5063
5064
5065%------------------------------------------------------------------------
5066function MenuRuler_Callback(hObject, eventdata, handles)
5067%------------------------------------------------------------------------
5068set(handles.CheckZoom,'Value',0)
5069CheckZoom_Callback(handles.uvmat, [], handles)
5070set(handles.MenuRuler,'checked','on')
5071UvData=get(handles.uvmat,'UserData');
5072UvData.MouseAction='ruler';
5073set(handles.uvmat,'UserData',UvData);
5074
5075%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5076% MenuRun Callbacks
5077%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5078
5079%------------------------------------------------------------------------
5080% open the GUI 'series'
5081function MenuSeries_Callback(hObject, eventdata, handles)
5082%------------------------------------------------------------------------
5083Param=read_param(handles);
5084series(Param); %run the series interface
5085
5086% --------------------------------------------------------------------
5087function MenuPIV_Callback(hObject, eventdata, handles)
5088    Param=read_param(handles);
5089%     Param.ActionName='civ_series';
5090hseries=series(Param);
5091hhseries=guidata(hseries);
5092ActionMenu=get(hhseries.ActionName,'String');
5093index_action=find(strcmp('civ_series',ActionMenu));
5094set(hhseries.ActionName,'Value',index_action);
5095series('ActionName_Callback',hObject,eventdata,hhseries); %file input with xml reading  in uvmat, show the image in phys coordinates
5096
5097
5098%------------------------------------------------------------------------
5099% -- open the GUI civ.fig for PIV
5100function MenuCIVx_Callback(hObject, eventdata, handles)
5101%------------------------------------------------------------------------
5102 [RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
5103 FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];
5104civ(FileName);% interface de civ(not in the uvmat file)
5105
5106function Param=read_param(handles)
5107   
5108[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
5109Param.FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];%first input file name
5110if isequal(get(handles.SubField,'Value'),1)
5111    [RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
5112    FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];
5113    if ~isequal(FileName_1,Param.FileName)
5114        Param.FileName_1=FileName_1;%second input file name if relevant
5115    end
5116end
5117Param.NomType=get(handles.NomType,'String');
5118Param.NomType_1=get(handles.NomType_1,'String');
5119Param.CheckFixPair=get(handles.CheckFixPair,'Value');
5120UvData=get(handles.uvmat,'UserData');
5121if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'Time')
5122    Param.Time=UvData.XmlData{1}.Time;
5123end
5124if isequal(get(handles.scan_i,'Value'),1)
5125    Param.incr_i=str2num(get(handles.num_IndexIncrement,'String'));
5126elseif isequal(get(handles.scan_j,'Value'),1)
5127    Param.incr_j=str2num(get(handles.num_IndexIncrement,'String'));
5128end
5129
5130%% transfer fields and coordinate names
5131Param.list_fields=get(handles.FieldName,'String');% list menu fields
5132FieldName=Param.list_fields{get(handles.FieldName,'Value')};
5133ind_image=find(strcmp('image',Param.list_fields));
5134if ~isempty(ind_image) && numel(Param.list_fields)>1
5135    Param.list_fields(ind_image)=[]; %suppress  'image' option
5136end
5137Param.index_fields=find(strcmp(FieldName,Param.list_fields));% selected string index
5138Param.list_fields_1=get(handles.FieldName_1,'String');% list menu fields
5139if ischar(Param.list_fields_1),Param.list_fields_1={Param.list_fields_1};end
5140FieldName_1=Param.list_fields_1{get(handles.FieldName_1,'Value')};
5141ind_image=find(strcmp('image',Param.list_fields_1));
5142if ~isempty(ind_image) && numel(Param.list_fields_1)>1
5143    Param.list_fields_1(ind_image)=[]; %suppress  'image' option
5144end
5145Param.index_fields_1=find(strcmp(FieldName_1,Param.list_fields_1));% selected string index
5146TransformList=get(handles.TransformName,'String');
5147Param.TransformName=TransformList{get(handles.TransformName,'Value')};
5148Param.Coord_x_str=get(handles.Coord_x,'String');
5149Param.Coord_x_val=get(handles.Coord_x,'Value');
5150Param.Coord_y_str=get(handles.Coord_y,'Data');
5151
5152% --------------------------------------------------------------------
5153function MenuHelp_Callback(hObject, eventdata, handles)
5154% --------------------------------------------------------------------
5155web('http://servforge.legi.grenoble-inp.fr/projects/soft-uvmat/wiki/UvmatHelp')
5156
5157% path_to_uvmat=which ('uvmat');% check the path of uvmat
5158% pathelp=fileparts(path_to_uvmat);
5159% helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
5160% 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')
5161% else
5162%     addpath (fullfile(pathelp,'uvmat_doc'))
5163%     web(helpfile);
5164% end
5165
5166% --- Executes on selection change in Coord_y.
5167function Coord_y_Callback(hObject, eventdata, handles)
5168
5169% --- Executes on selection change in Coord_x.
5170function Coord_x_Callback(hObject, eventdata, handles)
5171
5172
5173% --- Executes on button press in CheckColorBar.
5174function CheckColorBar_Callback(hObject, eventdata, handles)
5175
5176
5177
5178function TransformPath_Callback(hObject, eventdata, handles)
5179% hObject    handle to TransformPath (see GCBO)
5180% eventdata  reserved - to be defined in a future version of MATLAB
5181% handles    structure with handles and user data (see GUIDATA)
5182
5183% Hints: get(hObject,'String') returns contents of TransformPath as text
5184%        str2double(get(hObject,'String')) returns contents of TransformPath as a double
5185
5186
5187%TODO: use to modify fill_GUI
5188%'write_plot_param': update the plotting parameters on the uvmat or view_field interface after a plotting operation
5189function write_plot_param(handles,PlotParam)
5190%% coordinates
5191if isempty(PlotParam.Coordinates)
5192    set(handles.Coordinates,'Visible','off')
5193    set(handles.PlotAxes,'Visible','off')
5194    set(handles.text_display,'Visible','off')
5195    set(handles.TableDisplay,'Visible','on')
5196else
5197    set(handles.Coordinates,'Visible','on')
5198    set(handles.PlotAxes,'Visible','on')
5199    set(handles.text_display,'Visible','on')
5200    if isfield(handles,'TableDisplay')
5201    set(handles.TableDisplay,'Visible','off')
5202    end
5203    Coordinates=PlotParam.Coordinates;
5204    if isfield(Coordinates,'CheckFixAspectRatio')
5205        if Coordinates.CheckFixAspectRatio
5206            set(handles.CheckFixAspectRatio,'Value',1)
5207        else
5208            set(handles.CheckFixAspectRatio,'Value',0)
5209 
5210        end
5211    end
5212    if isfield(Coordinates,'AspectRatio')
5213        set(handles.num_AspectRatio,'String',num2str(Coordinates.AspectRatio))
5214    end
5215    if isfield(Coordinates,'MinX')
5216        set(handles.num_MinX,'String',num2str(Coordinates.MinX,4));
5217        set(handles.num_MaxX,'String',num2str(Coordinates.MaxX,4));
5218        set(handles.num_MinY,'String',num2str(Coordinates.MinY,4));
5219        set(handles.num_MaxY,'String',num2str(Coordinates.MaxY,4));
5220    else
5221        set(handles.num_MinX,'String','');
5222        set(handles.num_MaxX,'String','');
5223        set(handles.num_MinY,'String','');
5224        set(handles.num_MaxY,'String','');
5225    end
5226end
5227
5228%% scalar or image parameters
5229if isfield(PlotParam,'Scalar')
5230    set(handles.Scalar,'Visible','on')
5231    if isfield(PlotParam.Scalar,'MaxA')
5232        set(handles.num_MaxA,'String',num2str(PlotParam.Scalar.MaxA,3));
5233    end
5234    if isfield(PlotParam.Scalar,'MinA')
5235        set(handles.num_MinA,'String',num2str(PlotParam.Scalar.MinA,3));
5236    end   
5237    if isfield(PlotParam.Scalar,'IncrA')
5238        set(handles.num_IncrA,'String',num2str(PlotParam.Scalar.IncrA,3))
5239    end
5240    set(handles.CheckBW,'Value',PlotParam.Scalar.CheckBW)
5241    if isfield(PlotParam.Scalar,'Opacity')&&isfield(handles,'num_Opacity')
5242        set(handles.num_Opacity,'String',num2str(PlotParam.Scalar.Opacity))
5243    end
5244else
5245    set(handles.Scalar,'Visible','off')
5246end
5247
5248%% parameter for vector field
5249if isfield(PlotParam,'Vectors')
5250    set(handles.Vectors,'Visible','on')
5251    if isfield(PlotParam.Vectors,'VecScale')
5252        set(handles.num_VecScale,'String',num2str(PlotParam.Vectors.VecScale,3))
5253    end
5254    if isfield(PlotParam.Vectors,'MinC')&& isfield(PlotParam.Vectors,'MaxC')
5255        MinC=PlotParam.Vectors.MinC;
5256        MaxC=PlotParam.Vectors.MaxC;
5257        set(handles.num_MinVec,'String', num2str(MinC,3));
5258        set(handles.num_MaxVec,'String',num2str(MaxC,3));
5259        list=get(handles.ColorCode,'String');
5260        ichoice=get(handles.ColorCode,'Value');
5261        color_option=list{ichoice};
5262        test3color=strcmp(color_option,'rgb')||strcmp(color_option,'bgr');
5263        if test3color% need to update color thresholds
5264            set(handles.num_ColCode1,'Visible','on')
5265            set(handles.num_ColCode2,'Visible','on')
5266            set(handles.Slider1,'Visible','on')
5267            set(handles.Slider2,'Visible','on')
5268            set(handles.num_ColCode1,'String',num2str(PlotParam.Vectors.ColCode1,3))
5269            set(handles.num_ColCode2,'String',num2str(PlotParam.Vectors.ColCode2,3))
5270            set(handles.Slider1,'Value',(PlotParam.Vectors.ColCode1-MinC)/(MaxC-MinC))
5271            set(handles.Slider2,'Value',(PlotParam.Vectors.ColCode2-MinC)/(MaxC-MinC))
5272        else
5273            set(handles.num_ColCode1,'Visible','off')
5274            set(handles.num_ColCode2,'Visible','off')
5275            set(handles.Slider1,'Visible','off')
5276            set(handles.Slider2,'Visible','off')
5277        end
5278    end
5279else
5280    set(handles.Vectors,'Visible','off')
5281    if isfield(handles,'edit_vect')
5282        set(handles.edit_vect,'Visible','off')
5283        set(handles.record,'Visible','off')
5284    end
5285end
Note: See TracBrowser for help on using the repository browser.