source: trunk/src/uvmat.m @ 641

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

corrections for mask and transform fct

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