source: trunk/src/uvmat.m @ 610

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

various bugs corrected after tests with Windows OS.

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