source: trunk/src/uvmat.m @ 699

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

mouse indication improved

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