source: trunk/src/uvmat.m @ 813

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