source: trunk/src/uvmat.m @ 710

Last change on this file since 710 was 710, checked in by sommeria, 10 years ago

various improvements.

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