source: trunk/src/uvmat.m @ 598

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

various bugs repaired . civ_series further developed

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