source: trunk/src/uvmat.m @ 693

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

bug repaired geometry_calib/Detect grid, + corrections in get_field

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