source: trunk/src/uvmat.m @ 660

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

a few bugs corrected in geometry_calib

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