source: trunk/src/uvmat.m @ 611

Last change on this file since 611 was 611, checked in by sommeria, 8 years ago

problem of time display repaired

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