source: trunk/src/uvmat.m @ 672

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

various bugs corrected

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