source: trunk/src/uvmat.m @ 701

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

several bugs repaired

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