source: trunk/src/uvmat.m @ 690

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

representation of ancillary data as table improved.

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