source: trunk/src/uvmat.m @ 709

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

improve check svn with command "&"
improve import config in series

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