source: trunk/src/uvmat.m @ 650

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

bugs corrected: handles.TimeName? in uvmat, 0_OAR emptied for culter computations with series.

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