source: trunk/src/uvmat.m @ 656

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

various bugs corrected

File size: 231.5 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 UvData.Field.NbDim>1
2550    UvData.Field=find_field_bounds(UvData.Field);
2551    % default projection plane
2552    if isempty(UvData.ProjObject{1})
2553        UvData.ProjObject{1}.Type='plane';%main plotting plane
2554        UvData.ProjObject{1}.ProjMode='projection';%main plotting plane
2555       % UvData.ProjObject{1}.Coord=[0 0 0];
2556        UvData.ProjObject{1}.DisplayHandle.uvmat=[]; %plane not visible in uvmat
2557        UvData.ProjObject{1}.DisplayHandle.view_field=[]; %plane not visible in uvmat
2558    end
2559    %% 3D case (menuvolume)
2560    if UvData.Field.NbDim==3% && UvData.NewSeries
2561        test_set_object=1;
2562        hset_object=findobj(allchild(0),'tag','set_object');% look for the set_object GUI
2563        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
2564        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
2565        if ~isempty(hset_object) %if set_object is detected
2566            delete(hset_object);% delete the GUI set_object if it does not fit
2567        end
2568        if test_set_object% reinitiate the GUI set_object
2569            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
2570            UvData.ProjObject{1}.NbDim=NbDim;%test for 3D objects
2571            UvData.ProjObject{1}.RangeZ=UvData.Field.CoordMesh;%main plotting plane
2572            UvData.ProjObject{1}.Coord(1,3)=(UvData.Field.ZMin+UvData.Field.ZMax)/2;%section at a middle plane chosen
2573            UvData.ProjObject{1}.Angle=[0 0 0];
2574            UvData.ProjObject{1}.HandlesDisplay=plot(0,0,'Tag','proj_object');% A REVOIR
2575            UvData.ProjObject{1}.Name='1-PLANE';
2576            UvData.ProjObject{1}.enable_plot=1;
2577            set_object(UvData.ProjObject{1},handles,ZBounds);
2578            set(handles.ListObject,'Value',1);
2579            set(handles.ListObject,'String',{'1-PLANE'});
2580            set(handles.CheckEditObject,'Value',1)% put the plane in edit mode to enable the z cursor
2581            CheckEditObject_Callback([],[], handles)
2582        end
2583        %multilevel case (single menuplane in a 3D space)
2584    elseif isfield(UvData,'Z')
2585        if isfield(UvData,'CoordType')&& isequal(UvData.CoordType,'phys') && isfield(UvData,'XmlData')
2586            XmlData=UvData.XmlData{1};
2587            if isfield(XmlData,'PlanePos')
2588                UvData.ProjObject{1}.Coord=XmlData.PlanePos(UvData.ZIndex,:);
2589            end
2590            if isfield(XmlData,'PlaneAngle')
2591                siz=size(XmlData.PlaneAngle);
2592                indangle=min(siz(1),UvData.ZIndex);%take first angle if a single angle is defined (translating scanning)
2593                UvData.ProjObject{1}.PlaneAngle=XmlData.PlaneAngle(indangle,:);
2594            end
2595        elseif isfield(UvData,'ZIndex')
2596            UvData.ProjObject{1}.ZObject=UvData.ZIndex;
2597        end
2598    end
2599end
2600
2601testnewseries=UvData.NewSeries;
2602UvData.NewSeries=0;% put to 0 the test for a new field series (set by RootPath_callback)
2603set(handles.uvmat,'UserData',UvData)
2604
2605%% reset the min and max of scalar if only the mask is displayed(TODO: check the need)
2606% if isfield(UvData,'Mask')&& ~isfield(UvData,'A')
2607%     set(handles.num_MinA,'String','0')
2608%     set(handles.num_MaxA,'String','255')
2609% end
2610
2611%% usual 1D (x,y) plots
2612if UvData.Field.NbDim<=1
2613    set(handles.Objects,'Visible','off')
2614    set(handles.ListObject_1_title,'Visible','off')
2615    set(handles.ListObject_1,'Visible','off')
2616    [PlotType,PlotParamOut]=plot_field(UvData.Field,handles.PlotAxes,read_GUI(handles.uvmat));
2617    errormsg=fill_GUI(PlotParamOut,handles.uvmat);
2618    for list={'Scalar','Vectors'}
2619        if ~isfield(PlotParamOut,list{1})
2620            set(handles.(list{1}),'Visible','off')
2621        end
2622    end
2623   
2624%% 2D or 3D fieldname are generally projected
2625else
2626    set(handles.Objects,'Visible','on')
2627    set(handles.ListObject_1_title,'Visible','on')
2628    set(handles.ListObject_1,'Visible','on')
2629   
2630    %% Plot the projections on the selected  projection objects
2631    % main projection object (uvmat display)
2632    list_object=get(handles.ListObject_1,'String');
2633    if isequal(list_object,{''})||isequal(list_object,' ')%refresh list of objects if the menu is empty
2634        set(handles.ListObject,'Value',1)
2635        set(handles.ListObject,'String',{'plane'})
2636        UvData.ProjObject{1}.Type='plane';%main plotting plane
2637        UvData.ProjObject{1}.ProjMode='projection';%main plotting plane
2638        UvData.ProjObject{1}.DisplayHandle.uvmat=[]; %plane not visible in uvmat
2639        UvData.ProjObject{1}.DisplayHandle.view_field=[]; %plane not visible in uvmat
2640        set(handles.ListObject_1,'Value',1)
2641        set(handles.ListObject_1,'String',{'plane'})
2642    end
2643    IndexObj(1)=get(handles.ListObject_1,'Value');%selected projection object for main view
2644    if IndexObj(1)> numel(UvData.ProjObject)
2645        IndexObj(1)=1;%select the first object if the selected one does not exist
2646        set(handles.ListObject_1,'Value',1)
2647    end
2648    IndexObj(2)=get(handles.ListObject,'Value');%selected projection object for main view
2649    if isequal(IndexObj(2),IndexObj(1))
2650        IndexObj(2)=[];
2651    end
2652    plot_handles{1}=handles;
2653    if isfield(UvData,'plotaxes')%case of movies
2654        haxes(1)=UvData.plotaxes;
2655    else
2656        haxes(1)=handles.PlotAxes;
2657    end
2658    PlotParam{1}=read_GUI(handles.uvmat);
2659    %default settings if vectors not visible
2660    if ~isfield(PlotParam{1},'Vectors')
2661        PlotParam{1}.Vectors.MaxVec=1;
2662        PlotParam{1}.Vectors.MinVec=0;
2663        PlotParam{1}.Vectors.CheckFixVecColor=1;
2664        PlotParam{1}.Vectors.ColCode1=0.33;
2665        PlotParam{1}.Vectors.ColCode2=0.66;
2666        PlotParam{1}.Vectors.ColorScalar={''};
2667        PlotParam{1}.Vectors.ColorCode= {'rgb'};
2668    end
2669    PosColorbar{1}=UvData.OpenParam.PosColorbar;%prescribe the colorbar position on the uvmat interface
2670   
2671    %% second projection object (view_field display)
2672    if length( IndexObj)>=2
2673        view_field_handle=findobj(allchild(0),'tag','view_field');%handles of the view_field GUI
2674        if ~isempty(view_field_handle)
2675            plot_handles{2}=guidata(view_field_handle);
2676            haxes(2)=plot_handles{2}.PlotAxes;
2677            PlotParam{2}=read_GUI(view_field_handle);
2678           % PlotParam{2}=read_GUI(handles.uvmat);%read plotting parameters on the uvmat interface
2679            PosColorbar{2}='*'; %TODO: deal with colorbar position on view_field
2680        end
2681    end
2682   
2683    %% loop on the projection objects: one or two
2684   
2685    for imap=1:numel(IndexObj)
2686        iobj=IndexObj(imap);
2687        if numel(UvData.ProjObject)<iobj
2688            break
2689        end
2690        [ObjectData,errormsg]=proj_field(UvData.Field,UvData.ProjObject{iobj});% project field on the object
2691        if ~isempty(errormsg)
2692            return
2693        end
2694        if testnewseries
2695            PlotParam{imap}.Scalar.CheckBW=[]; %B/W option depends on the input field (image or scalar)
2696            if isfield(ObjectData,'CoordUnit')
2697                PlotParam{imap}.Coordinates.CheckFixAspectRatio=1;% set x and y scaling equal if CoordUnit is defined (common unit for x and y)
2698                PlotParam{imap}.Coordinates.AspectRatio=1; %set aspect ratio to 1
2699            end
2700        end
2701        %use of mask (TODO: check)
2702        if isfield(ObjectData,'NbDim') && isequal(ObjectData.NbDim,2) && isfield(ObjectData,'Mask') && isfield(ObjectData,'A')
2703            flag_mask=double(ObjectData.Mask>200);%=0 for masked regions
2704            AX=ObjectData.AX;%x coordiantes for the scalar field
2705            AY=ObjectData.AY;%y coordinates for the scalar field
2706            MaskX=ObjectData.MaskX;%x coordiantes for the mask
2707            MaskY=ObjectData.MaskY;%y coordiantes for the mask
2708            if ~isequal(MaskX,AX)||~isequal(MaskY,AY)
2709                nxy=size(flag_mask);
2710                sizpx=(ObjectData.MaskX(end)-ObjectData.MaskX(1))/(nxy(2)-1);%size of a mask pixel
2711                sizpy=(ObjectData.MaskY(1)-ObjectData.MaskY(end))/(nxy(1)-1);
2712                x_mask=ObjectData.MaskX(1):sizpx:ObjectData.MaskX(end); % pixel x coordinates for image display
2713                y_mask=ObjectData.MaskY(1):-sizpy:ObjectData.MaskY(end);% pixel x coordinates for image display
2714                %project on the positions of the scalar
2715                npxy=size(ObjectData.A);
2716                dxy(1)=(ObjectData.AY(end)-ObjectData.AY(1))/(npxy(1)-1);%grid mesh in y
2717                dxy(2)=(ObjectData.AX(end)-ObjectData.AX(1))/(npxy(2)-1);%grid mesh in x
2718                xi=ObjectData.AX(1):dxy(2):ObjectData.AX(end);
2719                yi=ObjectData.AY(1):dxy(1):ObjectData.AY(end);
2720                [XI,YI]=meshgrid(xi,yi);% creates the matrix of regular coordinates
2721                flag_mask = interp2(x_mask,y_mask,flag_mask,XI,YI);
2722            end
2723            AClass=class(ObjectData.A);
2724            ObjectData.A=flag_mask.*double(ObjectData.A);
2725            ObjectData.A=feval(AClass,ObjectData.A);
2726        end
2727        if ~isempty(ObjectData)
2728            %PlotType='none'; %default
2729            if imap==2 && isempty(view_field_handle)
2730                view_field(ObjectData)
2731            else
2732              %  ObjectData.VarAttribute{5}.Role='scalar';TODO    CORRECT
2733                [PlotType,PlotParamOut]=plot_field(ObjectData,haxes(imap),PlotParam{imap},PosColorbar{imap});
2734                if imap==1
2735                    errormsg=fill_GUI(PlotParamOut,handles.uvmat);
2736                else
2737                    errormsg=fill_GUI(PlotParamOut,view_field_handle);
2738                end
2739                for list={'Scalar','Vectors'}
2740                    if ~isfield(PlotParamOut,list{1})
2741                        set(plot_handles{imap}.(list{1}),'Visible','off')
2742                    end
2743                end
2744                if isfield(Field,'CoordMesh')&&~isempty(Field.CoordMesh)
2745                    ObjectData.CoordMesh=Field.CoordMesh; % gives an estimated mesh size (useful for mouse action on the plot)
2746                end
2747            end
2748        end
2749    end
2750   
2751    %% update the mask
2752    if isequal(get(handles.CheckMask,'Value'),1)%if the mask option is on
2753        update_mask(handles);
2754    end
2755   
2756    %% prepare the menus of histograms and plot them (histogram of the whole volume in 3D case)
2757    menu_histo=(UvData.Field.ListVarName)';%list of field variables to be displayed for the menu of histogram display
2758    ind_skip=[];
2759    % nb_histo=1;
2760    Ustring='';
2761    Vstring='';
2762    % suppress coordinates from the histogram menu
2763    for ivar=1:numel(menu_histo)%l loop on field variables:
2764        if isfield(UvData.Field,'VarAttribute') && numel(UvData.Field.VarAttribute)>=ivar && isfield(UvData.Field.VarAttribute{ivar},'Role')
2765            Role=UvData.Field.VarAttribute{ivar}.Role;
2766            switch Role
2767                case {'coord_x','coord_y','coord_z','dimvar'}
2768                    ind_skip=[ind_skip ivar];
2769                case {'vector_x'}
2770                    Ustring=UvData.Field.ListVarName{ivar};
2771                    ind_skip=[ind_skip ivar];
2772                case {'vector_y'}
2773                    Vstring=UvData.Field.ListVarName{ivar};
2774                    ind_skip=[ind_skip ivar];
2775            end
2776        end
2777        DimCell=UvData.Field.VarDimName{ivar};
2778        DimName='';
2779        if ischar(DimCell)
2780            DimName=DimCell;
2781        elseif iscell(DimCell)&& numel(DimCell)==1
2782            DimName=DimCell{1};
2783        end
2784        if strcmp(DimName,menu_histo{ivar})
2785            ind_skip=[ind_skip ivar];
2786        end
2787    end
2788    menu_histo(ind_skip)=[];% remove skipped items
2789    if ~isempty(Ustring)
2790        menu_histo=[{[Ustring ',' Vstring]};menu_histo];% add U, V at the beginning if they exist
2791    end
2792   
2793    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2794    % display menus and plot histograms
2795    test_v=0;
2796    if ~isempty(menu_histo)
2797        set(handles.histo1_menu,'Value',1)
2798        set(handles.histo1_menu,'String',menu_histo)
2799        histo1_menu_Callback(handles.histo1_menu, [], handles)% plot first histogram
2800    end
2801end
2802ResizeFcn(handles.uvmat,[],handles)
2803
2804%------------------------------------------------------------------------
2805function histo1_menu_Callback(hObject, eventdata, handles)
2806%--------------------------------------------
2807histo_menu=get(handles.histo1_menu,'String');
2808histo_value=get(handles.histo1_menu,'Value');
2809FieldName=histo_menu{histo_value};
2810
2811UvData=get(handles.uvmat,'UserData');
2812Field=UvData.Field;
2813r=regexp(FieldName,'(?<var1>.*)(?<sep>,)(?<var2>.*)','names');
2814FieldName_2='';
2815if ~isempty(r)
2816    FieldName=r.var1;
2817    FieldName_2=r.var2;
2818end
2819if ~isfield(UvData.Field,FieldName)
2820    msgbox_uvmat('ERROR',['no field  ' FieldName ' for histogram'])
2821    return
2822end
2823FieldHisto=Field.(FieldName);
2824if isfield(Field,'FF') && ~isempty(Field.FF) && isequal(size(Field.FF),size(FieldHisto))
2825    indsel=find(Field.FF==0);%find values marked as false
2826    if ~isempty(indsel)
2827        FieldHisto=FieldHisto(indsel);
2828        if ~isempty(FieldName_2)
2829            FieldHisto(:,:,2)=Field.(FieldName_2)(indsel);
2830        end
2831    end
2832end
2833if isempty(Field)
2834    msgbox_uvmat('ERROR',['empty field ' FieldName])
2835else
2836    nxy=size(FieldHisto);
2837    Amin=double(min(min(min(FieldHisto))));%min of field value
2838    Amax=double(max(max(max(FieldHisto))));%max of field value
2839    if isequal(Amin,Amax)
2840        cla(handles.HistoAxes)
2841    else
2842        Histo.ListVarName={FieldName,'histo'};
2843        if isfield(Field,'NbDim') && isequal(Field.NbDim,3)
2844            Histo.VarDimName={FieldName,FieldName}; %dimensions for the histogram
2845        else
2846            if numel(nxy)==2
2847                Histo.VarDimName={FieldName,FieldName}; %dimensions for the histogram
2848            else
2849                Histo.VarDimName={FieldName,{FieldName,'component'}}; %dimensions for the histogram
2850            end
2851        end
2852        %unit
2853        units=[]; %default
2854        for ivar=1:numel(Field.ListVarName)
2855            if strcmp(Field.ListVarName{ivar},FieldName)
2856                if isfield(Field,'VarAttribute') && numel(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'units')
2857                    units=Field.VarAttribute{ivar}.units;
2858                    break
2859                end
2860            end
2861        end
2862        if ~isempty(units)
2863            Histo.VarAttribute{1}.units=units;
2864        end
2865        eval(['Histo.' FieldName '=linspace(Amin,Amax,50);'])%absissa values for histo
2866        if isfield(Field,'NbDim') && isequal(Field.NbDim,3)
2867            C=reshape(double(FieldHisto),1,[]);% reshape in a vector
2868            Histo.histo(:,1)=hist(C, Histo.(FieldName));  %calculate histogram
2869        else
2870            for col=1:size(FieldHisto,3)
2871                B=FieldHisto(:,:,col);
2872                C=reshape(double(B),1,nxy(1)*nxy(2));% reshape in a vector
2873                Histo.histo(:,col)=hist(C, Histo.(FieldName));  %calculate histogram
2874            end
2875        end
2876        plot_field(Histo,handles.HistoAxes);
2877        hlegend=legend;
2878        if isempty(FieldName_2)
2879        set(hlegend,'String',FieldName)
2880        else
2881            set(hlegend,'String',{FieldName;FieldName_2})
2882        end
2883    end
2884end
2885
2886%------------------------------------------------------------------------
2887% --- translate coordinate to matrix index
2888%------------------------------------------------------------------------
2889function [indx,indy]=pos2ind(x0,rangx0,nxy)
2890indx=1+round((nxy(2)-1)*(x0-rangx0(1))/(rangx0(2)-rangx0(1)));% index x of pixel 
2891indy=1+round((nxy(1)-1)*(y12-rangy0(1))/(rangy0(2)-rangy0(1)));% index y of pixel
2892
2893%------------------------------------------------------------------------
2894% --- Executes on button press in 'CheckZoom'.
2895%------------------------------------------------------------------------
2896function CheckZoom_Callback(hObject, eventdata, handles)
2897
2898if get(handles.CheckZoom,'Value')
2899    set(handles.CheckFixLimits,'Value',1)% propose by default fixed limits for the plotting axes
2900    set(handles.CheckZoomFig,'Value',0)%desactivate zoom fig
2901end
2902
2903%------------------------------------------------------------------------
2904% --- Executes on button press in CheckZoomFig.
2905%------------------------------------------------------------------------
2906function CheckZoomFig_Callback(hObject, eventdata, handles)
2907
2908if get(handles.CheckZoomFig,'Value')
2909    set(handles.CheckZoom,'value',0)
2910end
2911
2912%------------------------------------------------------------------------
2913% --- Executes on button press in 'CheckFixLimits'.
2914%------------------------------------------------------------------------
2915function CheckFixLimits_Callback(hObject, eventdata, handles)
2916
2917if ~get(handles.CheckFixLimits,'Value')
2918    update_plot(handles);
2919end
2920
2921%------------------------------------------------------------------------
2922% --- Executes on button press in CheckFixAspectRatio.
2923function CheckFixAspectRatio_Callback(hObject, eventdata, handles)
2924%------------------------------------------------------------------------
2925
2926if get(handles.CheckFixAspectRatio,'Value')
2927    update_plot(handles);
2928else
2929    update_plot(handles);
2930end
2931
2932%------------------------------------------------------------------------
2933function num_AspectRatio_Callback(hObject, eventdata, handles)
2934%------------------------------------------------------------------------
2935set(handles.CheckFixAspectRatio,'Value',1)% select the fixed aspect ratio button
2936update_plot(handles);
2937
2938%------------------------------------------------------------------------
2939%----Executes on button press in 'record': records the current flags of manual correction.
2940%------------------------------------------------------------------------
2941function record_Callback(hObject, eventdata, handles)
2942
2943[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
2944FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
2945[erread,message]=fileattrib(FileName);
2946if ~isempty(message) && ~isequal(message.UserWrite,1)
2947     msgbox_uvmat('ERROR',['no writting access to ' FileName])
2948     return
2949end
2950MenuVelType=get(handles.VelType,'String');
2951test_civ2=strcmp(MenuVelType{get(handles.VelType,'Value')},'civ2');
2952test_civ1=strcmp(MenuVelType{get(handles.VelType,'Value')},'civ1');
2953if ~test_civ2 && ~test_civ1
2954    msgbox_uvmat('ERROR','manual correction only possible for CIV1 or CIV2 velocity fields')
2955end
2956if test_civ2
2957    nbname='nb_vec_2';
2958   flagname='Civ2_FF';
2959   CivStage=5;
2960end
2961if test_civ1
2962    nbname='nb_vec_1';
2963   flagname='Civ1_FF';
2964    CivStage=2;
2965end
2966%write fix flags in the netcdf file
2967UvData=get(handles.uvmat,'UserData');
2968hhh=which('netcdf.open');% look for built-in matlab netcdf library
2969if ~isequal(hhh,'')% case of  builtin Matlab netcdf library
2970    nc=netcdf.open(FileName,'NC_WRITE');
2971    netcdf.reDef(nc);
2972    netcdf.putAtt(nc,netcdf.getConstant('NC_GLOBAL'),'CivStage',CivStage);
2973    dimid = netcdf.inqDimID(nc,nbname);
2974    try
2975        varid = netcdf.inqVarID(nc,flagname);% look for already existing fixflag variable
2976    catch
2977        varid=netcdf.defVar(nc,flagname,'double',dimid);%create fixflag variable if it does not exist
2978    end
2979    netcdf.endDef(nc);
2980    netcdf.putVar(nc,varid,UvData.PlotAxes.FF);
2981    netcdf.close(nc); 
2982else %old netcdf library
2983    netcdf_toolbox(FileName,AxeData,attrname,nbname,flagname)
2984end
2985
2986%-------------------------------------------------------------------
2987%----Correct the netcdf file, using toolbox (old versions of Matlab).
2988%-------------------------------------------------------------------
2989function netcdf_toolbox(FileName,AxeData,attrname,nbname,flagname)
2990nc=netcdf(FileName,'write'); %open netcdf file
2991result=redef(nc);
2992eval(['nc.' attrname '=1;']);
2993theDim=nc(nbname) ;% get the number of velocity vectors
2994nb_vectors=size(theDim);
2995var_FixFlag=ncvar(flagname,nc);% var_FixFlag will be written as the netcdf variable vec_FixFlag
2996var_FixFlag(1:nb_vectors)=AxeData.FF;%
2997fin=close(nc);
2998
2999%-------------------------------------------------------------------
3000% --- Executes on button press in SubField
3001function SubField_Callback(hObject, eventdata, handles)
3002%-------------------------------------------------------------------
3003UvData=get(handles.uvmat,'UserData');
3004if get(handles.SubField,'Value')==0% if the subfield button is desactivated   
3005    set(handles.RootPath_1,'String','')
3006    set(handles.RootFile_1,'String','')
3007    set(handles.SubDir_1,'String','');
3008    set(handles.FileIndex_1,'String','');
3009    set(handles.FileExt_1,'String','');
3010    set(handles.RootPath_1,'Visible','off')
3011    set(handles.RootFile_1,'Visible','off')
3012    set(handles.SubDir_1,'Visible','off');
3013    set(handles.NomType_1,'Visible','off');
3014    set(handles.TimeValue_1,'Visible','off')
3015    set(handles.FileIndex_1,'Visible','off');
3016    set(handles.FileExt_1,'Visible','off');
3017    set(handles.FieldName_1,'Value',1);%set to blank state
3018    set(handles.VelType_1,'Value',1);%set to blank state
3019    set(handles.num_Opacity,'String','')% desactivate opacity setting
3020    FieldList=get(handles.FieldName,'String');
3021    if numel(FieldList)>1   % if a choice of fields exists
3022        set(handles.FieldName_1,'Value',1)% set second field choice to blank
3023        set(handles.FieldName_1,'String',[{''};FieldList])% reproduce the menu FieldName plus a blank option
3024    else
3025        set(handles.FieldName_1,'String',{''})% set second field choice to blank
3026    end
3027    if ~strcmp(get(handles.VelType,'Visible'),'on')
3028        set(handles.VelType_1,'Visible','off')
3029    end
3030    if isfield(UvData,'XmlData_1')
3031        UvData=rmfield(UvData,'XmlData_1');
3032    end
3033    set(handles.uvmat,'UserData',UvData);
3034    transform_fct_list=get(handles.TransformName,'String');
3035    transform_fct=transform_fct_list(get(handles.TransformName,'Value'));
3036    if strcmp(transform_fct,'sub_field')
3037        set(handles.TransformName,'Value',1)%suppress the sub_field transform
3038        TransformName_Callback(hObject, eventdata, handles);
3039    else
3040        run0_Callback(hObject, eventdata, handles)
3041    end 
3042else
3043    %RootPath=get(handles.RootPath,'String');
3044    %SubDir=get(handles.SubDir,'String');
3045    fileinput_1=uigetfile_uvmat('select a second input file:',get(handles.RootPath,'String'));
3046    if isempty(fileinput_1)
3047        set(handles.SubField,'Value',0)
3048    else
3049       
3050        % refresh the current displayed field
3051        set(handles.SubField,'Value',1)
3052        display_file_name(handles,fileinput_1,2)
3053       
3054        %update list of recent files in the menubar
3055        MenuFile_1=fileinput_1;
3056        MenuFile_2=get(handles.MenuFile_1,'Label');
3057        MenuFile_3=get(handles.MenuFile_2,'Label');
3058        MenuFile_4=get(handles.MenuFile_3,'Label');
3059        MenuFile_5=get(handles.MenuFile_4,'Label');
3060        set(handles.MenuFile_1,'Label',MenuFile_1)
3061        set(handles.MenuFile_2,'Label',MenuFile_2)
3062        set(handles.MenuFile_3,'Label',MenuFile_3)
3063        set(handles.MenuFile_4,'Label',MenuFile_4)
3064        set(handles.MenuFile_5,'Label',MenuFile_5)
3065    end
3066    %     MenuBrowse_1_Callback(hObject, eventdata, handles)
3067end
3068
3069%------------------------------------------------------------------------
3070% --- read the data displayed for the input rootfile windows (new): TODO use read_GUI
3071
3072function [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles)
3073%------------------------------------------------------------------------
3074InputFile=read_GUI(handles.InputFile);
3075RootPath=InputFile.RootPath;
3076SubDir=regexprep(InputFile.SubDir,'/|\','');
3077RootFile=regexprep(InputFile.RootFile,'/|\','');
3078FileIndices=InputFile.FileIndex;
3079FileExt=InputFile.FileExt;
3080
3081
3082%------------------------------------------------------------------------
3083% ---- read the data displayed for the second input rootfile windows
3084function [RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1,NomType_1]=read_file_boxes_1(handles)
3085%------------------------------------------------------------------------
3086RootPath_1=get(handles.RootPath_1,'String'); % read the data from the file1_input window
3087if isequal(get(handles.RootPath_1,'Visible'),'off') || isequal(RootPath_1,'"')
3088    RootPath_1=get(handles.RootPath,'String');
3089end;
3090SubDir_1=get(handles.SubDir_1,'String');
3091if isequal(get(handles.SubDir_1,'Visible'),'off')|| isequal(SubDir_1,'"')
3092    SubDir_1=get(handles.SubDir,'String');
3093end
3094SubDir_1=regexprep(SubDir_1,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3095RootFile_1=get(handles.RootFile_1,'String');
3096if isequal(get(handles.RootFile_1,'Visible'),'off') || isequal(RootFile_1,'"')
3097    RootFile_1=get(handles.RootFile,'String');
3098end
3099RootFile_1=regexprep(RootFile_1,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3100FileIndex_1=get(handles.FileIndex_1,'String');
3101if isequal(get(handles.FileIndex_1,'Visible'),'off')|| isequal(FileIndex_1,'"')
3102    FileIndex_1=get(handles.FileIndex,'String');
3103end
3104FileExt_1=get(handles.FileExt_1,'String');
3105if isequal(get(handles.FileExt_1,'Visible'),'off') || isequal(FileExt_1,'"')
3106    FileExt_1=get(handles.FileExt,'String');%read FileExt by default
3107end
3108NomType_1=get(handles.NomType_1,'String');
3109if isequal(get(handles.NomType_1,'Visible'),'off') || isequal(NomType_1,'"')
3110    NomType_1=get(handles.NomType,'String');%read FileExt by default
3111end
3112%------------------------------------------------------------------------
3113% --- Executes on menu selection FieldName
3114function FieldName_Callback(hObject, eventdata, handles)
3115%------------------------------------------------------------------------
3116
3117%% read data from uvmat
3118UvData=get(handles.uvmat,'UserData');
3119list_fields=get(handles.FieldName,'String');% list menu fields
3120index_fields=get(handles.FieldName,'Value');% selected string index
3121field= list_fields{index_fields(1)}; % selected string
3122[RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
3123FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3124[tild,tild,tild,i1,i2,j1,j2,tild,NomType]=fileparts_uvmat(['xxx' get(handles.FileIndex,'String') FileExt]);
3125
3126switch field
3127   
3128    case 'get_field...'
3129    %% fill the coordinates and variables from selections in get_field
3130        ParamIn=[];
3131        % in case of civ data, we use the civ choice as default input for the GUI get_field
3132        if strcmp(get(handles.VelType,'Visible'),'on')
3133            ParamIn.SwitchVarIndexTime='attribute';
3134            ListVelType=get(handles.VelType,'String');
3135            VelType=ListVelType{get(handles.VelType,'Value')};
3136            switch VelType
3137                case 'civ1'
3138                    ParamIn.TimeVarName='Civ1_Time';
3139                    ParamIn.vector_x='Civ1_U';
3140                    ParamIn.vector_y='Civ1_V';
3141                    ParamIn.vec_color='Civ1_C';
3142                case 'filter1'
3143                    ParamIn.TimeVarName='Civ1_Time';
3144                    ParamIn.vector_x='Civ1_U_smooth';
3145                    ParamIn.vector_y='Civ1_V_smooth';
3146                case 'civ2'
3147                    ParamIn.TimeVarName='Civ2_Time';
3148                    ParamIn.vector_x='Civ2_U';
3149                    ParamIn.vector_y='Civ2_V';
3150                case 'filter2'
3151                    ParamIn.TimeVarName='Civ2_Time';
3152                    ParamIn.vector_x='Civ2_U_smooth';
3153                    ParamIn.vector_y='Civ2_V_smooth';
3154                    ParamIn.vec_color='Civ2_C';
3155            end
3156        end
3157       
3158        % VelType menu desactivated
3159        set(handles.FixVelType,'visible','off')
3160        set(handles.VelType,'Visible','off')
3161        %set(handles.VelType_1,'Visible','off')
3162       
3163        %read selection from get_field
3164        [RootPath,SubDir,RootFile,FileIndices,FileExt]=read_file_boxes(handles);
3165        FileName=[fullfile(RootPath,SubDir,RootFile) FileIndices FileExt];
3166        GetFieldData=get_field(FileName,ParamIn);% inport field names from the GUI get_field
3167        FieldList={};
3168        VecColorList={};
3169        switch GetFieldData.FieldOption
3170            case 'vectors'
3171                UName=GetFieldData.PanelVectors.vector_x;
3172                VName=GetFieldData.PanelVectors.vector_y;
3173                YName={GetFieldData.Coordinates.Coord_y};
3174                CName=GetFieldData.PanelVectors.vec_color;
3175                [FieldList,VecColorList]=set_field_list(UName,VName,CName);
3176            case 'scalar'
3177                AName=GetFieldData.PanelScalar.scalar;
3178                YName={GetFieldData.Coordinates.Coord_y};
3179                FieldList={AName};
3180            case '1D plot'
3181                YName=GetFieldData.PanelOrdinate.ordinate;
3182            case 'civdata...'%return to civdata from get_field
3183               % [FieldList,VecColorList]=set_field_list('U','V','C');
3184                set(handles.FieldName,'Value',2)
3185                set(handles.FixVelType,'visible','on')
3186                set(handles.VelType,'Visible','on')
3187        end
3188        if ~strcmp(GetFieldData.FieldOption,'civdata...')
3189            XName=GetFieldData.Coordinates.Coord_x;
3190        TimeNameStr=GetFieldData.Time.SwitchVarIndexTime;
3191        if strcmp(TimeNameStr,'file index')
3192            set(handles.TimeName,'String','');
3193        else
3194            set(handles.TimeName,'String',[TimeNameStr(1:3) ':' GetFieldData.Time.TimeName]);
3195        end
3196        if strcmp(TimeNameStr,'variable')||strcmp(TimeNameStr,'dim index')% we scan a variable index, not a file index
3197            set(handles.NomType,'String','*')
3198            set(handles.RootFile,FileName)
3199        end
3200        %     set(handles.TimeValue,'String' SwitchVarIndexTime
3201        set(handles.Coord_x,'String',XName)
3202        if ischar(YName)
3203            YName={YName};
3204        end
3205        set(handles.Coord_y,'Data',YName)
3206        set(handles.FieldName,'Value',1)
3207        set(handles.FieldName,'String',[FieldList; {'get_field...'}]);
3208        set(handles.ColorScalar,'Value',1)
3209        set(handles.ColorScalar,'String',VecColorList);
3210        UvData.FileType{1}='netcdf';
3211        set(handles.uvmat,'UserData',UvData)
3212        end
3213        run0_Callback(hObject, eventdata, handles)
3214       
3215    case 'image'
3216    %% look for image corresponding to civ data
3217        if  isfield(UvData.Field,'Civ2_ImageA')%get the corresponding input image in the netcdf file
3218            imagename=UvData.Field.Civ2_ImageA;
3219        elseif isfield(UvData.Field,'Civ1_ImageA')%
3220            imagename=UvData.Field.Civ1_ImageA;
3221        else
3222            SubDirBase=regexprep(SubDir,'\..*','');%take the root part of SubDir, before the first dot '.'
3223            imagename=fullfile_uvmat(RootPath,SubDirBase,RootFile,'.png',NomType,i1,[],j1,[]);
3224        end
3225        if ~exist(imagename,'file')
3226            imagename=uigetfile_uvmat('Pick an image file',imagename,'image');
3227            if isempty(imagename)
3228                return
3229            end
3230        end
3231        % display the selected field and related information
3232        display_file_name(handles,imagename)%display the image
3233     otherwise
3234%         ext=get(handles.FileExt,'String');
3235%         if ~isequal(ext,'.nc') %find the new NomType if the previous display was not already a netcdf file
3236%             [FileName,PathName] = uigetfile( ...
3237%                 {'*.nc', ' (*.nc)';
3238%                 '*.nc',' netcdf files'; ...
3239%                 '*.*',  'All Files (*.*)'}, ...
3240%                 'Pick a netcdf file',FileBase);
3241%             if ~ischar(FileName),return,end %abandon if the browser is cancelled
3242%             FullFileName=[PathName FileName];
3243            % display the selected field and related information
3244             run0_Callback(hObject, eventdata, handles)
3245end
3246
3247%----------------------------------------------------------------
3248% --- Executes on menu selection FieldName
3249function FieldName_1_Callback(hObject, eventdata, handles)
3250%-------------------------------------------------
3251
3252%%%%%% TODO: modify like FieldName_Callback
3253%% read input data
3254check_new=~get(handles.SubField,'Value'); %check_new=1 if a second field was not previously entered
3255UvData=get(handles.uvmat,'UserData');
3256if check_new && isfield(UvData,'XmlData')
3257    UvData.XmlData{2}=UvData.XmlData{1};
3258end
3259if isfield(UvData,'Field_1')
3260    UvData=rmfield(UvData,'Field_1');% remove the stored second field (a new one needs to be read)
3261end
3262UvData.FileName_1='';% desactivate the use of a constant second file
3263list_fields=get(handles.FieldName,'String');% list menu fields
3264field= list_fields{get(handles.FieldName,'Value')}; % selected string
3265list_fields=get(handles.FieldName_1,'String');% list menu fields
3266field_1= list_fields{get(handles.FieldName_1,'Value')}; % selected string for the second field
3267if isempty(field_1)%||(numel(UvData.FileType)>=2 && strcmp(UvData.FileType{2},'image'))
3268    set(handles.SubField,'Value',0)
3269    SubField_Callback(hObject, eventdata, handles)
3270    return
3271else
3272    set(handles.SubField,'Value',1)%state that a second field is now entered
3273end
3274
3275%% read the rootfile input display
3276[RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
3277FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];
3278[tild,tild,tild,i1,i2,j1,j2]=fileparts_uvmat(get(handles.FileIndex,'String'));
3279switch field_1
3280    case 'get_field...'
3281        set_veltype_display(0) % no veltype display
3282        hget_field=findobj(allchild(0),'name','get_field_1');
3283        if ~isempty(hget_field)
3284            delete(hget_field)
3285        end
3286        hget_field=get_field(FileName_1);
3287        set(hget_field,'name','get_field_1')
3288        hhget_field=guidata(hget_field);
3289        set(hhget_field.list_fig,'Value',1)
3290        set(hhget_field.list_fig,'String',{'uvmat'})
3291        if check_new
3292            UvData.FileType{2}=UvData.FileType{1};
3293            set(handles.FileIndex_1,'String',get(handles.FileIndex,'String'))
3294              set(handles.uvmat,'UserData',UvData)
3295        end
3296    case 'image'
3297        % get the image name corresponding to the current netcdf name (no unique correspondance)
3298        if  isfield(UvData.Field,'Civ2_ImageA')%get the corresponding input image in the netcdf file
3299            imagename=UvData.Field.Civ2_ImageA;
3300        elseif isfield(UvData.Field,'Civ1_ImageA')%
3301            imagename=UvData.Field.Civ1_ImageA;
3302        else
3303            SubDirBase=regexprep(SubDir_1,'\..*','');%take the root part of SubDir, before the first dot '.'
3304            imagename=fullfile_uvmat(RootPath_1,SubDirBase,RootFile_1,'.png',get(handles.NomType,'String'),i1,[],j1);
3305        end
3306        if ~exist(imagename,'file') % browse for images if it is not found
3307            [FileName,PathName] = uigetfile( ...
3308                {'*.png;*.jpg;*.tif;*.avi;*.AVI;*.vol', ' (*.png, .tif, *.avi,*.vol)';
3309                '*.jpg',' jpeg image files'; ...
3310                '*.png','.png image files'; ...
3311                '*.tif','.tif image files'; ...
3312                '*.avi;*.AVI','.avi movie files'; ...
3313                '*.vol','.volume images (png)'; ...
3314                '*.*',  'All Files (*.*)'}, ...
3315                'Pick an image',imagename);
3316            if ~ischar(FileName),return,end %abandon if the browser is cancelled
3317            imagename=[PathName FileName];
3318        end
3319        if ~ischar(imagename)% quit if the browser has  been closed
3320            set(handles.SubField,'Value',0)
3321        else %valid browser input:  display the selected image
3322            set(handles.TitleNpxy,'Visible','on')% visible npx,pxcm... buttons
3323            set(handles.num_Npx,'Visible','on')
3324            set(handles.num_Npy,'Visible','on')
3325            display_file_name(handles,imagename,2)%display the imag
3326        end
3327    otherwise
3328        check_refresh=1;
3329        if check_new% if a second field was not previously entered, we just read another field in the first input file
3330            set(handles.FileIndex_1,'String',get(handles.FileIndex,'String'))
3331            set(handles.FileExt_1,'String',get(handles.FileExt,'String'))
3332           
3333            UvData.FileType{2}=UvData.FileType{1};
3334            UvData.XmlData{2}= UvData.XmlData{1};
3335            transform=get(handles.TransformPath,'UserData');
3336             if (~isa(transform,'function_handle')||nargin(transform)<3)
3337                set(handles.uvmat,'UserData',UvData)
3338                set(handles.TransformName,'value',2); % set transform fct to 'sub_field' if the current fct does not accept two input fields
3339                transform_fct_Callback(hObject, eventdata, handles)% activate transform_fct_Callback and refresh current plot
3340                 check_refresh=0;
3341             end             
3342        end
3343        if ~isequal(field,'image')
3344            set(handles.TitleNpxy,'Visible','off')% visible npx,pxcm... buttons
3345            set(handles.num_Npx,'Visible','off')
3346            set(handles.num_Npy,'Visible','off')
3347        end
3348        set(handles.uvmat,'UserData',UvData)
3349 
3350        if check_refresh && ~(isfield(UvData,'NewSeries')&&isequal(UvData.NewSeries,1))
3351            run0_Callback(hObject, eventdata, handles)
3352        end
3353end
3354
3355%------------------------------------------------------------------------
3356% --- set the visibility of relevant velocity type menus:
3357function menu=set_veltype_display(Civ,FileType)
3358%------------------------------------------------------------------------
3359if ~exist('FileType','var')
3360    FileType='civx';
3361end
3362switch FileType
3363    case 'civx'
3364        menu={'civ1';'interp1';'filter1';'civ2';'interp2';'filter2'};
3365        if isequal(Civ,0)
3366            imax=0;
3367        elseif isequal(Civ,1) || isequal(Civ,2)
3368            imax=1;
3369        elseif isequal(Civ,3)
3370            imax=3;
3371        elseif isequal(Civ,4) || isequal(Civ,5)
3372            imax=4;
3373        elseif isequal(Civ,6) %patch2
3374            imax=6;
3375        end
3376    case 'civdata'
3377        menu={'civ1';'filter1';'civ2';'filter2'};
3378        if isequal(Civ,0)
3379            imax=0;
3380        elseif isequal(Civ,1) || isequal(Civ,2)
3381            imax=1;
3382        elseif isequal(Civ,3)
3383            imax=2;
3384        elseif isequal(Civ,4) || isequal(Civ,5)
3385            imax=3;
3386        elseif isequal(Civ,6) %patch2
3387            imax=4;
3388        end
3389end
3390menu=menu(1:imax);
3391
3392%------------------------------------------------------------------------
3393% --- Executes on button press in FixVelType.
3394function FixVelType_Callback(hObject, eventdata, handles)
3395%------------------------------------------------------------------------
3396% refresh the current plot if the fixed  veltype is unselected
3397if ~get(handles.FixVelType,'Value')
3398    run0_Callback(hObject, eventdata, handles)
3399end
3400
3401%------------------------------------------------------------------------
3402% --- Executes on button press in VelType.
3403function VelType_Callback(hObject, eventdata, handles)
3404%------------------------------------------------------------------------
3405set(handles.FixVelType,'Value',1)
3406run0_Callback(hObject, eventdata, handles)
3407
3408%------------------------------------------------------------------------
3409% --- Executes on choice selection in VelType_1.
3410function VelType_1_Callback(hObject, eventdata, handles)
3411%------------------------------------------------------------------------
3412set(handles.FixVelType,'Value',1)% the velocity type is now imposed by the GUI (not automatic)
3413UvData=get(handles.uvmat,'UserData');
3414set(handles.run0,'BackgroundColor',[1 1 0])%paint run0 button in yellow to indicate its activation
3415drawnow   
3416InputFile=read_GUI(handles.InputFile);% read the input file parameters
3417[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
3418[RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
3419FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];% name of the first input file
3420
3421check_refresh=0;
3422if isempty(InputFile.VelType_1)
3423        FileName_1='';% we plot the first input field without the second field
3424        set(handles.SubField,'Value',0)
3425        SubField_Callback(hObject, eventdata, handles)% activate SubField_Callback and refresh current plot, removing the second field
3426elseif get(handles.SubField,'Value')% if subfield is already 'on'
3427     FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];% name of the second input file
3428     check_refresh=1;%will refresh the current plot
3429else% we introduce the same file (with a different field) for the second series
3430     FileName_1=FileName;% we compare two fields in the same file
3431     UvData.FileType{2}=UvData.FileType{1};
3432     UvData.XmlData{2}= UvData.XmlData{1};
3433     set(handles.SubField,'Value',1)
3434     transform=get(handles.TransformPath,'UserData');
3435     if (~isa(transform,'function_handle')||nargin(transform)<3)
3436        set(handles.uvmat,'UserData',UvData)
3437        set(handles.TransformName,'value',2); % set transform fct to 'sub_field' if the current fct does not accept two input fields
3438        transform_fct_Callback(hObject, eventdata, handles)% activate transform_fct_Callback and refresh current plot
3439     else
3440         check_refresh=1;
3441     end 
3442end
3443
3444% refresh the current plot if it has not been done previously
3445if check_refresh
3446    UvData.FileName_1='';% desactivate the use of a constant second file
3447    set(handles.uvmat,'UserData',UvData)
3448    num_i1=stra2num(get(handles.i1,'String'));
3449    num_i2=stra2num(get(handles.i2,'String'));
3450    num_j1=stra2num(get(handles.j1,'String'));
3451    num_j2=stra2num(get(handles.j2,'String'));
3452    [tild,tild,tild,i1_1,i2_1,j1_1,j2_1]=fileparts_uvmat(['xx' FileIndex_1]);
3453    errormsg=refresh_field(handles,FileName,FileName_1,num_i1,num_i2,num_j1,num_j2,i1_1,i2_1,j1_1,j2_1);
3454    if ~isempty(errormsg)
3455        msgbox_uvmat('ERROR',errormsg);
3456    else
3457        set(handles.i1,'BackgroundColor',[1 1 1])
3458        set(handles.i2,'BackgroundColor',[1 1 1])
3459        set(handles.j1,'BackgroundColor',[1 1 1])
3460        set(handles.j2,'BackgroundColor',[1 1 1])
3461        set(handles.FileIndex,'BackgroundColor',[1 1 1])
3462        set(handles.FileIndex_1,'BackgroundColor',[1 1 1])
3463    end
3464    set(handles.run0,'BackgroundColor',[1 0 0])
3465end
3466
3467
3468%------------------------------------------------------------------------
3469% --- reset civ buttons
3470function reset_vel_type(handles_civ0,handle1)
3471%------------------------------------------------------------------------
3472for ibutton=1:length(handles_civ0)
3473    set(handles_civ0(ibutton),'BackgroundColor',[0.831 0.816 0.784])
3474    set(handles_civ0(ibutton),'Value',0)
3475end
3476if exist('handle1','var')%handles of selected button
3477        set(handle1,'BackgroundColor',[1 1 0]) 
3478end
3479
3480%-----------------------------------------------------------------------
3481% --- Executes on button press in MENUVOLUME.
3482function VOLUME_Callback(hObject, eventdata, handles)
3483%-----------------------------------------------------------------------
3484%errordlg('command VOL not implemented yet')
3485if ishandle(handles.UVMAT_title)
3486    delete(handles.UVMAT_title)
3487end
3488UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
3489if isequal(get(handles.VOLUME,'Value'),1)
3490    set(handles.CheckZoom,'Value',0)
3491%     set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
3492    set(handles.edit_vect,'Value',0)
3493    edit_vect_Callback(hObject, eventdata, handles)
3494    set(handles.CheckEditObject,'Value',0)
3495%     set(handles.CheckEditObject,'BackgroundColor',[0.7 0.7 0.7])
3496%     set(handles.cal,'Value',0)
3497%     set(handles.cal,'BackgroundColor',[0 1 0])
3498    set(handles.edit_vect,'Value',0)
3499    edit_vect_Callback(hObject, eventdata, handles)
3500    %initiate set_object GUI
3501    data.Name='VOLUME';
3502    if isfield(UvData,'CoordType')
3503        data.CoordType=UvData.CoordType;
3504    end
3505    if isfield(UvData.Field,'CoordMesh')&~isempty(UvData.Field.CoordMesh)
3506        data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
3507        data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
3508        data.DX=UvData.Field.CoordMesh;
3509        data.DY=UvData.Field.CoordMesh;
3510    elseif isfield(UvData.Field,'AX')&isfield(UvData.Field,'AY')& isfield(UvData.Field,'A')%only image
3511        np=size(UvData.Field.A);
3512        meshx=(UvData.Field.AX(end)-UvData.Field.AX(1))/np(2);
3513        meshy=abs(UvData.Field.AY(end)-UvData.Field.AY(1))/np(1);
3514        data.RangeY=max(meshx,meshy);
3515        data.RangeX=max(meshx,meshy);
3516        data.DX=max(meshx,meshy);
3517    end
3518    data.ParentButton=handles.VOLUME;
3519    PlotHandles=get_plot_handles(handles);%get the handles of the interface elements setting the plotting parameters
3520    [hset_object,UvData.sethandles]=set_object(data,PlotHandles);% call the set_object interface with action on haxes,
3521                                                      % associate the set_object interface handle to the plotting axes
3522    %set(hset_object,'Position',get(handles.uvmat,'Position')+UvData.OpenParam.PosSetObject)
3523    UvData.MouseAction='create_object';
3524else
3525    set(handles.VOLUME,'BackgroundColor',[0 1 0])
3526end
3527set(handles.uvmat,'UserData',UvData)
3528
3529%-------------------------------------------------------
3530function edit_vect_Callback(hObject, eventdata, handles)
3531%-------------------------------------------------------
3532%
3533if isequal(get(handles.edit_vect,'Value'),1)
3534    VelTypeMenu=get(handles.VelType,'String');
3535    VelType=VelTypeMenu{get(handles.VelType,'Value')};
3536    if ~strcmp(VelType,'civ2') && ~strcmp(VelType,'civ1')
3537        msgbox_uvmat('ERROR','manual correction only possible for CIV1 or CIV2 velocity fields')
3538    end
3539    set(handles.record,'Visible','on')
3540    set(handles.edit_vect,'BackgroundColor',[1 1 0])
3541    set(handles.CheckEditObject,'Value',0)
3542    set(handles.CheckZoom,'Value',0)
3543%     set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
3544%     set(handles.CheckEditObject,'BackgroundColor',[0.7 0.7 0.7])
3545    set(gcf,'Pointer','arrow')
3546else
3547    set(handles.record,'Visible','off')
3548    set(handles.edit_vect,'BackgroundColor',[0.7 0.7 0.7])
3549end
3550
3551%----------------------------------------------
3552function save_mask_Callback(hObject, eventdata, handles)
3553%-----------------------------------------------------------------------
3554UvData=get(handles.uvmat,'UserData');
3555
3556flag=1;
3557npx=size(UvData.Field.A,2);
3558npy=size(UvData.Field.A,1);
3559xi=0.5:npx-0.5;
3560yi=0.5:npy-0.5;
3561[Xi,Yi]=meshgrid(xi,yi);
3562if isfield(UvData,'ProjObject')
3563    for iobj=1:length(UvData.ProjObject)
3564        ObjectData=UvData.ProjObject{iobj};
3565        if isfield(ObjectData,'ProjMode') &&(isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside'));
3566            flagobj=1;
3567            testphys=0; %coordinates in pixels by default
3568            if isfield(ObjectData,'CoordType') && isequal(ObjectData.CoordType,'phys')
3569                if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
3570                    Calib=UvData.XmlData{1}.GeometryCalib;
3571                    testphys=1;
3572                end
3573            end
3574            if isfield(ObjectData,'Coord')& isfield(ObjectData,'Style')
3575                if isequal(ObjectData.Type,'polygon')
3576                    X=ObjectData.Coord(:,1);
3577                    Y=ObjectData.Coord(:,2);
3578                    if testphys
3579                        [X,Y]=px_XYZ(Calib,X,Y,0);% to generalise with 3D cases
3580                    end
3581                    flagobj=~inpolygon(Xi,Yi,X',Y');%=0 inside the polygon, 1 outside                 
3582                elseif isequal(ObjectData.Type,'ellipse')
3583                    if testphys
3584                        %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
3585                    end
3586                    RangeX=max(ObjectData.RangeX);
3587                    RangeY=max(ObjectData.RangeY);
3588                    X2Max=RangeX*RangeX;
3589                    Y2Max=RangeY*RangeY;
3590                    distX=(Xi-ObjectData.Coord(1,1));
3591                    distY=(Yi-ObjectData.Coord(1,2));
3592                    flagobj=(distX.*distX/X2Max+distY.*distY/Y2Max)>1;
3593                elseif isequal(ObjectData.Type,'rectangle')
3594                    if testphys
3595                        %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
3596                    end
3597                    distX=abs(Xi-ObjectData.Coord(1,1));
3598                    distY=abs(Yi-ObjectData.Coord(1,2));
3599                    flagobj=distX>max(ObjectData.RangeX) | distY>max(ObjectData.RangeY);
3600                end
3601                if isequal(ObjectData.ProjMode,'mask_outside')
3602                    flagobj=~flagobj;
3603                end
3604                flag=flag & flagobj;
3605            end
3606        end
3607    end
3608end
3609% flag=~flag;
3610%mask name
3611RootPath=get(handles.RootPath,'String');
3612RootFile=get(handles.RootFile,'String');
3613RootFile=regexprep(RootFile,'\<[\\/]|[\\/]\>','');%suppress possible / or \ separator at the beginning or the end of the string
3614filebase=fullfile(RootPath,RootFile);
3615list=get(handles.masklevel,'String');
3616masknumber=num2str(length(list));
3617maskindex=get(handles.masklevel,'Value');
3618mask_name=fullfile_uvmat(RootPath,SubDir,[RootFile '_' masknumber 'mask'],'.png','_1',maskindex);
3619%mask_name=name_generator([filebase '_' masknumber 'mask'],maskindex,1,'.png','_i');
3620imflag=uint8(255*(0.392+0.608*flag));% =100 for flag=0 (vectors not computed when 20<imflag<200)
3621imflag=flipdim(imflag,1);
3622% imflag=uint8(255*flag);% =0 for flag=0 (vectors=0 when 20<imflag<200)
3623msgbox_uvmat('CONFIRMATION',[mask_name ' saved'])
3624imwrite(imflag,mask_name,'BitDepth',8);
3625
3626%display the mask
3627figure;
3628vec=linspace(0,1,256);%define a linear greyscale colormap
3629map=[vec' vec' vec'];
3630colormap(map)
3631
3632image(imflag);
3633
3634%------------------------------------------------------------------------
3635%------------------------------------------------------------------------
3636%  - FUNCTIONS FOR SETTING PLOTTING PARAMETERS
3637
3638%------------------------------------------------------------------------
3639%------------------------------------------------------------------------
3640% --- Executes on selection change in TransformName.
3641
3642function TransformName_Callback(hObject, eventdata, handles)
3643%------------------------------------------------------------------------
3644UvData=get(handles.uvmat,'UserData');
3645menu=get(handles.TransformName,'String');refresh
3646ichoice=get(handles.TransformName,'Value');%item number in the menu
3647transform_name=menu{ichoice};% choice of the transform fct
3648list_path=get(handles.TransformName,'UserData');
3649
3650%% add a new item to the menu if the option 'more...' has been selected
3651prev_path=fullfile(get(handles.TransformPath,'String'));
3652if ~exist(prev_path,'dir')
3653    prev_path=fullfile(fileparts(which('uvmat')),'transform_field');
3654end
3655if strcmp(transform_name,'more...');
3656    transform_fct=uigetfile_uvmat('Pick the transform function',prev_path,'.m');
3657    %     [FileName, PathName] = uigetfile( ...
3658    %         {'*.m', ' (*.m)';
3659    %         '*.m',  '.m files '; ...
3660    %         '*.*', 'All Files (*.*)'}, ...
3661    %         'Pick the transform function', prev_path);
3662    %     if ~ischar(FileName),return,end %abandon if the browser is cancelled
3663    %     path_transform_fct =fullfile(PathName,FileName);
3664    if ~isempty(transform_fct)
3665        [PathName,transform_name]=fileparts(transform_fct);
3666        %     if isempty(regexp(FileName,'\.m$'))% detect file extension .m
3667        %         msgbox_uvmat('ERROR','a Matlab function .m must be introduced');
3668        %         return
3669        %     else
3670        %         transform_name=regexprep(FileName,'\.m','');
3671        %     end
3672        ichoice=find(strcmp(transform_name,menu),1);%look for the selected fct in the existing menu
3673        if isempty(ichoice)% if the item is not found, add it to the menu (before 'more...' and select it)
3674            menu=[menu(1:end-1);{transform_name};{'more...'}];
3675            ichoice=numel(menu)-1;
3676        end
3677        list_path{ichoice}=PathName;%update the list fo fct paths
3678        set(handles.TransformName,'String',menu)
3679        set(handles.TransformName,'Value',ichoice)
3680       
3681        % save the new menu in the personal file 'uvmat_perso.mat'
3682        dir_perso=prefdir;%personal Matalb directory
3683        profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
3684        if exist(profil_perso,'file')
3685            nb_builtin=UvData.OpenParam.NbBuiltin;% number of 'builtin' (basic) transform fcts in uvmat
3686            if nb_builtin<numel(list_path)
3687                for ilist=nb_builtin+1:numel(list_path)
3688                    transform_fct{ilist-nb_builtin}=[fullfile(list_path{ilist},menu{ilist}) '.m'];
3689                end
3690                save (profil_perso,'transform_fct','-append'); %store the root name for future opening of uvmat
3691            end
3692        end
3693    end
3694end
3695
3696%% create the function handle of the selected fct
3697
3698if isempty(list_path{ichoice})% case of no selected fct
3699    transform_handle=[];
3700else
3701    if ~exist(list_path{ichoice},'dir')
3702        msgbox_uvmat('ERROR','invalid fct path: select the transform fct again with the option more...')
3703        return
3704    end
3705    current_dir=pwd;%current working dir
3706    cd(list_path{ichoice})
3707    transform_handle=str2func(transform_name);
3708    cd(current_dir)
3709end
3710set(handles.TransformPath,'String',list_path{ichoice})
3711set(handles.TransformPath,'UserData',transform_handle)
3712set(handles.TransformName,'UserData',list_path)
3713
3714%% update the ToolTip string of the menu TransformName with the first line of the selected fct file
3715if isempty(list_path{ichoice})% case of no selected fct
3716    set(handles.TransformName,'ToolTipString','transform_fct:choose a transform function')
3717else
3718    try
3719        [fid,errormsg] =fopen([fullfile(list_path{ichoice},transform_name) '.m']);
3720        InputText=textscan(fid,'%s',1,'delimiter','\n');
3721        fclose(fid)
3722        set(handles.TransformName,'ToolTipString',['transform_fct: ' InputText{1}{1}])% put the first line of the selected function as tooltip help
3723    end
3724end
3725
3726%% adapt the GUI to the input/output conditions of the selected transform fct
3727DataOut=[];
3728CoordUnit='';
3729CoordUnitPrev='';
3730if isfield(UvData,'Field')&&isfield(UvData.Field,'CoordUnit')
3731    CoordUnitPrev=UvData.Field.CoordUnit;
3732end
3733if ~isempty(list_path{ichoice})
3734    if nargin(transform_handle)>1 && isfield(UvData,'XmlData')&&~isempty(UvData.XmlData)
3735        XmlData=UvData.XmlData{1};
3736        DataOut=feval(transform_handle,'*',XmlData);
3737        if isfield(DataOut,'CoordUnit')% set the requested coord unit (info used to possibly delete the current projection objects)
3738            CoordUnit=DataOut.CoordUnit;
3739        end
3740        if isfield(DataOut,'InputFieldType')% to be used to impose a type of input file (eg. for image transform)
3741            UvData.InputFieldType=DataOut.InputFieldType;
3742        end
3743        if isfield(DataOut,'XmlData')%  used to add transform parameters at selection of the transform fct
3744            ListFields=fieldnames(DataOut.XmlData);
3745            for ilist=1:numel(ListFields)
3746            UvData.XmlData{1}.(ListFields{ilist})=DataOut.XmlData.(ListFields{ilist});
3747            end
3748        end
3749    else
3750        DataOut=feval(transform_handle,'*');
3751    end
3752end
3753
3754
3755%% delete drawn objects if the output CooordUnit is different from the previous one
3756if ~strcmp(CoordUnit,CoordUnitPrev)
3757    set(handles.CheckFixLimits,'Value',0)
3758% set(handles.CheckFixLimits,'BackgroundColor',[0.7 0.7 0.7])
3759    hother=findobj('Tag','proj_object');%find all the proj objects
3760    for iobj=1:length(hother)
3761        delete_object(hother(iobj))
3762    end
3763    hother=findobj('Tag','DeformPoint');%find all the proj objects
3764    for iobj=1:length(hother)
3765        delete_object(hother(iobj))
3766    end
3767    hh=findobj('Tag','calib_points');
3768    if ~isempty(hh)
3769        delete(hh)
3770    end
3771    hhh=findobj('Tag','calib_marker');
3772    if ~isempty(hhh)
3773        delete(hhh)
3774    end
3775    set(handles.ListObject,'Value',1)
3776    set(handles.ListObject,'String',{''})
3777    set(handles.ListObject_1,'Value',1)
3778    set(handles.ListObject_1,'String',{''})
3779    set(handles.CheckViewObject,'value',0)
3780    CheckViewObject_Callback(hObject, eventdata, handles)
3781    set(handles.CheckViewField,'value',0)
3782    CheckViewField_Callback(hObject, eventdata, handles)
3783    set(handles.CheckEditObject,'Value',0)
3784    CheckEditObject_Callback(hObject, eventdata, handles)
3785    UvData.ProjObject={[]};
3786end
3787set(handles.uvmat,'UserData',UvData)
3788
3789%% refresh the current plot
3790if isempty(list_path{ichoice}) || nargin(transform_handle)<3
3791    set(handles.SubField,'Value',0)
3792    SubField_Callback(hObject, eventdata, handles)
3793else
3794    run0_Callback(hObject, eventdata, handles)
3795end
3796
3797%------------------------------------------------
3798%CALLBACKS FOR PLOTTING PARAMETERS
3799%-------------------------------------------------
3800%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3801% Plot coordinates
3802%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3803%------------------------------------------------------------------------
3804function num_MinX_Callback(hObject, eventdata, handles)
3805%------------------------------------------------------------------------
3806set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3807% set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3808update_plot(handles);
3809
3810%------------------------------------------------------------------------
3811function num_MaxX_Callback(hObject, eventdata, handles)
3812%------------------------------------------------------------------------
3813set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3814% set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3815update_plot(handles);
3816
3817%------------------------------------------------------------------------
3818function num_MinY_Callback(hObject, eventdata, handles)
3819%------------------------------------------
3820set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3821% set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3822update_plot(handles);
3823
3824%------------------------------------------------------------------------
3825function num_MaxY_Callback(hObject, eventdata, handles)
3826%------------------------------------------------------------------------
3827set(handles.CheckFixLimits,'Value',1) %suppress auto mode
3828% set(handles.CheckFixLimits,'BackgroundColor',[1 1 0])
3829update_plot(handles);
3830
3831%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3832% Scalar or image representation
3833%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3834%------------------------------------------------------------------------
3835function num_MinA_Callback(hObject, eventdata, handles)
3836%------------------------------------------
3837set(handles.CheckFixScalar,'Value',1) %suppress auto mode
3838% set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3839MinA=str2double(get(handles.num_MinA,'String'));
3840MaxA=str2double(get(handles.num_MaxA,'String'));
3841if MinA>MaxA% switch minA and maxA in case of error
3842    MinA_old=MinA;
3843    MinA=MaxA;
3844    MaxA=MinA_old;
3845    set(handles.num_MinA,'String',num2str(MinA,5));
3846    set(handles.num_MaxA,'String',num2str(MaxA,5));
3847end
3848update_plot(handles);
3849
3850%------------------------------------------------------------------------
3851function num_MaxA_Callback(hObject, eventdata, handles)
3852%------------------------------------------------------------------------
3853set(handles.CheckFixScalar,'Value',1) %suppress auto mode
3854% set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3855MinA=str2double(get(handles.num_MinA,'String'));
3856MaxA=str2double(get(handles.num_MaxA,'String'));
3857if MinA>MaxA% switch minA and maxA in case of error
3858        MinA_old=MinA;
3859    MinA=MaxA;
3860    MaxA=MinA_old;
3861    set(handles.num_MinA,'String',num2str(MinA,5));
3862    set(handles.num_MaxA,'String',num2str(MaxA,5));
3863end
3864update_plot(handles);
3865
3866%------------------------------------------------------------------------
3867function CheckFixScalar_Callback(hObject, eventdata, handles)
3868%------------------------------------------------------------------------
3869test=get(handles.CheckFixScalar,'Value');
3870if test
3871%     set(handles.CheckFixScalar,'BackgroundColor',[1 1 0])
3872else
3873%     set(handles.CheckFixScalar,'BackgroundColor',[0.7 0.7 0.7])
3874    update_plot(handles);
3875end
3876
3877%-------------------------------------------------------------------
3878function CheckBW_Callback(hObject, eventdata, handles)
3879%-------------------------------------------------------------------
3880update_plot(handles);
3881
3882%-------------------------------------------------------------------
3883function num_Opacity_Callback(hObject, eventdata, handles)
3884update_plot(handles);
3885%-------------------------------------------------------------------
3886
3887%-------------------------------------------------------------------
3888function ListContour_Callback(hObject, eventdata, handles)
3889%-------------------------------------------------------------------
3890val=get(handles.ListContour,'Value');
3891if val==2
3892    set(handles.interval_txt,'Visible','on')
3893    set(handles.num_IncrA,'Visible','on')
3894else
3895    set(handles.interval_txt,'Visible','off')
3896    set(handles.num_IncrA,'Visible','off')
3897end
3898update_plot(handles);
3899
3900%-------------------------------------------------------------------
3901function num_IncrA_Callback(hObject, eventdata, handles)
3902%-------------------------------------------------------------------
3903update_plot(handles);
3904
3905
3906%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3907% Vector representation
3908%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3909%-------------------------------------------------------------------
3910function CheckHideWarning_Callback(hObject, eventdata, handles)
3911%-------------------------------------------------------------------
3912update_plot(handles);
3913
3914%-------------------------------------------------------------------
3915function CheckHideFalse_Callback(hObject, eventdata, handles)
3916%-------------------------------------------------------------------
3917update_plot(handles);
3918
3919%-------------------------------------------------------------------
3920function num_VecScale_Callback(hObject, eventdata, handles)
3921%-------------------------------------------------------------------
3922set(handles.CheckFixVectors,'Value',1);
3923set(handles.CheckFixVectors,'BackgroundColor',[1 1 0])
3924update_plot(handles);
3925
3926%-------------------------------------------------------------------
3927function CheckFixVectors_Callback(hObject, eventdata, handles)
3928%-------------------------------------------------------------------
3929test=get(handles.CheckFixVectors,'Value');
3930if test
3931%     set(handles.CheckFixVectors,'BackgroundColor',[1 1 0])
3932else
3933    update_plot(handles);
3934    %set(handles.num_VecScale,'String',num2str(ScalOut.num_VecScale,3))
3935%     set(handles.CheckFixVectors,'BackgroundColor',[0.7 0.7 0.7])
3936end
3937
3938%------------------------------------------------------------------------
3939% --- Executes on selection change in CheckDecimate4 (nb_vec/4).
3940%------------------------------------------------------------------------
3941function CheckDecimate4_Callback(hObject, eventdata, handles)
3942
3943if isequal(get(handles.CheckDecimate4,'Value'),1)
3944    set(handles.CheckDecimate16,'Value',0)
3945end
3946update_plot(handles);
3947
3948%------------------------------------------------------------------------
3949% --- Executes on selection change in CheckDecimate16 (nb_vec/16).
3950%------------------------------------------------------------------------
3951function CheckDecimate16_Callback(hObject, eventdata, handles)
3952
3953if isequal(get(handles.CheckDecimate16,'Value'),1)
3954    set(handles.CheckDecimate4,'Value',0)
3955end
3956update_plot(handles);
3957
3958%------------------------------------------------------------------------
3959% --- Executes on selection change in ColorCode menu
3960function ColorCode_Callback(hObject, eventdata, handles)
3961%------------------------------------------------------------------------
3962% edit the choice for color code
3963update_color_code_boxes(handles);
3964update_plot(handles);
3965
3966%------------------------------------------------------------------------
3967function update_color_code_boxes(handles)
3968%------------------------------------------------------------------------
3969list_code=get(handles.ColorCode,'String');% list menu fields
3970colcode= list_code{get(handles.ColorCode,'Value')}; % selected field
3971enable_slider='off';%default
3972enable_bounds='off';%default
3973enable_scalar='off';%default
3974switch colcode
3975    case {'rgb','bgr'}
3976        enable_slider='on';
3977        enable_bounds='on';
3978        enable_scalar='on';
3979    case '64 colors'
3980        enable_bounds='on';
3981        enable_scalar='on';
3982end
3983set(handles.Slider1,'Visible',enable_slider)
3984set(handles.Slider2,'Visible', enable_slider)
3985set(handles.num_ColCode1,'Visible',enable_slider)
3986set(handles.num_ColCode2,'Visible',enable_slider)
3987set(handles.TitleColCode1,'Visible',enable_slider)
3988set(handles.TitleColCode2,'Visible',enable_slider)
3989set(handles.CheckFixVecColor,'Visible',enable_bounds)
3990set(handles.num_MinVec,'Visible',enable_bounds)
3991set(handles.num_MaxVec,'Visible',enable_bounds)
3992set(handles.ColorScalar,'Visible',enable_scalar)
3993set_vec_col_bar(handles)
3994
3995%------------------------------------------------------------------
3996% --- Executes on selection change in ColorScalar: choice of the color code.
3997function ColorScalar_Callback(hObject, eventdata, handles)
3998%------------------------------------------------------------------
3999% edit the choice for color code
4000list_scalar=get(handles.ColorScalar,'String');% list menu fields
4001col_scalar= list_scalar{get(handles.ColorScalar,'Value')}; % selected field
4002if isequal(col_scalar,'ima_cor')
4003    set(handles.CheckFixVecColor,'Value',1)%fixed scale by default
4004    ColorCode='rgb';
4005    set(handles.num_MinVec,'String','0')
4006    set(handles.num_MaxVec,'String','1')
4007    set(handles.num_ColCode1,'String','0.333')
4008    set(handles.num_ColCode2,'String','0.666')
4009else
4010    set(handles.CheckFixVecColor,'Value',0)%auto scale between min,max by default
4011    ColorCode='64 colors';
4012end
4013ColorCodeList=get(handles.ColorCode,'String');
4014ichoice=find(strcmp(ColorCode,ColorCodeList),1);
4015set(handles.ColorCode,'Value',ichoice)% set color code in the menu
4016
4017update_color_code_boxes(handles);
4018%replot the current graph
4019run0_Callback(hObject, eventdata, handles)
4020
4021%----------------------------------------------------------------
4022% -- Executes on slider movement to set the color code
4023%
4024function Slider1_Callback(hObject, eventdata, handles)
4025%------------------------------------------------------------------
4026slider1=get(handles.Slider1,'Value');
4027min_val=str2num(get(handles.num_MinVec,'String'));
4028max_val=str2num(get(handles.num_MaxVec,'String'));
4029col=min_val+(max_val-min_val)*slider1;
4030set(handles.num_ColCode1,'String',num2str(col))
4031if(get(handles.Slider2,'Value') < col)%move also the second slider at the same value if needed
4032    set(handles.Slider2,'Value',col)
4033    set(handles.num_ColCode2,'String',num2str(col))
4034end
4035set_vec_col_bar(handles)
4036update_plot(handles);
4037
4038%----------------------------------------------------------------
4039% Executes on slider movement to set the color code
4040%----------------------------------------------------------------
4041function Slider2_Callback(hObject, eventdata, handles)
4042slider2=get(handles.Slider2,'Value');
4043min_val=str2num(get(handles.num_MinVec,'String'));
4044max_val=str2num(get(handles.num_MaxVec,'String'));
4045col=min_val+(max_val-min_val)*slider2;
4046set(handles.num_ColCode2,'String',num2str(col))
4047if(get(handles.Slider1,'Value') > col)%move also the first slider at the same value if needed
4048    set(handles.Slider1,'Value',col)
4049    set(handles.num_ColCode1,'String',num2str(col))
4050end
4051set_vec_col_bar(handles)
4052update_plot(handles);
4053
4054%----------------------------------------------------------------
4055% --- Execute on return carriage on the edit box corresponding to slider 1
4056%----------------------------------------------------------------
4057function num_ColCode1_Callback(hObject, eventdata, handles)
4058set_vec_col_bar(handles)
4059update_plot(handles);
4060
4061%----------------------------------------------------------------
4062% --- Execute on return carriage on the edit box corresponding to slider 2
4063%----------------------------------------------------------------
4064function num_ColCode2_Callback(hObject, eventdata, handles)
4065set_vec_col_bar(handles)
4066update_plot(handles);
4067%------------------------------------------------------------------------
4068%-------------------------------------------------------
4069% --- Executes on button press in CheckFixVecColor.
4070%-------------------------------------------------------
4071function VecColBar_Callback(hObject, eventdata, handles)
4072set_vec_col_bar(handles)
4073
4074%------------------------------------------------------------------------
4075% --- Executes on button press in CheckFixVecColor.
4076function CheckFixVecColor_Callback(hObject, eventdata, handles)
4077%------------------------------------------------------------------------
4078if ~get(handles.CheckFixVecColor,'Value')
4079    update_plot(handles);
4080end
4081
4082%------------------------------------------------------------------------
4083% --- Executes on selection change in num_MaxVec.
4084function num_MinVec_Callback(hObject, eventdata, handles)
4085%------------------------------------------------------------------------
4086num_MaxVec_Callback(hObject, eventdata, handles)
4087
4088%------------------------------------------------------------------------
4089% --- Executes on selection change in num_MaxVec.
4090function num_MaxVec_Callback(hObject, eventdata, handles)
4091%------------------------------------------------------------------------
4092set(handles.CheckFixVecColor,'Value',1)
4093CheckFixVecColor_Callback(hObject, eventdata, handles)
4094min_val=str2num(get(handles.num_MinVec,'String'));
4095max_val=str2num(get(handles.num_MaxVec,'String'));
4096slider1=get(handles.Slider1,'Value');
4097slider2=get(handles.Slider2,'Value');
4098colcode1=min_val+(max_val-min_val)*slider1;
4099colcode2=min_val+(max_val-min_val)*slider2;
4100set(handles.num_ColCode1,'String',num2str(colcode1))
4101set(handles.num_ColCode2,'String',num2str(colcode2))
4102update_plot(handles);
4103
4104%------------------------------------------------------------------------
4105% --- update the display of color code for vectors (on vecColBar)
4106function set_vec_col_bar(handles)
4107%------------------------------------------------------------------------
4108%get the image of the color display button 'VecColBar' in pixels
4109set(handles.VecColBar,'Unit','pixel');
4110pos_vert=get(handles.VecColBar,'Position');
4111set(handles.VecColBar,'Unit','Normalized');
4112width=ceil(pos_vert(3));
4113height=ceil(pos_vert(4));
4114
4115%get slider indications
4116list=get(handles.ColorCode,'String');
4117ichoice=get(handles.ColorCode,'Value');
4118colcode.ColorCode=list{ichoice};
4119colcode.MinVec=str2num(get(handles.num_MinVec,'String'));
4120colcode.MaxVec=str2num(get(handles.num_MaxVec,'String'));
4121test3color=strcmp(colcode.ColorCode,'rgb') || strcmp(colcode.ColorCode,'bgr');
4122if test3color
4123    colcode.ColCode1=str2num(get(handles.num_ColCode1,'String'));
4124    colcode.ColCode2=str2num(get(handles.num_ColCode2,'String'));
4125end
4126vec_C=colcode.MinVec+(colcode.MaxVec-colcode.MinVec)*(0.5:width-0.5)/width;%sample of vec_C values from min to max
4127[colorlist,col_vec]=set_col_vec(colcode,vec_C);
4128oneheight=ones(1,height);
4129A1=colorlist(col_vec,1)*oneheight;
4130A2=colorlist(col_vec,2)*oneheight;
4131A3=colorlist(col_vec,3)*oneheight;
4132A(:,:,1)=A1';
4133A(:,:,2)=A2';
4134A(:,:,3)=A3';
4135set(handles.VecColBar,'Cdata',A)
4136
4137%-------------------------------------------------------------------
4138function update_plot(handles)
4139%-------------------------------------------------------------------
4140UvData=get(handles.uvmat,'UserData');
4141AxeData=UvData.PlotAxes;% retrieve the current plotted data
4142PlotParam=read_GUI(handles.uvmat);
4143[tild,PlotParamOut]= plot_field(AxeData,handles.PlotAxes,PlotParam);
4144errormsg=fill_GUI(PlotParamOut,handles.uvmat);
4145%write_plot_param(handles,PlotParamOut); %update the auto plot parameters
4146
4147%------------------------------------------------------------------------
4148%------------------------------------------------------------------------
4149%   SELECTION AND EDITION OF PROJECTION OBJECTS
4150%------------------------------------------------------------------------
4151%------------------------------------------------------------------------
4152
4153% --- Executes on selection change in ListObject_1.
4154function ListObject_1_Callback(hObject, eventdata, handles)
4155list_str=get(handles.ListObject,'String');
4156UvData=get(handles.uvmat,'UserData');
4157ObjectData=UvData.ProjObject{get(handles.ListObject_1,'Value')};
4158
4159%% update the projection plot on uvmat
4160ProjData= proj_field(UvData.Field,ObjectData);%project the current input field on object ObjectData
4161plot_field(ProjData,handles.PlotAxes,read_GUI(handles.uvmat));% plot the projected field;
4162%replot all the objects within the new projected field
4163for IndexObj=1:numel(list_str)
4164        hobject=UvData.ProjObject{IndexObj}.DisplayHandle.uvmat;
4165        if isempty(hobject) || ~ishandle(hobject)
4166            hobject=handles.PlotAxes;
4167        end
4168        if isequal(IndexObj,get(handles.ListObject,'Value'))
4169            objectcolor='m'; %paint in magenta the currently selected object in ListObject
4170        else
4171            objectcolor='b';
4172        end
4173        UvData.ProjObject{IndexObj}.DisplayHandle.uvmat=plot_object(UvData.ProjObject{IndexObj},ObjectData,hobject,objectcolor);%draw the object in uvmat     
4174end
4175set(handles.uvmat,'UserData',UvData)
4176
4177%% display the object parameters if the GUI set_object is already opened
4178if ~get(handles.CheckViewObject,'Value')
4179    ZBounds=0; % default
4180    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4181        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4182        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4183    end
4184    ObjectData.Name=list_str{get(handles.ListObject_1,'Value')};
4185    set_object(ObjectData,[],ZBounds);
4186    set(handles.CheckViewObject,'Value',1)% show that the selected object in ListObject_1 is currently visualised
4187end
4188
4189%  desactivate the edit object mode
4190set(handles.CheckEditObject,'Value',0)
4191% set(handles.CheckEditObject,'BackgroundColor',[0.7,0.7,0.7])
4192
4193%------------------------------------------------------------------------
4194% --- Executes on selection change in ListObject.
4195function ListObject_Callback(hObject, eventdata, handles)
4196%------------------------------------------------------------------------
4197list_str=get(handles.ListObject,'String');
4198IndexObj=get(handles.ListObject,'Value');%present object selection
4199UvData=get(handles.uvmat,'UserData');
4200ObjectData=UvData.ProjObject{IndexObj};
4201    ZBounds=0; % default
4202    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4203        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4204        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4205    end
4206
4207%% show object features if view_object isselected
4208if get(handles.CheckViewObject,'value')
4209    set_object(ObjectData,[],ZBounds);
4210end
4211
4212%% The object  is displayed in set_object if this GUI is already opened
4213%
4214% hset_object=findobj(allchild(0),'tag','set_object');
4215% if ~isempty(hset_object)
4216%
4217%     ObjectData.Name=list_str{IndexObj};
4218%     set_object(ObjectData,[],ZBounds);
4219%     set(handles.CheckViewField,'Value',1)% show that the selected object in ListObject is currently visualised
4220% end
4221
4222%%  desactivate the edit object mode for security
4223set(handles.CheckEditObject,'Value',0)
4224
4225% set(handles.CheckEditObject,'BackgroundColor',[0.7,0.7,0.7])
4226
4227%% update the  plot on view_field if view_field is already openened
4228hview_field=findobj(allchild(0),'tag','view_field');
4229if isempty(hview_field)
4230    hhview_field.PlotAxes=[];
4231else
4232    Data=get(hview_field,'UserData');
4233    hhview_field=guidata(hview_field);
4234    ProjData= proj_field(UvData.Field,ObjectData);%project the current interface field on ObjectData
4235    [PlotType,PlotParam]=plot_field(ProjData,hhview_field.PlotAxes,read_GUI(hview_field));%read plotting parameters on the uvmat interface
4236   
4237    %write_plot_param(hhview_field,PlotParam); %update the display of plotting parameters for the current object
4238    haxes=findobj(hview_field,'tag','axes3');
4239    pos=get(hview_field,'Position'); 
4240    if strcmp(get(haxes,'Visible'),'off')%sempty(PlotParam.Coordinates)% case of no plot display (pure text table)
4241        h_TableDisplay=findobj(hview_field,'tag','TableDisplay');
4242        pos_table=get(h_TableDisplay,'Position');
4243        set(hview_field,'Position',[pos(1)+pos(3)-pos_table(3) pos(2)+pos(4)-pos_table(4) pos_table(3) pos_table(4)])
4244        drawnow% needed to change position before the next command
4245        set(hview_field,'UserData',Data);% restore the previously stored GUI position after GUI resizing
4246    else
4247%         set(hview_field,'Position',Data.GUISize)% return to the previously stored GUI position and size
4248    end
4249end
4250
4251%% update the color of the graphic object representation: the selected object in magenta, others in blue
4252update_object_color(handles.PlotAxes,hhview_field.PlotAxes,UvData.ProjObject{IndexObj}.DisplayHandle.uvmat)
4253
4254%------------------------------------------------------------------------
4255%--- update the color representation of objects (indicating the selected ones)
4256function update_object_color(axes_uvmat,axes_view_field,DisplayHandle)
4257%------------------------------------------------------------------------
4258if isempty(axes_view_field)% case with no view_field plot
4259hother=[findobj(axes_uvmat,'Tag','proj_object');findobj(axes_uvmat,'Tag','DeformPoint')];%find all the proj object and deform point representations
4260else
4261hother=[findobj(axes_uvmat,'Tag','proj_object') ;findobj(axes_view_field,'Tag','proj_object');... %find all the proj object representations
4262findobj(axes_uvmat,'Tag','DeformPoint'); findobj(axes_view_field,'Tag','DeformPoint')];%find all the deform point representations
4263end
4264for iobj=1:length(hother)
4265    if isequal(get(hother(iobj),'Type'),'rectangle')||isequal(get(hother(iobj),'Type'),'patch')
4266        set(hother(iobj),'EdgeColor','b')
4267        if isequal(get(hother(iobj),'FaceColor'),'m')
4268            set(hother(iobj),'FaceColor','b')
4269        end
4270    elseif isequal(get(hother(iobj),'Type'),'image')
4271        Acolor=get(hother(iobj),'CData');
4272        Acolor(:,:,1)=zeros(size(Acolor,1),size(Acolor,2));
4273        set(hother(iobj),'CData',Acolor);
4274    else
4275        set(hother(iobj),'Color','b')
4276    end
4277    set(hother(iobj),'Selected','off')
4278end
4279if ishandle(DisplayHandle)
4280    linetype=get(DisplayHandle,'Type');
4281    if isequal(linetype,'line')
4282        set(DisplayHandle,'Color','m'); %set the selected object to magenta color
4283    elseif isequal(linetype,'rectangle')
4284        set(DisplayHandle,'EdgeColor','m'); %set the selected object to magenta color
4285    elseif isequal(linetype,'patch')
4286        set(DisplayHandle,'FaceColor','m'); %set the selected object to magenta color
4287    end
4288    SubObjectData=get(DisplayHandle,'UserData');
4289    if isfield(SubObjectData,'SubObject') & ishandle(SubObjectData.SubObject)
4290        for iobj=1:length(SubObjectData.SubObject)
4291            hsub=SubObjectData.SubObject(iobj);
4292            if isequal(get(hsub,'Type'),'rectangle')
4293                set(hsub,'EdgeColor','m'); %set the selected object to magenta color
4294            elseif isequal(get(hsub,'Type'),'image')
4295                Acolor=get(hsub,'CData');
4296                Acolor(:,:,1)=Acolor(:,:,3);
4297                set(hsub,'CData',Acolor);
4298            else
4299                set(hsub,'Color','m')
4300            end
4301        end
4302    end
4303    if isfield(SubObjectData,'DeformPoint') & ishandle(SubObjectData.DeformPoint)
4304        set(SubObjectData.DeformPoint,'Color','m')
4305    end
4306end
4307
4308%-------------------------------------------------------------------
4309% --- Executes on selection change in CheckEditObject.
4310function CheckEditObject_Callback(hObject, eventdata, handles)
4311%-------------------------------------------------------------------
4312hset_object=findobj(allchild(0),'Tag','set_object');
4313if get(handles.CheckEditObject,'Value')
4314    %suppress the other options
4315    set(handles.CheckZoom,'Value',0)
4316    CheckZoom_Callback(hObject, eventdata, handles)
4317    hgeometry_calib=findobj(allchild(0),'tag','geometry_calib');
4318    if ishandle(hgeometry_calib)
4319        hhgeometry_calib=guidata(hgeometry_calib);
4320        set(hhgeometry_calib.edit_append,'Value',0)% desactivate mouse action in geometry_calib
4321    end
4322    set(handles.CheckViewObject,'value',1)
4323    CheckViewObject_Callback(hObject, eventdata, handles)
4324else % desactivate object edit mode
4325    if ~isempty(hset_object)% open the
4326        set(get(hset_object,'children'),'Enable','off')
4327        hSAVE=findobj(hset_object,'Tag','SAVE');
4328        set(hSAVE,'Enable','on')
4329    end
4330end
4331
4332
4333%------------------------------------------------------------------------
4334% --- Executes on button press in CheckViewObject.
4335function CheckViewObject_Callback(hObject, eventdata, handles)
4336%------------------------------------------------------------------------
4337check_view=get(handles.CheckViewObject,'Value');
4338
4339if check_view %activate set_object   
4340    IndexObj=get(handles.ListObject,'Value');
4341    list_object=get(handles.ListObject,'String');
4342    UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4343    UvData.ProjObject{IndexObj}.Name=list_object{IndexObj};
4344    if numel(UvData.ProjObject)<IndexObj;% error in UvData
4345        msgbox_uvmat('ERROR','invalid object list')
4346        return
4347    end
4348    ZBounds=0; % default
4349    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4350        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4351        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4352    end
4353    data=UvData.ProjObject{IndexObj};
4354    if ~isfield(data,'Type')% default plane
4355        data.Type='plane';
4356    end
4357    hset_object=set_object(data,[],ZBounds);
4358    hhset_object=guidata(hset_object);
4359    if get(handles.CheckEditObject,'Value')% edit mode
4360        set(get(hset_object,'children'),'Enable','on')
4361    else
4362        set(get(hset_object,'children'),'Enable','off')% deactivate the GUI except SAVE
4363        set(hhset_object.SAVE,'Enable','on')
4364    end
4365else
4366    hset_object=findobj(allchild(0),'tag','set_object');
4367    if ~isempty(hset_object)
4368        delete(hset_object)% delete existing version of set_object
4369    end
4370end
4371 
4372
4373%------------------------------------------------------------------------
4374% --- Executes on button press in CheckViewField.
4375function CheckViewField_Callback(hObject, eventdata, handles)
4376%------------------------------------------------------------------------
4377check_view=get(handles.CheckViewField,'Value');
4378
4379if check_view
4380    IndexObj=get(handles.ListObject,'Value');
4381    UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4382    if numel(UvData.ProjObject)<IndexObj(end);% error in UvData
4383        msgbox_uvmat('ERROR','invalid object list')
4384        return
4385    end
4386    ZBounds=0; % default
4387    if isfield(UvData.Field,'ZMin') && isfield(UvData.Field,'ZMax')
4388        ZBounds(1)=UvData.Field.ZMin; %minimum for the Z slider
4389        ZBounds(2)=UvData.Field.ZMax;%maximum for the Z slider
4390    end
4391    set(handles.ListObject,'Value',IndexObj);%restore ListObject selection after set_object deletion
4392    if ~isfield(UvData.ProjObject{IndexObj(1)},'Type')% default plane
4393        UvData.ProjObject{IndexObj(1)}.Type='plane';
4394    end
4395    list_object=get(handles.ListObject,'String');
4396    UvData.ProjObject{IndexObj(end)}.Name=list_object{IndexObj(end)};
4397   
4398    %% show the projection of the selected object on view_field
4399    ProjData= proj_field(UvData.Field,UvData.ProjObject{IndexObj});%project the current field on ObjectData
4400    hview_field=findobj(allchild(0),'tag','view_field');
4401    if isempty(hview_field)
4402        hview_field=view_field;
4403    end
4404    hhview_field=guidata(hview_field);
4405    [PlotType,PlotParam]=plot_field(ProjData,hhview_field.PlotAxes,read_GUI(hview_field));%read plotting parameters on the GUI view_field);
4406    errormsg=fill_GUI(PlotParam,hview_field);
4407    for list={'Scalar','Vectors'}
4408        if ~isfield(PlotParam,list{1})
4409            set(hhview_field.(list{1}),'Visible','off')
4410        end
4411    end
4412    %write_plot_param(hhview_field,PlotParam); %update the display of plotting parameters for the current object
4413    haxes=findobj(hview_field,'tag','axes3');
4414    pos=get(hview_field,'Position');
4415    if strcmp(get(haxes,'Visible'),'off')%sempty(PlotParam.Coordinates)% case of no plot display (pure text table)
4416        h_TableDisplay=findobj(hview_field,'tag','TableDisplay');
4417        pos_table=get(h_TableDisplay,'Position');
4418        set(hview_field,'Position',[pos(1)+pos(3)-pos_table(3) pos(2)+pos(4)-pos_table(4) pos_table(3) pos_table(4)])
4419    else
4420        Data=get(hview_field,'UserData');
4421%         set(hview_field,'Position',Data.GUISize)% restore the size of view_field for plots
4422    end
4423else
4424    hview_field=findobj(allchild(0),'tag','view_field');
4425    if ~isempty(hview_field)
4426        delete(hview_field)% delete existing version of set_object
4427    end
4428end
4429
4430
4431%------------------------------------------------------------------------
4432% --- Executes on button press in DeleteObject.
4433%------------------------------------------------------------------------
4434function DeleteObject_Callback(hObject, eventdata, handles)
4435
4436IndexObj=get(handles.ListObject,'Value');%projection object selected for view_field
4437IndexObj_1=get(handles.ListObject_1,'Value');%projection object selected for uvmat plot
4438if IndexObj>1 && ~isequal(IndexObj,IndexObj_1) % do not delete the object used for the uvmat plot
4439    delete_object(IndexObj)
4440end
4441
4442%'DeleteObject': delete a projection object, defined by its index in the Uvmat list or by its graphic handle
4443%------------------------------------------------------------------------
4444% function DeleteObject(hObject)
4445%
4446% INPUT:
4447% hObject: object index (if integer) or handle of the graphic object. If
4448%          hObject is a subobject, the parent object is detected and deleted.
4449
4450function delete_object(IndexObj)
4451
4452huvmat=findobj('tag','uvmat');%handles of the uvmat interface
4453UvData=get(huvmat,'UserData');
4454hlist_object=findobj(huvmat,'Tag','ListObject');%handles of the object list in the uvmat interface
4455list_str=get(hlist_object,'String');%objet list
4456if  ~isempty(UvData) && isfield(UvData, 'ProjObject') && length(UvData.ProjObject)>=IndexObj
4457    if isfield(UvData.ProjObject{IndexObj},'DisplayHandle') && isfield(UvData.ProjObject{IndexObj}.DisplayHandle,'uvmat')
4458        hdisplay=UvData.ProjObject{IndexObj}.DisplayHandle.uvmat;
4459        for iview=1:length(hdisplay)
4460            if ishandle(hdisplay(iview)) && ~isequal(hdisplay(iview),0)
4461                ObjectData=get(hdisplay(iview),'UserData');
4462                if isfield(ObjectData,'SubObject') & ishandle(ObjectData.SubObject)
4463                    delete(ObjectData.SubObject);
4464                end
4465                if isfield(ObjectData,'DeformPoint') & ishandle(ObjectData.DeformPoint)
4466                    delete(ObjectData.DeformPoint);
4467                end
4468                delete(hdisplay(iview))
4469            end
4470            ishandle(hdisplay(iview))
4471        end
4472        for iobj=IndexObj+1:length(UvData.ProjObject)
4473            hdisplay=UvData.ProjObject{iobj}.DisplayHandle.uvmat;
4474            for iview=1:length(hdisplay)
4475                if ishandle(hdisplay(iview)) && ~isequal(hdisplay(iview),0)
4476                    PlotData=get(hdisplay(iview),'UserData');
4477                    PlotData.IndexObj=iobj-1;
4478                    set(hdisplay(iview),'UserData',PlotData);
4479                end
4480            end
4481        end
4482    end
4483    UvData.ProjObject(IndexObj)=[];
4484    if ~isempty(list_str)
4485        list_str(IndexObj)=[];
4486    end
4487end
4488set(huvmat,'UserData',UvData);
4489set(hlist_object,'String',list_str)
4490set(hlist_object,'Value',length(list_str))
4491hlist_object_1=findobj(huvmat,'Tag','ListObject_1');%handles of the first object list in the uvmat interface
4492old_index=get(hlist_object_1,'Value');
4493set(hlist_object_1,'String',list_str)
4494if IndexObj<=old_index
4495    set(hlist_object_1,'Value',old_index-1)
4496end
4497
4498%------------------------------------------------------------------------
4499%------------------------------------------------------------------------
4500%  II - TOOLS FROM THE UPPER MENU BAR
4501%------------------------------------------------------------------------
4502%------------------------------------------------------------------------
4503
4504%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4505% Export  Menu Callbacks
4506%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4507%------------------------------------------------------------------------
4508% --- Executes on button press in Menu/Export/field in workspace.
4509function MenuExportField_Callback(hObject, eventdata, handles)
4510%------------------------------------------------------------------------
4511global Data_uvmat
4512Data_uvmat=get(handles.uvmat,'UserData');
4513evalin('base','global Data_uvmat')%make CurData global in the workspace
4514display('current field :')
4515evalin('base','Data_uvmat') %display CurData in the workspace
4516commandwindow; %brings the Matlab command window to the front
4517
4518%------------------------------------------------------------------------
4519% --- Executes on button press in Menu/Export/extract figure.
4520function MenuExportFigure_Callback(hObject, eventdata, handles)
4521%------------------------------------------------------------------------
4522% huvmat=get(handles.MenuExport,'parent');
4523hfig=figure;
4524copyobj(handles.PlotAxes,hfig);
4525map=colormap(handles.PlotAxes);
4526colormap(map);%transmit the current colormap to the zoom fig
4527colorbar
4528
4529% --------------------------------------------------------------------
4530function MenuExportAxis_Callback(hObject, eventdata, handles)
4531ListFig=findobj(allchild(0),'Type','figure');
4532nb_option=0;
4533menu={};
4534for ilist=1:numel(ListFig)
4535    FigName=get(ListFig(ilist),'name');
4536    if isempty(FigName)
4537        FigName=['figure ' num2str(ListFig(ilist))];
4538    end
4539    if ~strcmp(FigName,'uvmat')
4540        ListAxes=findobj(ListFig(ilist),'Type','axes');
4541        ListTags=get(ListAxes,'Tag');
4542        if ~isempty(ListTags) && ~isempty(find(~strcmp('Colorbar',ListTags), 1))
4543            ListAxes=ListAxes(~strcmp('Colorbar',ListTags));
4544            if numel(ListAxes)==1
4545                nb_option=nb_option+1;
4546                menu{nb_option}=FigName ;
4547                AxesHandle(nb_option)=ListAxes;
4548            else
4549                nb_axis=0;
4550                for iaxes=1:numel(ListAxes)
4551                    nb_axis=nb_axis+1;
4552                    nb_option=nb_option+1;
4553                    menu{nb_option}=[FigName '_' num2str(nb_axis)];
4554                    AxesHandle(nb_option)=ListAxes(nb_axis);
4555                end
4556            end
4557        end
4558    end
4559end
4560if isempty(menu)
4561    answer=msgbox_uvmat('INPUT_Y-N','no existing plotting axes available, create new figure?');
4562    if strcmp(answer,'Yes')
4563        hfig=figure;
4564        copyobj(handles.PlotAxes,hfig);
4565    else
4566        return
4567    end
4568    map=colormap(handles.PlotAxes);
4569    colormap(map);%transmit the current colormap to the zoom fig
4570    colorbar
4571else
4572    answer=msgbox_uvmat('INPUT_MENU','select a figure/axis on which the current uvmat plot will be exported',menu);
4573    if isempty(answer)
4574        return
4575    else
4576        axes(AxesHandle(answer))
4577        hold on
4578        hchild=get(handles.PlotAxes,'children');
4579        copyobj(hchild,gca);
4580    end
4581end
4582
4583
4584%------------------------------------------------------------------------
4585% --------------------------------------------------------------------
4586function MenuExportMovie_Callback(hObject, eventdata, handles)
4587% --------------------------------------------------------------------
4588set(handles.MenuExportMovie,'BusyAction','queue')% activate the button
4589huvmat=get(handles.run0,'parent');
4590UvData=get(huvmat,'UserData');
4591%[xx,xx,FileBase]=read_file_boxes(handles);
4592[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
4593FileBase=fullfile(RootPath,RootFile);
4594 %read the current input file name
4595prompt = {'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)'};
4596dlg_title = 'select properties of the output avi movie';
4597num_lines= 1;
4598def     = {[FileBase '_out.avi'];'10';'1';'[0.03 0.05 0.95 0.92]';'10'};
4599answer = inputdlg(prompt,dlg_title,num_lines,def,'on');
4600aviname=answer{1};
4601fps=str2double(answer{2});
4602% check for existing file with output name aviname
4603if exist(aviname,'file')
4604    backup=aviname;
4605    testexist=2;
4606    while testexist==2
4607        backup=[backup '~'];
4608        testexist=exist(backup,'file');     
4609    end
4610    [success,message]=copyfile(aviname,backup);%make backup of the existing file
4611    if isequal(success,1)
4612        delete(aviname)%delete existing file
4613    else
4614        msgbox_uvmat('ERROR',message)
4615        return
4616    end
4617end
4618%create avi open
4619aviobj=avifile(aviname,'Compression','None','fps',fps);
4620
4621%display first view for tests
4622newfig=figure;
4623newaxes=copyobj(handles.PlotAxes,newfig);%new plotting axes in the new figure
4624set(newaxes,'Tag','movieaxes')
4625nbpix=[512 384]*str2double(answer{3});
4626set(gcf,'Position',[1 1 nbpix])% resolution XVGA
4627set(newaxes,'Position',eval(answer{4}));
4628map=colormap(handles.PlotAxes);
4629colormap(map);%transmit the current colormap to the zoom fig
4630msgbox_uvmat('INPUT_Y-N',{['adjust figure ' num2str(newfig) ' with its matlab edit menu '] ;...
4631        ['then press OK to get the avi movie as a copy of figure ' num2str(newfig) ' display']});
4632UvData.plotaxes=newaxes;% the axis in the new figure becomes the current main plotting axes
4633set(huvmat,'UserData',UvData);
4634increment=str2num(get(handles.num_IndexIncrement,'String')); %get the field increment d
4635set(handles.STOP,'Visible','on')
4636set(handles.speed,'Visible','on')
4637set(handles.speed_txt,'Visible','on')
4638set(handles.Movie,'BusyAction','queue')
4639
4640%imin=str2double(get(handles.i1,'String'));
4641imax=str2double(answer{5});
4642% if isfield(UvData,'Time')
4643htitle=get(newaxes,'Title');
4644xlim=get(newaxes,'XLim');
4645ylim=get(newaxes,'YLim');
4646set(htitle,'Position',[xlim(2)+0.07*(xlim(2)-xlim(1)) ylim(2)-0.05*(ylim(2)-ylim(1)) 0])
4647time_str=get(handles.TimeValue,'String');
4648set(htitle,'String',['t=' time_str])
4649set(handles.speed,'Value',1)
4650for i=1:imax
4651    if get(handles.speed,'Value')~=0 && isequal(get(handles.MenuExportMovie,'BusyAction'),'queue') % enable STOP command
4652            runpm(hObject,eventdata,handles,increment)% run plus
4653            drawnow
4654            time_str=get(handles.TimeValue,'String');
4655            if ishandle(htitle)
4656             set(htitle,'String',['t=' time_str])
4657            end
4658            mov=getframe(newfig);
4659            aviobj=addframe(aviobj,mov);
4660    end
4661end
4662aviobj=close(aviobj);
4663UvData=rmfield(UvData,'plotaxes');
4664set(huvmat,'UserData',UvData);
4665msgbox_uvmat('CONFIRMATION',{['movie ' aviname ' created '];['with ' num2str(imax) ' frames']})
4666
4667
4668%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4669% Projection Objects Menu Callbacks
4670%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4671
4672% -----------------------------------------------------------------------
4673function Menupoints_Callback(hObject, eventdata, handles)
4674%------------------------------------------------------------------------
4675data.Type='points';
4676data.ProjMode='projection';%default
4677data.ProjModeMenu={};% do not restrict ProjMode menus
4678create_object(data,handles)
4679
4680% -----------------------------------------------------------------------
4681% --- Callback of the Menu command line
4682%------------------------------------------------------------------------
4683function Menuline_Callback(hObject, eventdata, handles)
4684%------------------------------------------------------------------------
4685data.Type='line';
4686data.ProjMode='projection';%default
4687data.ProjModeMenu={};% do not restrict ProjMode menus
4688create_object(data,handles)
4689
4690% -----------------------------------------------------------------------
4691% --- Callback of the Menu command line_x
4692%------------------------------------------------------------------------
4693function Menuline_x_Callback(hObject, eventdata, handles)
4694    msgbox_uvmat('ERROR','option not yet implemented, use line')
4695    return
4696data.Type='line_x';
4697data.ProjMode='projection';%default
4698data.ProjModeMenu={};% do not restrict ProjMode menus
4699create_object(data,handles)
4700
4701% -----------------------------------------------------------------------
4702% --- Callback of the Menu command line_y
4703% -----------------------------------------------------------------------
4704function Menuline_y_Callback(hObject, eventdata, handles)
4705    msgbox_uvmat('ERROR','option not yet implemented, use line')
4706    return
4707data.Type='line_y';
4708data.ProjMode='projection';%default
4709data.ProjModeMenu={};% do not restrict ProjMode menus
4710create_object(data,handles)
4711
4712%------------------------------------------------------------------------
4713function Menupolyline_Callback(hObject, eventdata, handles)
4714%------------------------------------------------------------------------
4715data.Type='polyline';
4716data.ProjMode='projection';%default
4717data.ProjModeMenu={};% do not restrict ProjMode menus
4718create_object(data,handles)
4719
4720%------------------------------------------------------------------------
4721function Menupolygon_Callback(hObject, eventdata, handles)
4722%------------------------------------------------------------------------
4723data.Type='polygon';
4724data.ProjMode='inside';%default
4725data.ProjModeMenu={};% do not restrict ProjMode menus
4726create_object(data,handles)
4727
4728%------------------------------------------------------------------------
4729function Menurectangle_Callback(hObject, eventdata, handles)
4730%------------------------------------------------------------------------
4731data.Type='rectangle';
4732data.ProjMode='inside';%default
4733data.ProjModeMenu={};% do not restrict ProjMode menus
4734create_object(data,handles)
4735
4736%------------------------------------------------------------------------
4737function Menuellipse_Callback(hObject, eventdata, handles)
4738%------------------------------------------------------------------------
4739data.Type='ellipse';
4740data.ProjMode='inside';%default
4741data.ProjModeMenu={};% do not restrict ProjMode menus
4742create_object(data,handles)
4743
4744%------------------------------------------------------------------------
4745function MenuMaskObject_Callback(hObject, eventdata, handles)
4746%------------------------------------------------------------------------
4747data.Type='polygon';
4748data.TypeMenu={'polygon'};
4749data.ProjMode='mask_inside';%default
4750data.ProjModeMenu={'mask_inside';'mask_outside'};
4751create_object(data,handles)
4752
4753%------------------------------------------------------------------------
4754function Menuplane_Callback(hObject, eventdata, handles)
4755%------------------------------------------------------------------------
4756data.Type='plane';
4757data.ProjMode='projection';%default
4758data.ProjModeMenu={};% do not restrict ProjMode menus
4759create_object(data,handles)
4760
4761%------------------------------------------------------------------------
4762function Menuvolume_Callback(hObject, eventdata, handles)
4763%------------------------------------------------------------------------
4764data.Type='volume';
4765data.ProjMode='interp_lin';%default
4766data.ProjModeMenu={};
4767% set(handles.create,'Visible','on')
4768% set(handles.create,'Value',1)
4769% VOLUME_Callback(hObject,eventdata,handles)data.ProjModeMenu={};
4770create_object(data,handles)
4771
4772%------------------------------------------------------------------------
4773% --- generic function used for the creation of a projection object
4774function create_object(data,handles)
4775%------------------------------------------------------------------------
4776%% desactivate concurrent tools
4777hgeometry_calib=findobj(allchild(0),'tag','geometry_calib');% search the GUI geometric calibration
4778if ishandle(hgeometry_calib)
4779    hhgeometry_calib=guidata(hgeometry_calib);
4780    set(hhgeometry_calib.edit_append,'Value',0)% desactivate mouse action in geometry_calib
4781end
4782set(handles.CheckEditObject,'Value',0)  %desactivate the object edit mode
4783CheckEditObject_Callback([],[],handles)
4784set(handles.CheckViewObject,'Value',0) % desactivate view_object (new object created)
4785set(handles.CheckZoomFig,'Value',0) %desactivate zoom sub fig
4786set(handles.CheckZoom,'Value',0)    %desactivate the zoom action
4787if ishandle(handles.UVMAT_title)
4788    delete(handles.UVMAT_title)     %delete the initial display of uvmat if no field has been entered yet
4789end
4790
4791%% initiate the new projection object
4792UvData=get(handles.uvmat,'UserData');
4793data.Name=data.Type;% default name=type
4794data.Coord=[0 0]; %default
4795if isfield(UvData,'Field')
4796    Field=UvData.Field;
4797    if isfield(UvData.Field,'CoordMesh')&&~isempty(UvData.Field.CoordMesh)
4798        data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
4799        switch data.Type
4800            case {'line','polyline','points'}
4801                data.RangeY=UvData.Field.CoordMesh;
4802            case 'line_x'
4803                data.RangeX=[UvData.Field.XMin UvData.Field.XMax];
4804                data.RangeY=UvData.Field.CoordMesh;
4805                data.Coord=[0 (UvData.Field.YMin +UvData.Field.YMax)/2];% put line at the middle of the y axis
4806            case 'line_y'
4807                data.RangeY=UvData.Field.CoordMesh;
4808                data.Coord=[(UvData.Field.XMin +UvData.Field.XMax)/2 0];% put line at the middle of the x axis
4809            case {'rectangle','ellipse'}
4810                data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
4811                data.RangeX=UvData.Field.CoordMesh;
4812                data.RangeY=UvData.Field.CoordMesh;
4813            otherwise
4814                data.RangeY=[UvData.Field.YMin UvData.Field.YMax];
4815        end
4816        data.DX=UvData.Field.CoordMesh;
4817        data.DY=UvData.Field.CoordMesh;
4818    end
4819    if isfield(Field,'NbDim')&& isequal(Field.NbDim,3)
4820         data.Coord=[0 0 0]; %default
4821    end
4822    if isfield(Field,'CoordUnit')
4823        data.CoordUnit=Field.CoordUnit;
4824    end
4825end
4826hset_object=set_object(data,handles);% call the GUI set_object
4827hchild=get(hset_object,'children');
4828set(hchild,'enable','on')
4829set(handles.DeleteObject,'Visible','on')% make the object delete button visible
4830
4831%------------------------------------------------------------------------
4832function MenuBrowseObject_Callback(hObject, eventdata, handles)
4833%------------------------------------------------------------------------
4834%get the object file
4835[FileName, PathName, filterindex] = uigetfile( ...
4836       {'*.xml;*.mat', ' (*.xml,*.mat)';
4837       '*.xml',  '.xml files '; ...
4838        '*.mat',  '.mat matlab files '}, ...
4839        'Pick an xml Object file',get(handles.RootPath,'String'));
4840fileinput=[PathName FileName];%complete file name
4841sizf=size(fileinput);
4842if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end
4843
4844%read the file
4845[data,heading]=xml2struct(fileinput);
4846if ~strcmp(heading,'ProjObject')
4847    msgbox_uvmat('WARNING','The xml file does not have the heading ProjObject for projection objects')
4848end
4849[tild,data.Name]=fileparts(FileName);% object name set as file name
4850ListObject=get(handles.ListObject,'String');
4851if ~strcmp(ListObject{end},'')
4852    ListObject=[ListObject;{''}]; %append a blank to the list (if not already done) to indicate the creation of a new object
4853    set(handles.ListObject,'String',ListObject)
4854end
4855IndexObj=length(ListObject);
4856
4857UvData=get(handles.uvmat,'UserData');
4858UvData.ProjObject{IndexObj}=[]; %create a new empty object
4859UvData.ProjObject{IndexObj}.DisplayHandle.uvmat=[]; %no plot handle before plot_field operation
4860UvData.ProjObject{IndexObj}.DisplayHandle.view_field=[]; %no plot handle before plot_field operation
4861set(handles.uvmat,'UserData',UvData)
4862set(handles.ListObject,'Value',IndexObj)
4863hset_object=set_object(data);% call the set_object interface
4864set(get(hset_object,'children'),'enable','on')% enable edit action on elements on GUI set_object
4865set(handles.CheckEditObject,'Value',0); %suppress the object edit mode
4866CheckEditObject_Callback([],[],handles)
4867% set(handles.CheckEditObject,'BackgroundColor',[0.7,0.7,0.7]) 
4868set(handles.DeleteObject,'Visible','on')
4869
4870
4871% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4872% % MenuEdit Callbacks
4873% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4874% %------------------------------------------------------------------------
4875% function MenuEditObject_Callback(hObject, eventdata, handles)
4876% %------------------------------------------------------------------------
4877% set(handles.CheckEditObject,'Value',1)
4878% edit_Callback(hObject, eventdata, handles)
4879%
4880% %------------------------------------------------------------------------
4881% function MenuEditVectors_Callback(hObject, eventdata, handles)
4882% %------------------------------------------------------------------------
4883% set(handles.edit_vect,'Visible','on')
4884% set(handles.edit_vect,'Value',1)
4885% edit_vect_Callback(hObject, eventdata, handles)
4886
4887%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4888% MenuTools Callbacks
4889%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
4890%------------------------------------------------------------------------
4891function MenuCalib_Callback(hObject, eventdata, handles)
4892%------------------------------------------------------------------------
4893
4894UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
4895
4896%suppress competing options
4897set(handles.CheckZoom,'Value',0)
4898set(handles.CheckZoom,'BackgroundColor',[0.7 0.7 0.7])
4899set(handles.ListObject,'Value',1)     
4900% initiate display of GUI geometry_calib
4901data=[]; %default
4902if isfield(UvData,'CoordType')
4903    data.CoordType=UvData.CoordType;
4904end
4905[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
4906FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];
4907set(handles.view_xml,'Backgroundcolor',[1 1 0])%indicate the reading of the current xml file by geometry_calib
4908pos_uvmat=get(handles.uvmat,'Position');
4909pos_cal(1)=pos_uvmat(1)+UvData.OpenParam.PosGeometryCalib(1)*pos_uvmat(3);
4910pos_cal(2)=pos_uvmat(2)+UvData.OpenParam.PosGeometryCalib(2)*pos_uvmat(4);
4911pos_cal(3:4)=UvData.OpenParam.PosGeometryCalib(3:4).* pos_uvmat(3:4);
4912geometry_calib(FileName,pos_cal);% call the geometry_calib interface   
4913set(handles.view_xml,'Backgroundcolor',[1 1 1])%indicate the end of reading of the current xml file by geometry_calib
4914set(handles.MenuCalib,'checked','on')% indicate that MenuCalib is activated, test used by mouse action
4915
4916
4917%-----------------------------------------------------------------------
4918function MenuLIFCalib_Callback(hObject, eventdata, handles)
4919%------------------------------------------------------------------------
4920%% read UvData properties stored on the uvmat interface
4921UvData=get(handles.uvmat,'UserData');
4922if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
4923    XmlData=UvData.XmlData{1};
4924else
4925    msgbox_uvmat('ERROR','geometric calibration needed: use Tools/geometric calibration in the menu bar');
4926    return
4927end
4928
4929%% read lines currently drawn
4930ListObj=UvData.ProjObject;
4931select=zeros(1,numel(ListObj));
4932for iobj=1:numel(ListObj);
4933    if isfield(ListObj{iobj},'Type') && strcmp(ListObj{iobj}.Type,'line')
4934        select(iobj)=1;
4935    end
4936end
4937val=find(select);
4938if numel(val)<2
4939    msgbox_uvmat('ERROR','light rays must be defined by at least two lines created by Projection object/line in the menu bar');
4940    return
4941else
4942    set(handles.ListObject,'Value',val);% show the selected lines on the list
4943    ObjectData=UvData.ProjObject(val);
4944    for iobj=1:length(ObjectData)
4945%         if isfield(ObjectData{iobj},'Coord')
4946            xA(iobj)=ObjectData{iobj}.Coord(1,1);
4947            yA(iobj)=ObjectData{iobj}.Coord(1,2);
4948            xB(iobj)=ObjectData{iobj}.Coord(2,1);
4949            yB(iobj)=ObjectData{iobj}.Coord(2,2);
4950%         end
4951    end
4952end
4953
4954%% find the origin as intersection of the two first lines (see http://www.ahristov.com/tutorial/geometry-games/intersection-lines.html )
4955x1=xA(1);x2=xB(1);
4956x3=xA(2);x4=xB(2);
4957y1=yA(1);y2=yB(1);
4958y3=yA(2);y4=yB(2);
4959D = (x1-x2)*(y3-y4) -(y1-y2)*(x3-x4);
4960if D==0
4961    msgbox_uvmat('ERROR','the two lines are parallel');
4962    return
4963end
4964x0=((x3-x4)*(x1*y2-y1*x2)-(x1-x2)*(x3*y4-y3*x4))/D;
4965y0=((y3-y4)*(x1*y2-y1*x2)-(y1-y2)*(x3*y4-y3*x4))/D;
4966XmlData.Illumination.Origin=[x0 y0];
4967XmlData.PolarCentre=[x0 y0];
4968
4969%% display the current image in polar coordinates with origin at the  illumination source
4970currentdir=pwd; 
4971uvmatpath=fileparts(which('uvmat'));
4972cd(fullfile(uvmatpath,'transform_field'));
4973phys_polar=str2func('phys_polar');
4974cd(currentdir)
4975DataOut=phys_polar(UvData.Field,XmlData);
4976view_field(DataOut);
4977
4978%% use the third line for reference luminosity
4979if numel(val)==3
4980    x_ref=linspace(ObjectData{3}.Coord(1,1),ObjectData{3}.Coord(2,1),10);
4981    y_ref=linspace(ObjectData{3}.Coord(1,2),ObjectData{3}.Coord(2,2),10);
4982    x_ref=x_ref-x0;
4983    y_ref=y_ref-y0;
4984    [theta_ref,r_ref] = cart2pol(x_ref,y_ref);%theta_ref  and r_ref are the polar coordinates of the points on the line
4985    theta_ref=theta_ref*180/pi;
4986    figure
4987    plot(theta_ref,r_ref)
4988    azimuth_ima=linspace(DataOut.AY(1),DataOut.AY(2),size(DataOut.A,1));%profile of x index on the transformed image
4989    dist_source = interp1(theta_ref,r_ref,azimuth_ima);
4990    dist_source_pixel=round(size(DataOut.A,2)*(dist_source-DataOut.AX(1))/(DataOut.AX(2)-DataOut.AX(1)));
4991    line_nan= isnan(dist_source_pixel);
4992    dist_source_pixel(line_nan)=1;
4993    width=20; %number of pixels used for reference
4994    DataOut.A=double(DataOut.A);
4995    Anorm=zeros(size(DataOut.A));
4996    Aval=mean(mean(DataOut.A));
4997    for iline=1:size(DataOut.A,1)
4998        lum(iline)=mean(DataOut.A(iline,dist_source_pixel(iline):dist_source_pixel(iline)+width));
4999        Anorm(iline,:)=uint16(Aval*DataOut.A(iline,:)/lum(iline));
5000    end
5001    lum(line_nan)=NaN;
5002    figure
5003    plot(1:size(DataOut.A,1),lum)
5004end
5005ImaName=regexprep([get(handles.RootFile,'String') get(handles.FileIndex,'String')],'//','');
5006NewImageName=fullfile(get(handles.RootPath,'String'),'polar',[ImaName get(handles.FileExt,'String')]);
5007imwrite(Anorm,NewImageName,'BitDepth',16)
5008
5009%% record the origin in the xml file
5010XmlFileName=find_imadoc(get(handles.RootPath,'String'),get(handles.SubDir,'String'),get(handles.RootFile,'String'),get(handles.FileExt,'String'));
5011answer=msgbox_uvmat('INPUT_Y-N','save the illumination origin in the current xml file?');
5012if strcmp(answer,'Yes')
5013    t=xmltree(XmlFileName); %read the file
5014    title=get(t,1,'name');
5015    if ~strcmp(title,'ImaDoc')
5016        msgbox_uvmat('ERROR','wrong xml file');
5017        return
5018    end
5019    % backup the output file if it already exist, and read it
5020    backupfile=XmlFileName;
5021    testexist=2;
5022    while testexist==2
5023        backupfile=[backupfile '~'];
5024        testexist=exist(backupfile,'file');
5025    end
5026    [success,message]=copyfile(XmlFileName,backupfile);%make backup
5027    if success~=1
5028        errormsg=['errror in xml file backup: ' message];
5029        return
5030    end
5031    uid_illumination=find(t,'ImaDoc/Illumination');
5032    if isempty(uid_illumination)  %if GeometryCalib does not already exists, create it
5033        [t,uid_illumination]=add(t,1,'element','Illumination');
5034    end
5035    uid_origin=find(t,'ImaDoc/Illumination/Origin');
5036    if ~isempty(uid_origin)  %if GeometryCalib does not already exists, create it
5037         t=delete(t,uid_origin);
5038    end
5039    % save the illumination origin
5040    t=struct2xml(XmlData.Illumination,t,uid_illumination);
5041    save(t,XmlFileName);
5042end
5043   
5044
5045
5046%------------------------------------------------------------------------
5047function MenuMask_Callback(hObject, eventdata, handles)
5048%------------------------------------------------------------------------
5049UvData=get(handles.uvmat,'UserData');%read UvData properties stored on the uvmat interface
5050ListObj=UvData.ProjObject;
5051select=zeros(1,numel(ListObj));
5052for iobj=1:numel(ListObj);
5053    if strcmp(ListObj{iobj}.ProjMode,'mask_inside')||strcmp(ListObj{iobj}.ProjMode,'mask_outside')
5054        select(iobj)=1;
5055    end
5056end
5057val=find(select);
5058if isempty(val)
5059    msgbox_uvmat('ERROR','polygons must be first created by Projection object/mask polygon in the menu bar');
5060    return
5061else
5062    set(handles.ListObject,'Value',val);
5063    flag=1;
5064    if ~isfield(UvData.Field,'A')
5065            msgbox_uvmat('ERROR','an image needs to be opened to set the mask size');
5066    return
5067    end
5068    npx=size(UvData.Field.A,2);
5069    npy=size(UvData.Field.A,1);
5070    xi=0.5:npx-0.5;
5071    yi=0.5:npy-0.5;
5072    [Xi,Yi]=meshgrid(xi,yi);
5073        for iobj=1:length(UvData.ProjObject)
5074            ObjectData=UvData.ProjObject{iobj};
5075            if isfield(ObjectData,'ProjMode') &&(isequal(ObjectData.ProjMode,'mask_inside')||isequal(ObjectData.ProjMode,'mask_outside'));
5076                flagobj=1;
5077                testphys=0; %coordinates in pixels by default
5078                if isfield(ObjectData,'CoordUnit') && ~isequal(ObjectData.CoordUnit,'pixel')
5079                    if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'GeometryCalib')
5080                        Calib=UvData.XmlData{1}.GeometryCalib;
5081                        testphys=1;
5082                    end
5083                end
5084                if isfield(ObjectData,'Coord')&& isfield(ObjectData,'Type')
5085                    if isequal(ObjectData.Type,'polygon')
5086                        X=ObjectData.Coord(:,1);
5087                        Y=ObjectData.Coord(:,2);
5088                        if testphys
5089                            pos=[X Y zeros(size(X))];
5090                            if isfield(Calib,'SliceCoord') && length(Calib.SliceCoord)>=3
5091                                if isfield(Calib,'SliceAngle')&&~isequal(Calib.SliceAngle,[0 0 0])
5092                                    om=norm(Calib.SliceAngle);%norm of rotation angle in radians
5093                                    OmAxis=Calib.SliceAngle/om; %unit vector marking the rotation axis
5094                                    cos_om=cos(pi*om/180);
5095                                    sin_om=sin(pi*om/180);
5096                                    pos=cos_om*pos+sin_om*cross(OmAxis,pos)+(1-cos_om)*(OmAxis*pos')*OmAxis;
5097                                end
5098                                pos(:,1)=pos(:,1)+Calib.SliceCoord(1);
5099                                pos(:,2)=pos(:,2)+Calib.SliceCoord(2);
5100                                pos(:,3)=pos(:,3)+Calib.SliceCoord(3);
5101                            end                           
5102                            [X,Y]=px_XYZ(Calib,pos(:,1),pos(:,2),pos(:,3));
5103                        end
5104                        flagobj=~inpolygon(Xi,Yi,X',Y');%=0 inside the polygon, 1 outside
5105                    elseif isequal(ObjectData.Type,'ellipse')
5106                        if testphys
5107                            %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
5108                        end
5109                        RangeX=max(ObjectData.RangeX);
5110                        RangeY=max(ObjectData.RangeY);
5111                        X2Max=RangeX*RangeX;
5112                        Y2Max=RangeY*RangeY;
5113                        distX=(Xi-ObjectData.Coord(1,1));
5114                        distY=(Yi-ObjectData.Coord(1,2));
5115                        flagobj=(distX.*distX/X2Max+distY.*distY/Y2Max)>1;
5116                    elseif isequal(ObjectData.Type,'rectangle')
5117                        if testphys
5118                            %[X,Y]=px_XYZ(Calib,X,Y,0);% TODO:create a polygon boundary and transform to phys
5119                        end
5120                        distX=abs(Xi-ObjectData.Coord(1,1));
5121                        distY=abs(Yi-ObjectData.Coord(1,2));
5122                        flagobj=distX>max(ObjectData.RangeX) | distY>max(ObjectData.RangeY);
5123                    end
5124                    if isequal(ObjectData.ProjMode,'mask_outside')
5125                        flagobj=~flagobj;
5126                    end
5127                    flag=flag & flagobj;
5128                end
5129            end
5130        end
5131%     end
5132    %mask name
5133    RootPath=get(handles.RootPath,'String');
5134    SubDir=get(handles.SubDir,'String');
5135    RootFile=get(handles.RootFile,'String');
5136    if ~isempty(RootFile)&&(isequal(RootFile(1),'/')|| isequal(RootFile(1),'\'))
5137        RootFile(1)=[];
5138    end
5139    list=get(handles.masklevel,'String');
5140    masknumber=num2str(length(list));
5141    maskindex=get(handles.masklevel,'Value');
5142   % mask_name=fullfile_uvmat(RootPath,'',[RootFile '_' masknumber 'mask'],'.png','_1',maskindex);
5143    mask_name=fullfile_uvmat(RootPath,[SubDir '.mask'],'mask','.png','_1',maskindex);
5144    imflag=uint8(255*(0.392+0.608*flag));% =100 for flag=0 (vectors not computed when 20<imflag<200)
5145    imflag=flipdim(imflag,1);
5146
5147    %display the mask
5148    hfigmask=figure;
5149    set(hfigmask,'Name','mask image')
5150    vec=linspace(0,1,256);%define a linear greyscale colormap
5151    map=[vec' vec' vec'];
5152    colormap(map)
5153    image(imflag);
5154    answer=msgbox_uvmat('INPUT_TXT','mask file name:', mask_name);
5155    if ~strcmp(answer,'Cancel')
5156        mask_dir=fileparts(answer);
5157        if ~exist(mask_dir,'dir')
5158            [xx,msg1]=mkdir(mask_dir);
5159            if ~strcmp(msg1,'')
5160                errormsg=['cannot create ' mask_dir ': ' msg1];%error message for directory creation
5161                return
5162            end
5163        end
5164        imwrite(imflag,answer,'BitDepth',8);
5165    end
5166    set(handles.ListObject,'Value',1)
5167end
5168
5169%------------------------------------------------------------------------
5170%-- open the GUI set_grid.fig to create grid
5171function MenuGrid_Callback(hObject, eventdata, handles)
5172%------------------------------------------------------------------------
5173%suppress the other options if grid is chosen
5174set(handles.edit_vect,'Value',0)
5175edit_vect_Callback(hObject, eventdata, handles)
5176% set(handles.CheckEditObject,'BackgroundColor',[0.7 0.7 0.7])
5177set(handles.ListObject,'Value',1)     
5178
5179%prepare display of the set_grid GUI
5180[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
5181FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];
5182UvData=get(handles.uvmat,'UserData');
5183% CoordList=get(handles.TransformName,'String');
5184% val=get(handles.TransformName,'Value');
5185set_grid(FileName,UvData.Field);% call the set_object interface
5186
5187
5188%------------------------------------------------------------------------
5189function MenuRuler_Callback(hObject, eventdata, handles)
5190%------------------------------------------------------------------------
5191set(handles.CheckZoom,'Value',0)
5192CheckZoom_Callback(handles.uvmat, [], handles)
5193set(handles.MenuRuler,'checked','on')
5194UvData=get(handles.uvmat,'UserData');
5195UvData.MouseAction='ruler';
5196set(handles.uvmat,'UserData',UvData);
5197
5198%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5199% MenuRun Callbacks
5200%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
5201
5202%------------------------------------------------------------------------
5203% open the GUI 'series'
5204function MenuSeries_Callback(hObject, eventdata, handles)
5205%------------------------------------------------------------------------
5206Param=read_param(handles);
5207series(Param); %run the series interface
5208
5209% --------------------------------------------------------------------
5210function MenuPIV_Callback(hObject, eventdata, handles)
5211    Param=read_param(handles);
5212%     Param.ActionName='civ_series';
5213hseries=series(Param);
5214hhseries=guidata(hseries);
5215ActionMenu=get(hhseries.ActionName,'String');
5216index_action=find(strcmp('civ_series',ActionMenu));
5217set(hhseries.ActionName,'Value',index_action);
5218series('ActionName_Callback',hObject,eventdata,hhseries); %file input with xml reading  in uvmat, show the image in phys coordinates
5219
5220
5221%------------------------------------------------------------------------
5222% -- open the GUI civ.fig for PIV
5223function MenuCIVx_Callback(hObject, eventdata, handles)
5224%------------------------------------------------------------------------
5225 [RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
5226 FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];
5227civ(FileName);% interface de civ(not in the uvmat file)
5228
5229function Param=read_param(handles)
5230   
5231[RootPath,SubDir,RootFile,FileIndex,FileExt]=read_file_boxes(handles);
5232Param.FileName=[fullfile(RootPath,SubDir,RootFile) FileIndex FileExt];%first input file name
5233if isequal(get(handles.SubField,'Value'),1)
5234    [RootPath_1,SubDir_1,RootFile_1,FileIndex_1,FileExt_1]=read_file_boxes_1(handles);
5235    FileName_1=[fullfile(RootPath_1,SubDir_1,RootFile_1) FileIndex_1 FileExt_1];
5236    if ~isequal(FileName_1,Param.FileName)
5237        Param.FileName_1=FileName_1;%second input file name if relevant
5238    end
5239end
5240Param.NomType=get(handles.NomType,'String');
5241Param.NomType_1=get(handles.NomType_1,'String');
5242Param.CheckFixPair=get(handles.CheckFixPair,'Value');
5243UvData=get(handles.uvmat,'UserData');
5244if isfield(UvData,'XmlData')&& isfield(UvData.XmlData{1},'Time')
5245    Param.Time=UvData.XmlData{1}.Time;
5246end
5247if isequal(get(handles.scan_i,'Value'),1)
5248    Param.incr_i=str2num(get(handles.num_IndexIncrement,'String'));
5249elseif isequal(get(handles.scan_j,'Value'),1)
5250    Param.incr_j=str2num(get(handles.num_IndexIncrement,'String'));
5251end
5252
5253%% transfer fields and coordinate names
5254Param.list_fields=get(handles.FieldName,'String');% list menu fields
5255FieldName=Param.list_fields{get(handles.FieldName,'Value')};
5256ind_image=find(strcmp('image',Param.list_fields));
5257if ~isempty(ind_image) && numel(Param.list_fields)>1
5258    Param.list_fields(ind_image)=[]; %suppress  'image' option
5259end
5260Param.index_fields=find(strcmp(FieldName,Param.list_fields));% selected string index
5261Param.list_fields_1=get(handles.FieldName_1,'String');% list menu fields
5262if ischar(Param.list_fields_1),Param.list_fields_1={Param.list_fields_1};end
5263FieldName_1=Param.list_fields_1{get(handles.FieldName_1,'Value')};
5264ind_image=find(strcmp('image',Param.list_fields_1));
5265if ~isempty(ind_image) && numel(Param.list_fields_1)>1
5266    Param.list_fields_1(ind_image)=[]; %suppress  'image' option
5267end
5268Param.index_fields_1=find(strcmp(FieldName_1,Param.list_fields_1));% selected string index
5269TransformList=get(handles.TransformName,'String');
5270Param.TransformName=TransformList{get(handles.TransformName,'Value')};
5271Param.Coord_x_str=get(handles.Coord_x,'String');
5272Param.Coord_x_val=get(handles.Coord_x,'Value');
5273Param.Coord_y_str=get(handles.Coord_y,'Data');
5274
5275% --------------------------------------------------------------------
5276function MenuHelp_Callback(hObject, eventdata, handles)
5277% --------------------------------------------------------------------
5278web('http://servforge.legi.grenoble-inp.fr/projects/soft-uvmat/wiki/UvmatHelp')
5279
5280% path_to_uvmat=which ('uvmat');% check the path of uvmat
5281% pathelp=fileparts(path_to_uvmat);
5282% helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
5283% 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')
5284% else
5285%     addpath (fullfile(pathelp,'uvmat_doc'))
5286%     web(helpfile);
5287% end
5288
5289% --- Executes on selection change in Coord_y.
5290function Coord_y_Callback(hObject, eventdata, handles)
5291
5292% --- Executes on selection change in Coord_x.
5293function Coord_x_Callback(hObject, eventdata, handles)
5294
5295
5296% --- Executes on button press in CheckColorBar.
5297function CheckColorBar_Callback(hObject, eventdata, handles)
5298
5299
5300
5301function TransformPath_Callback(hObject, eventdata, handles)
5302% hObject    handle to TransformPath (see GCBO)
5303% eventdata  reserved - to be defined in a future version of MATLAB
5304% handles    structure with handles and user data (see GUIDATA)
5305
5306% Hints: get(hObject,'String') returns contents of TransformPath as text
5307%        str2double(get(hObject,'String')) returns contents of TransformPath as a double
5308
5309
5310%TODO: use to modify fill_GUI
5311%'write_plot_param': update the plotting parameters on the uvmat or view_field interface after a plotting operation
5312function write_plot_param(handles,PlotParam)
5313%% coordinates
5314if isempty(PlotParam.Coordinates)
5315    set(handles.Coordinates,'Visible','off')
5316    set(handles.PlotAxes,'Visible','off')
5317    set(handles.text_display,'Visible','off')
5318    set(handles.TableDisplay,'Visible','on')
5319else
5320    set(handles.Coordinates,'Visible','on')
5321    set(handles.PlotAxes,'Visible','on')
5322    set(handles.text_display,'Visible','on')
5323    if isfield(handles,'TableDisplay')
5324    set(handles.TableDisplay,'Visible','off')
5325    end
5326    Coordinates=PlotParam.Coordinates;
5327    if isfield(Coordinates,'CheckFixAspectRatio')
5328        if Coordinates.CheckFixAspectRatio
5329            set(handles.CheckFixAspectRatio,'Value',1)
5330        else
5331            set(handles.CheckFixAspectRatio,'Value',0)
5332 
5333        end
5334    end
5335    if isfield(Coordinates,'AspectRatio')
5336        set(handles.num_AspectRatio,'String',num2str(Coordinates.AspectRatio))
5337    end
5338    if isfield(Coordinates,'MinX')
5339        set(handles.num_MinX,'String',num2str(Coordinates.MinX,4));
5340        set(handles.num_MaxX,'String',num2str(Coordinates.MaxX,4));
5341        set(handles.num_MinY,'String',num2str(Coordinates.MinY,4));
5342        set(handles.num_MaxY,'String',num2str(Coordinates.MaxY,4));
5343    else
5344        set(handles.num_MinX,'String','');
5345        set(handles.num_MaxX,'String','');
5346        set(handles.num_MinY,'String','');
5347        set(handles.num_MaxY,'String','');
5348    end
5349end
5350
5351%% scalar or image parameters
5352if isfield(PlotParam,'Scalar')
5353    set(handles.Scalar,'Visible','on')
5354    if isfield(PlotParam.Scalar,'MaxA')
5355        set(handles.num_MaxA,'String',num2str(PlotParam.Scalar.MaxA,3));
5356    end
5357    if isfield(PlotParam.Scalar,'MinA')
5358        set(handles.num_MinA,'String',num2str(PlotParam.Scalar.MinA,3));
5359    end   
5360    if isfield(PlotParam.Scalar,'IncrA')
5361        set(handles.num_IncrA,'String',num2str(PlotParam.Scalar.IncrA,3))
5362    end
5363    set(handles.CheckBW,'Value',PlotParam.Scalar.CheckBW)
5364    if isfield(PlotParam.Scalar,'Opacity')&&isfield(handles,'num_Opacity')
5365        set(handles.num_Opacity,'String',num2str(PlotParam.Scalar.Opacity))
5366    end
5367else
5368    set(handles.Scalar,'Visible','off')
5369end
5370
5371%% parameter for vector field
5372if isfield(PlotParam,'Vectors')
5373    set(handles.Vectors,'Visible','on')
5374    if isfield(PlotParam.Vectors,'VecScale')
5375        set(handles.num_VecScale,'String',num2str(PlotParam.Vectors.VecScale,3))
5376    end
5377    if isfield(PlotParam.Vectors,'MinC')&& isfield(PlotParam.Vectors,'MaxC')
5378        MinC=PlotParam.Vectors.MinC;
5379        MaxC=PlotParam.Vectors.MaxC;
5380        set(handles.num_MinVec,'String', num2str(MinC,3));
5381        set(handles.num_MaxVec,'String',num2str(MaxC,3));
5382        list=get(handles.ColorCode,'String');
5383        ichoice=get(handles.ColorCode,'Value');
5384        color_option=list{ichoice};
5385        test3color=strcmp(color_option,'rgb')||strcmp(color_option,'bgr');
5386        if test3color% need to update color thresholds
5387            set(handles.num_ColCode1,'Visible','on')
5388            set(handles.num_ColCode2,'Visible','on')
5389            set(handles.Slider1,'Visible','on')
5390            set(handles.Slider2,'Visible','on')
5391            set(handles.num_ColCode1,'String',num2str(PlotParam.Vectors.ColCode1,3))
5392            set(handles.num_ColCode2,'String',num2str(PlotParam.Vectors.ColCode2,3))
5393            set(handles.Slider1,'Value',(PlotParam.Vectors.ColCode1-MinC)/(MaxC-MinC))
5394            set(handles.Slider2,'Value',(PlotParam.Vectors.ColCode2-MinC)/(MaxC-MinC))
5395        else
5396            set(handles.num_ColCode1,'Visible','off')
5397            set(handles.num_ColCode2,'Visible','off')
5398            set(handles.Slider1,'Visible','off')
5399            set(handles.Slider2,'Visible','off')
5400        end
5401    end
5402else
5403    set(handles.Vectors,'Visible','off')
5404    if isfield(handles,'edit_vect')
5405        set(handles.edit_vect,'Visible','off')
5406        set(handles.record,'Visible','off')
5407    end
5408end
Note: See TracBrowser for help on using the repository browser.