source: trunk/src/uvmat.m @ 674

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

various bugs repaired, in particula timing

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