source: trunk/src/uvmat.m @ 606

Last change on this file since 606 was 606, checked in by sommeria, 8 years ago

bug on compilation solved (still to test with transform_field fct). faster browser inrtroduced. Various bug corrections

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