source: trunk/src/uvmat.m @ 671

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

geometry_calib corrected for translation and rotation + cleaning

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