source: trunk/src/series.m @ 1198

Last change on this file since 1198 was 1197, checked in by sommeria, 3 days ago

bugs repaired

File size: 184.8 KB
Line 
1%'series': master function associated to the GUI series.m for analysis field series
2%------------------------------------------------------------------------
3% function varargout = series(varargin)
4% associated with the GUI series.fig
5%
6%INPUT
7% param: structure with input parameters (link with the GUI uvmat)
8%      .menu_coord_str: string for the TransformName (menu for coordinate transforms)
9%      .menu_coord_val: value for TransformName (menu for coordinate transforms)
10%      .FileName: input file name
11%      .FileName_1: second input file name
12%      .list_field: menu of input fields
13%      .index_fields: chosen index
14%      .civ1=0 or 1, .interp1,  ... : input civ field type
15%
16
17%=======================================================================
18% Copyright 2008-2024, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
19%   http://www.legi.grenoble-inp.fr
20%   Joel.Sommeria - Joel.Sommeria (A) univ-grenoble-alpes.fr
21%
22%     This file is part of the toolbox UVMAT.
23%
24%     UVMAT is free software; you can redistribute it and/or modify
25%     it under the terms of the GNU General Public License as published
26%     by the Free Software Foundation; either version 2 of the license,
27%     or (at your option) any later version.
28%
29%     UVMAT is distributed in the hope that it will be useful,
30%     but WITHOUT ANY WARRANTY; without even the implied warranty of
31%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32%     GNU General Public License (see LICENSE.txt) for more details.
33%=======================================================================
34
35%------------------------------------------------------------------------
36%------------------------------------------------------------------------
37%  I - MAIN FUNCTION series
38%------------------------------------------------------------------------
39%------------------------------------------------------------------------
40function varargout = series(varargin)
41
42% Begin initialization code - DO NOT EDIT
43gui_Singleton = 1;
44gui_State = struct('gui_Name',       mfilename, ...
45                   'gui_Singleton',  gui_Singleton, ...
46                   'gui_OpeningFcn', @series_OpeningFcn, ...
47                   'gui_OutputFcn',  @series_OutputFcn, ...
48                   'gui_LayoutFcn',  [] , ...
49                   'gui_Callback',   []);
50if nargin && ischar(varargin{1})
51    gui_State.gui_Callback = str2func(varargin{1});
52end
53
54if nargout
55    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
56else
57    gui_mainfcn(gui_State, varargin{:});
58end
59% End initialization code - DO NOT EDIT
60
61%--------------------------------------------------------------------------
62% --- Executes just before series is made visible.
63%--------------------------------------------------------------------------
64function series_OpeningFcn(hObject, eventdata, handles,Param)
65
66% Choose default command line output for series
67handles.output = hObject;
68% Update handles structure
69guidata(hObject, handles);
70
71%% initial settings
72% position and  size of the GUI at opening
73set(0,'Unit','points')
74ScreenSize=get(0,'ScreenSize'); % size of the current screen, in points (1/72 inch)
75Width=900; % prefered width of the GUI in points (1/72 inch)
76Height=624; % prefered height of the GUI in points (1/72 inch)
77%adjust to screen size (reduced by a min margin)
78RescaleFactor=min((ScreenSize(3)-80)/Width,(ScreenSize(4)-80)/Height);
79if RescaleFactor>1
80    RescaleFactor=min(RescaleFactor,1);
81end
82Width=Width*RescaleFactor;
83Height=Height*RescaleFactor;
84LeftX=80*RescaleFactor; % position of the left fig side, in pixels (put to the left side, with some margin)
85LowY=round(ScreenSize(4)/2-Height/2); % put at the middle height on the screen
86set(hObject,'Units','points')
87set(hObject,'Position',[LeftX LowY Width Height])% position and size of the GUI at opening
88
89% settings of table MinIndex_j
90set(handles.MinIndex_i,'ColumnFormat',{'numeric'})
91set(handles.MinIndex_i,'ColumnEditable',false)
92set(handles.MinIndex_i,'ColumnName',{'i min'})
93set(handles.MinIndex_i,'Data',[])% initiate Data to double (not cell)
94
95% settings of table MinIndex_j
96set(handles.MinIndex_j,'ColumnFormat',{'numeric'})
97set(handles.MinIndex_j,'ColumnEditable',false)
98set(handles.MinIndex_j,'ColumnName',{'j min'})
99set(handles.MinIndex_j,'Data',[])% initiate Data to double (not cell)
100
101% settings of table MaxIndex_i
102set(handles.MaxIndex_i,'ColumnFormat',{'numeric'})
103set(handles.MaxIndex_i,'ColumnEditable',false)
104set(handles.MaxIndex_i,'ColumnName',{'i max'})
105set(handles.MaxIndex_i,'Data',[])% initiate Data to double (not cell)
106
107% settings of table MaxIndex_j
108set(handles.MaxIndex_j,'ColumnFormat',{'numeric'})
109set(handles.MaxIndex_j,'ColumnEditable',false)
110set(handles.MaxIndex_j,'ColumnName',{'j max'})
111set(handles.MaxIndex_j,'Data',[])% initiate Data to double (not cell)
112
113% settings of table PairString
114set(handles.PairString,'ColumnName',{'pairs'})
115set(handles.PairString,'ColumnEditable',false)
116set(handles.PairString,'ColumnFormat',{'char'})
117set(handles.PairString,'Data',{''})
118
119% settings of table MaskTable
120%set(handles.MaskTable,'ColumnName',{'mask name'})
121set(handles.PairString,'ColumnEditable',false)
122set(handles.PairString,'ColumnFormat',{'char'})
123set(handles.PairString,'Data',{''})
124
125series_ResizeFcn(hObject, eventdata, handles)%resize table according to series GUI size
126set(hObject,'WindowButtonDownFcn',{'mouse_down'})%allows mouse action with right button (zoom for uicontrol display)
127set(hObject,'DeleteFcn',{@closefcn})%
128
129% check default input data
130if ~exist('Param','var')
131    Param=[]; % default
132end
133
134%% Read the parameter file series.xml containing general parameters for the GUI series, or read series.xml.default if it does not exist
135SeriesData=[];
136path_series=fileparts(which('series'));% path to the GUI series
137xmlfile=fullfile(path_series,'series.xml');
138if ~exist(xmlfile,'file')
139    [success,message]=copyfile(fullfile(path_series,'series.xml.default'),xmlfile);
140    if success==0
141        disp(message)
142        return
143    end
144end
145if exist(xmlfile,'file')
146    SeriesData=xml2struct(xmlfile);% read the xml file containing parameters for series computations
147    if ~(isfield(SeriesData,'ClusterParam')&& isfield(SeriesData.ClusterParam,'LaunchCmdFcn'))
148        [success,message]=copyfile(xmlfile,fullfile(path_series,'series.xml~'));% backup the file series.xml, not correctly documented
149        delete(xmlfile);
150        [success,message]=copyfile(fullfile(path_series,'series.xml.default'),xmlfile);% use the defualt series.xml
151    end
152    SeriesData=xml2struct(xmlfile);% read again the xml file containing parameters for series computations
153end
154
155%% list of builtin functions in the menu ActionName
156ActionList={'check_data_files';'aver_stat';'time_series';'civ_series';'merge_proj'}; % WARNING: fits with nb_builtin_ACTION=4 in ActionName_callback
157NbBuiltinAction=numel(ActionList);
158set(handles.Action,'UserData',NbBuiltinAction)
159%path_series_fct=fullfile(path_series,'series');%path of the functions in subdirectroy 'series'
160[path_series]=fileparts(which('series')); % path to the GUI series
161path_series_fct=fullfile(path_series,'series'); % path of the functions in subdirectroy 'series'
162ActionExtList={'.m';'.sh';'fluidimage'}; % default choice of extensions (Matlab fct .m or compiled version .sh
163ActionPathList=cell(NbBuiltinAction,1); % initiate the cell matrix of Action fct paths
164ActionPathList(:)={path_series_fct}; % set the default path to series fcts to all list members
165RunModeList={'local';'background'}; % default choice of extensions (Matlab fct .m or compiled version .sh)
166if isfield(SeriesData.ClusterParam, 'ExistenceTest')
167    oarcommand=SeriesData.ClusterParam.ExistenceTest;
168    s=system(oarcommand); % look for cluster system presence
169    if isequal(s,0)% cluster detected
170        RunModeList=[RunModeList;{'cluster'}];
171        set(handles.MonitorCluster,'Visible','on'); % make visible button for access to Monika
172        set(handles.num_CPUTime,'Visible','on'); % make visible button for CPU time estimate for one ref index
173        set(handles.num_CPUTime,'String','')% default CPU time undefined
174        set(handles.CPUTime_txt,'Visible','on'); % make visible button for CPU time title
175    end
176    set(handles.RunMode,'String',RunModeList)% display the menu of available run modes, local, background or cluster manager
177else
178    disp('no cluster availability test in series.xml')
179end
180
181
182%% list of builtin transform functions in the menu TransformName
183TransformList={'';'sub_field';'phys';'phys_polar'}; % WARNING: must fit with the corresponding menu in uvmat and nb_builtin_transform=4 in  TransformName_callback
184NbBuiltinTransform=numel(TransformList);
185path_transform_fct=fullfile(path_series,'transform_field');
186TransformPathList=cell(NbBuiltinTransform,1); % initiate the cell matrix of Action fct paths
187TransformPathList(:)={path_transform_fct}; % set the default path to series fcts to all list members
188SeriesData.TransformPath=path_transform_fct;% store the standard path for trqnsform functions (needed for compilation)
189
190%% get the user defined functions stored in the personal file uvmat_perso.mat
191dir_perso=prefdir;
192profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
193if exist(profil_perso,'file')
194    h=load (profil_perso);
195    %get the list of previous input files in the upper bar menu Open
196    if isfield(h,'MenuFile')
197        for ifile=1:min(length(h.MenuFile),5)
198            set(handles.(['MenuFile_' num2str(ifile)]),'Label',h.MenuFile{ifile});
199            set(handles.(['MenuFile_' num2str(ifile+5)]),'Label',h.MenuFile{ifile});
200        end
201    end
202    %get the menu of actions
203    if isfield(h,'ActionListUser') && iscell(h.ActionListUser) && isfield(h,'ActionPathListUser') && iscell(h.ActionPathListUser)
204        ActionList=[ActionList;h.ActionListUser];
205        ActionPathList=[ActionPathList;h.ActionPathListUser(:,1)];
206    end
207    %get the menu of transform fct
208    if isfield(h,'TransformListUser') && iscell(h.TransformListUser) && isfield(h,'TransformPathListUser') && iscell(h.TransformPathListUser)
209        TransformList=[TransformList;h.TransformListUser];
210        TransformPathList=[TransformPathList;h.TransformPathListUser];
211    end
212end
213
214%% selection of the input Action fct
215ActionCheckExist=true(size(ActionList)); % initiate the check of the path to the listed action fct
216for ilist=NbBuiltinAction+1:numel(ActionList)%check  the validity of the path of the user defined Action fct
217    ActionCheckExist(ilist)=exist(fullfile(ActionPathList{ilist},[ActionList{ilist} '.m']),'file');
218end
219ActionPathList=ActionPathList(ActionCheckExist,:); % suppress the menu options which are not valid anymore
220ActionList=ActionList(ActionCheckExist);
221set(handles.ActionName,'String',[ActionList;{'more...'}])
222set(handles.ActionName,'UserData',ActionPathList)
223ActionIndex=[];
224if isfield(Param,'ActionName')% copy the selected menu index transferred in Param from uvmat
225    ActionIndex=find(strcmp(Param.ActionName,ActionList),1);
226end
227if isempty(ActionIndex)
228    ActionIndex=1;
229end
230set(handles.ActionName,'Value',ActionIndex)
231set(handles.ActionPath,'String',ActionPathList{ActionIndex})
232set(handles.ActionExt,'Value',1)
233set(handles.ActionExt,'String',ActionExtList)
234
235%% selection of the input transform fct
236TransformCheckExist=true(size(TransformList));
237for ilist=NbBuiltinTransform+1:numel(TransformList)
238    TransformCheckExist(ilist)=exist(fullfile(TransformPathList{ilist},[TransformList{ilist} '.m']),'file');
239end
240TransformPathList=TransformPathList(TransformCheckExist);
241TransformList=TransformList(TransformCheckExist);
242set(handles.TransformName,'String',[TransformList;{'more...'}])
243set(handles.TransformName,'UserData',TransformPathList)
244TransformIndex=[];
245if isfield(Param,'TransformName')% copy the selected menu index transferred in Param from uvmat
246    TransformIndex=find(strcmp(Param.TransformName,TransformList),1);
247end
248if isempty(TransformIndex)
249    TransformIndex=1;
250end
251set(handles.TransformName,'Value',TransformIndex)
252set(handles.TransformPath,'String',TransformPathList{TransformIndex})
253
254%% fields input initialisation
255if isfield(Param,'list_fields')&& isfield(Param,'index_fields') &&~isempty(Param.list_fields) &&~isempty(Param.index_fields)
256    set(handles.FieldName,'String',Param.list_fields); % list menu fields
257    set(handles.FieldName,'Value',Param.index_fields); % selected string index
258end
259if isfield(Param,'Coordinates')
260    if isfield(Param.Coordinates,'Coord_x')
261        set(handles.Coord_x,'String',Param.Coordinates.Coord_x)
262    end
263    if isfield(Param.Coordinates,'Coord_y')
264        set(handles.Coord_y,'String',Param.Coordinates.Coord_y)
265    end
266    if isfield(Param.Coordinates,'Coord_z')
267        set(handles.Coord_z,'String',Param.Coordinates.Coord_z)
268    end
269end
270
271%% introduce the input file name(s) if defined from input Param,
272set(handles.series,'UserData',SeriesData)% initiate Userdata
273if isfield(Param,'InputFile')
274
275    %% fill the list of input file series
276    InputTable=[{Param.InputFile.RootPath},{Param.InputFile.SubDir},{Param.InputFile.RootFile},{Param.InputFile.NomType},{Param.InputFile.FileExt}];
277    if isempty(find(cellfun('isempty',InputTable)==0,1)) % if there is no input file, do not introduce input info
278        set(handles.REFRESH,'BackgroundColor',[1 0 1])% set REFRESH button to magenta color to indicate that input refresh is needed
279        return
280    end
281    % TimeTable=[{Param.InputFile.TimeName},{[]},{[]},{[]},{[]}];
282    if isfield(Param.InputFile,'RootPath_1')
283        InputTable=[InputTable;[{Param.InputFile.RootPath_1},{Param.InputFile.SubDir_1},{Param.InputFile.RootFile_1},{Param.InputFile.NomType_1},{Param.InputFile.FileExt_1}]];
284        % TimeTable=[TimeTable; [{Param.InputFile.TimeName_1},{[]},{[]},{[]},{[]}]];
285    end
286    set(handles.InputTable,'Data',InputTable)
287
288    %% define the default path for the output files
289    [InputPath,Device,DeviceExt]=fileparts(InputTable{1,1});
290    [InputPath,Experiment,ExperimentExt]=fileparts(InputPath);
291    set(handles.Device,'String',[Device DeviceExt])
292    set(handles.Experiment,'String',[Experiment ExperimentExt])
293    if ~isempty(regexp(InputTable{1,1},'(^http://)|(^https://)','once'))
294        set(handles.OutputPathBrowse,'Value',1)% an output folder needs to be specified for OpenDAP data
295    end
296
297    %update the output path if needed
298    if ~(isfield(SeriesData,'InputPath') && strcmp(SeriesData.InputPath,InputPath))
299        if get(handles.OutputPathBrowse,'Value')==1  % fix the output path in manual mode
300            OutputPathOld=get(handles.OutputPath,'String');
301            OutputPath=uigetdir(OutputPathOld,'pick a root folder for output data');
302            set(handles.OutputPath,'String',OutputPath)
303        else %reproduce the input path for output
304            set(handles.OutputPath,'String',InputPath)
305        end
306    end
307
308    %% determine the selected reference field indices for pair display
309
310  %  [~,~,~,i1,i2,j1,j2]=fileparts_uvmat(Param.InputFile.FileIndex);
311  i1=1;j1=1;i2=[];j2=[];%default
312    if isfield(Param,'i1')
313        i1=Param.i1;
314    end
315    if isfield(Param,'j1')
316        j1=Param.j1;
317    end
318    if isfield(Param,'i2')
319        i2=Param.i2;
320    end
321    if isfield(Param,'j2')
322        j2=Param.j2;
323    end
324    ref_i=i1;%default
325    if ~isempty(i2)
326    ref_i=floor((i1+i2)/2); % reference image number corresponding to the file
327    end
328    % set(handles.num_ref_i,'String',num2str(ref_i));
329    if isempty(j1)
330        j1=1;
331    end
332    if isempty(j2)
333        j2=j1;
334    end
335    ref_j=floor((j1+j2)/2); % reference image number corresponding to the file
336    SeriesData.ref_i=ref_i;
337    SeriesData.ref_j=ref_j;
338    set(handles.series,'UserData',SeriesData)
339    Param.XmlData_1=[];XmlData_2=[];
340    if isfield(Param.HiddenData,'XmlData')
341            Param.XmlData=Param.HiddenData.XmlData{1};
342    end
343    Param.i1_series=Param.HiddenData.i1_series{1};
344    Param.i2_series=Param.HiddenData.i2_series{1};
345    Param.j1_series=Param.HiddenData.j1_series{1};
346    Param.j2_series=Param.HiddenData.j2_series{1};
347    Param.FileInfo=Param.HiddenData.FileInfo{1};
348    Param.Relabel=[];%default
349    update_rootinfo(handles,Param,Param.HiddenData.MovieObject{1},1)% update the data for the first input line
350    if isfield(Param,'FileName_1')% if there is a second input line from uvmat
351        if isfield(Param.HiddenData,'XmlData') && numel(Param.HiddenData.XmlData)>=2
352            Param.XmlData=Param.HiddenData.XmlData{1};
353        end
354        Param.i1_series=Param.HiddenData.i1_series{2};
355        Param.i2_series=Param.HiddenData.i2_series{2};
356        Param.j1_series=Param.HiddenData.j1_series{2};
357        Param.j2_series=Param.HiddenData.j2_series{2};
358        Param.FileInfo=Param.HiddenData.FileInfo{2};
359        update_rootinfo(handles,Param,Param.HiddenData.MovieObject{2},2)% update the data for the second input line
360    end
361
362    %% enable field and veltype menus, in accordance with the current action
363    ActionName_Callback([],[], handles)
364
365%     %% set length of waitbar
366%     displ_time(handles)
367
368else
369    set(handles.REFRESH,'BackgroundColor',[1 0 1])% set REFRESH button to magenta color to indicate that input refresh is needed
370end
371if isfield(Param,'incr_i')
372    set(handles.num_incr_i,'String',num2str(Param.incr_i))
373else
374    set(handles.num_incr_i,'String','1')
375end
376if isfield(Param,'incr_j')
377    set(handles.num_incr_j,'String',num2str(Param.incr_j))
378else
379    set(handles.num_incr_j,'String','1')
380end
381
382%------------------------------------------------------------------------
383% --- Outputs from this function are returned to the command line.
384function varargout = series_OutputFcn(hObject, eventdata, handles)
385%------------------------------------------------------------------------
386varargout{1} = handles.output;
387
388%------------------------------------------------------------------------
389% --- executed when closing uvmat: delete or desactivate the associated figures if exist
390function closefcn(gcbo,eventdata)
391%------------------------------------------------------------------------
392
393% delete set_object_series if detected
394hh=findobj(allchild(0),'name','view_object_series');
395if ~isempty(hh)
396    delete(hh)
397end
398hh=findobj(allchild(0),'name','edit_object_series');
399if ~isempty(hh)
400    delete(hh)
401end
402
403%delete the bowser if detected
404hh=findobj(allchild(0),'tag','browser');
405if ~isempty(hh)
406    delete(hh)
407end
408
409
410%------------------------------------------------------------------------
411%------------------------------------------------------------------------
412%  II - FUNCTIONS FOR INTRODUCING THE INPUT FILES
413% automatically sets the global properties when the rootfile name is introduced
414% then activate the view-field actionname if selected
415% it is activated either by clicking on the RootPath window or by the
416% browser
417%------------------------------------------------------------------------
418%------------------------------------------------------------------------
419% --- fct activated by the browser under 'Open'
420%------------------------------------------------------------------------
421function MenuBrowse_Callback(hObject, eventdata, handles)
422%% look for the previously opened file 'oldfile'
423InputTable=get(handles.InputTable,'Data');
424oldfile=InputTable{1,1};
425if isempty(oldfile)
426    % use a file name stored in prefdir
427    dir_perso=prefdir;
428    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
429    if exist(profil_perso,'file')
430        h=load (profil_perso);
431        if isfield(h,'RootPath') && ischar(h.RootPath)
432            oldfile=h.RootPath;
433        end
434    end
435end
436%% launch the browser
437fileinput=uigetfile_uvmat('pick an input file in the series',oldfile);
438hh=dir(fileinput);
439if numel(hh)>1
440    msgbox_uvmat('ERROR','invalid input, probably a broken link');
441else
442    if ~isempty(fileinput)
443        display_file_name(handles,fileinput,'one')
444    end
445end
446
447% --------------------------------------------------------------------
448function MenuBrowseAppend_Callback(hObject, eventdata, handles)
449
450%% look for the previously opened file 'oldfile'
451InputTable=get(handles.InputTable,'Data');
452RootPathCell=InputTable(:,1);
453if isempty(RootPathCell{1})% no input file in the table
454     MenuBrowse_Callback(hObject, eventdata, handles)%refresh the input table, not append
455     return
456end
457SubDirCell=InputTable(:,2);
458oldfile=fullfile(RootPathCell{1},SubDirCell{1});
459
460%% use a file name stored in prefdir
461dir_perso=prefdir;
462profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
463if exist(profil_perso,'file')
464    h=load (profil_perso);
465    if isfield(h,'RootPath') && ischar(h.RootPath)
466        oldfile=h.RootPath;
467    end
468end
469
470%% launch the browser
471fileinput=uigetfile_uvmat('pick a file to append in the input table',oldfile);
472hh=dir(fileinput);
473if numel(hh)>1
474    msgbox_uvmat('ERROR','invalid input, probably a broken link');
475else
476    if ~isempty(fileinput)
477        display_file_name(handles,fileinput,'append')
478    end
479end
480
481%------------------------------------------------------------------------
482% --- fct activated by selecting a previous file under the menu Open
483%------------------------------------------------------------------------
484function MenuFile_Callback(hObject, eventdata, handles)
485
486errormsg=display_file_name(handles,get(hObject,'Label'),'one');
487if ~isempty(errormsg)
488    set(hObject,'Label','')
489    MenuFile=[{get(handles.MenuFile_1,'Label')};{get(handles.MenuFile_2,'Label')};...
490        {get(handles.MenuFile_3,'Label')};{get(handles.MenuFile_4,'Label')};{get(handles.MenuFile_5,'Label')}];
491    str_find=strcmp(get(hObject,'Label'),MenuFile);
492    MenuFile(str_find)=[]; % suppress the input file to the list
493    for ifile=1:numel(MenuFile)
494        set(handles.(['MenuFile_' num2str(ifile)]),'Label',MenuFile{ifile});
495    end
496end
497
498%------------------------------------------------------------------------
499% --- fct activated by selecting a previous file under the menu Open/append
500%------------------------------------------------------------------------
501function MenuFile_append_Callback(hObject, eventdata, handles)
502
503InputTable=get(handles.InputTable,'Data');
504if isempty(InputTable{1,1})% no input file in the table
505    display_file_name(handles,get(hObject,'Label'),'one') %refresh the input table, not append
506else
507    display_file_name(handles,get(hObject,'Label'),'append')% append the selected file to the current list of InputTable
508end
509
510%------------------------------------------------------------------------
511% --- fct activated by the browser under 'Open campaign/Browse...'
512%------------------------------------------------------------------------
513function MenuBrowseCampaign_Callback(hObject, eventdata, handles)
514
515%% look for the previously opened file 'oldfile'
516InputTable=get(handles.InputTable,'Data');
517if ~isempty(InputTable)
518oldfile=[InputTable{1,1} InputTable{1,2}];
519else
520    % use a file name stored in prefdir
521    dir_perso=prefdir;
522    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
523    if exist(profil_perso,'file')
524        h=load (profil_perso);
525        if isfield(h,'MenuCampaign') && ~isempty(h.MenuCampaign)&& ischar(h.MenuCampaign{1})
526            oldfile=h.MenuCampaign{1};
527        end
528    end
529end
530InputTable{1,1}='...';
531set(handles.InputTable,'Data',InputTable)
532browse_data(oldfile,'on','on'); % open the GUI browse_data to get select a campaign dir, experiment and device
533
534
535
536% --- Executes when selected cell(s) is changed in InputTable.
537function InputTable_CellSelectionCallback(hObject, eventdata, handles)
538iline=[];
539if ~isempty(eventdata.Indices)
540    iline=eventdata.Indices(1);
541end
542set(handles.InputLine,'String',num2str(iline));
543
544%------------------------------------------------------------------------
545% --- 'key_press_fcn:' function activated when a key is pressed on the keyboard
546%------------------------------------------------------------------------
547function InputTable_KeyPressFcn(hObject, eventdata, handles)
548set(handles.REFRESH,'BackgroundColor',[1 0 1])% set REFRESH button to magenta color to indicate that input refresh is needed
549set(handles.OutputSubDir,'BackgroundColor',[1 0 1])% set edit box OutputSubDir to magenta color to indicate that refresh may be needed
550xx=double(get(handles.series,'CurrentCharacter')); % get the keyboard character
551if ~isempty(xx)
552    switch xx
553        case 31 %downward arrow
554            InputTable=get(handles.InputTable,'Data');
555            iline=str2double(get(handles.InputLine,'String'));
556            if isequal(iline,size(InputTable,1))% arrow downward
557                InputTable=[InputTable;InputTable(iline,:)]; % create a new line as a copy of the last one
558                set(handles.InputTable,'Data',InputTable);
559            end
560        case 127  %key 'Suppress'
561            ClearLine_Callback(hObject, eventdata, handles)
562    end
563end
564
565%------------------------------------------------------------------------
566% --- Executes on button press in REFRESH.
567function REFRESH_Callback(hObject, eventdata, handles)
568%------------------------------------------------------------------------
569CheckRelabel=get(handles.Relabel,'Value');
570check_input_file_series(handles,CheckRelabel)
571
572%% enable field and veltype menus, in accordance with the current action
573ActionInput_Callback([],[], handles)
574
575%------------------------------------------------------------------------
576% --- check the input file series.
577function check_input_file_series(handles,CheckRelabel)
578%------------------------------------------------------------------------
579InputTable=get(handles.InputTable,'Data');%read the table of input file series
580set(handles.series,'Pointer','watch') % set the mouse pointer to 'watch'
581set(handles.REFRESH,'BackgroundColor',[1 1 0])% set REFRESH  button to yellow color (indicate activation)
582set(handles.Relabel,'BackgroundColor',[0 1 0])
583drawnow
584empty_line=false(size(InputTable,1),1);
585for iline=1:size(InputTable,1)
586    empty_line(iline)= isempty(cell2mat(InputTable(iline,1:3)));%check the empty lines in the input table
587end
588if ~isempty(find(empty_line,1))%removes the empty lines in the table
589    InputTable(empty_line,:)=[]; % remove empty lines
590    set(handles.InputTable,'Data',InputTable)
591    ListTable={'MinIndex_i','MaxIndex_i','MinIndex_j','MaxIndex_j','PairString','TimeTable'};
592    for ilist=1:numel(ListTable)
593        Table=get(handles.(ListTable{ilist}),'Data');
594        Table(empty_line,:)=[]; % remove empty lines
595        set(handles.(ListTable{ilist}),'Data',Table);
596    end
597    set(handles.series,'UserData',[])%refresh the stored info
598end
599nbview=size(InputTable,1);
600CheckRelabelQuest=false;
601for iview=1:nbview
602    RootPath=fullfile(InputTable{iview,1},InputTable{iview,2});
603    Param.Relabel=false;
604    MovieObject=[];
605    Param.FileInfo=[];
606    if ~exist(RootPath,'dir')
607        Param.i1_series=[];
608        RootFile='';
609    else
610        [XmlFileName,Rank]=find_imadoc(InputTable{iview,1},InputTable{iview,2});
611        if ~isempty(XmlFileName)
612            XmlData=read_imadoc(XmlFileName);
613            if  Rank==0 && ~isempty(XmlData.FileSeries)
614                set(handles.Relabel,'Visible','on')
615                answer='Yes';
616                if ~CheckRelabel && ~CheckRelabelQuest% propose to relabel if not selected yet
617                    answer=msgbox_uvmat('INPUT_Y-N','relabel the frame  indices according to the xml info?');
618                    CheckRelabelQuest=true;
619                end
620                if strcmp(answer,'Yes')
621                    set(handles.Relabel,'Value',1)
622                    NomType='*';
623                    i1=1;i2=[];j1=1;j2=[];
624                    Param.i1_series=1:size(XmlData.Time,1)-1;
625                    Param.i2_series=[];
626                    if size(XmlData.Time,2)>2
627                        Param.j1_series=1:size(XmlData.Time,2)-1;
628                    else
629                        Param.j1_series=[];
630                    end
631                    Param.j2_series=[];
632                    Param.Relabel=true;
633                    FirstFile=fullfile(InputTable{iview,1},InputTable{iview,2},XmlData.FileSeries.FileName{1});
634                    if ~exist(FirstFile,'file')
635                        msgbox_uvmat('ERROR',[FirstFile ' does not exist']);
636                        return
637                    end
638                    [Param.FileInfo,VideoObject]=get_file_info(FirstFile);
639                else
640                    set(handles.Relabel,'Value',0)
641                end
642            end
643            Param.XmlData=XmlData;
644        end
645    end
646    if ~Param.Relabel
647        %scan the input folder
648        InputTable{iview,3}=regexprep(InputTable{iview,3},'^/','');%suppress '/' at the beginning of the input name
649        i1=str2double(get(handles.num_first_i,'String'));
650        j1=str2double(get(handles.num_first_j,'String'));
651        j2=[];%default
652%         PairString=get(handles.PairString,'Data');
653%         if numel(PairString)>=iview
654%             r=regexp(PairString{iview},'(?<num1>\d+)-(?<num2>\d+)' ,'names');
655%             if ~isempty(r)
656%                 j1=str2double(r.num1);
657%                 j2=str2double(r.num2);
658%             end
659%         end
660 InputFile=[InputTable{iview,3} InputTable{iview,4} InputTable{iview,5}];
661        %InputFile=fullfile_uvmat('','',InputTable{iview,3},InputTable{iview,5},InputTable{iview,4},i1,[],j1,j2);
662        [RootPath,~,RootFile,Param.i1_series,Param.i2_series,Param.j1_series,Param.j2_series,~,Param.FileInfo,MovieObject]=...
663            find_file_series(fullfile(InputTable{iview,1},InputTable{iview,2}),InputFile);
664    end
665
666    % if no file is found on line #ivew, open a browser
667    if ~Param.Relabel && isempty(RootFile)&& isempty(Param.i1_series)
668        fileinput=uigetfile_uvmat(['wrong input at line ' num2str(iview) ':pick a new input file'],RootPath);
669        if isempty(fileinput)
670            set(handles.REFRESH,'BackgroundColor',[1 0 0])% set REFRESH  back to red color
671            return
672        else
673            display_file_name(handles,fileinput,iview)% update the table of input file series, then call update_rootinfo
674        end
675    else
676        update_rootinfo(handles,Param,MovieObject,iview)
677    end
678end
679
680%% update MinIndex_i and MaxIndex_i if the input table content has been reduced in line nbre
681MinIndex_i_table=get(handles.MinIndex_i,'Data'); % retrieve the min indices in the table MinIndex
682set(handles.MinIndex_i,'Data',MinIndex_i_table(1:nbview,:));
683MinIndex_j_table=get(handles.MinIndex_j,'Data'); % retrieve the min indices in the table MinIndex
684set(handles.MinIndex_j,'Data',MinIndex_j_table(1:nbview,:));
685MaxIndex_i_table=get(handles.MaxIndex_i,'Data'); % retrieve the min indices in the table MinIndex
686
687set(handles.MaxIndex_i,'Data',MaxIndex_i_table(1:nbview,:));
688MaxIndex_j_table=get(handles.MaxIndex_j,'Data'); % retrieve the min indices in the table MinIndex
689set(handles.MaxIndex_j,'Data',MaxIndex_j_table(1:nbview,:));
690PairString=get(handles.PairString,'Data'); % retrieve the min indices in the table MinIndex
691set(handles.PairString,'Data',PairString(1:nbview,:));
692TimeTable=get(handles.TimeTable,'Data'); % retrieve the min indices in the table MinIndex
693set(handles.TimeTable,'Data',TimeTable(1:nbview,:));
694
695
696set(handles.REFRESH,'BackgroundColor',[1 0 0])% set REFRESH  button to red color (indicate activation finished)
697set(handles.series,'Pointer','arrow') % set the mouse pointer to 'watch'
698
699
700
701%------------------------------------------------------------------------
702% --- Function called when a new file is opened, either by series_OpeningFcn or by the browser
703%------------------------------------------------------------------------
704% INPUT:
705% handles: handles of elements in the GUI
706% InputFile: (full) input file name, including  path
707% iview: line index in the input table
708%       or 'one': refresh the list
709%         'append': add a new line to the input table
710function errormsg=display_file_name(handles,InputFile,iview)
711
712set(handles.REFRESH,'BackgroundColor',[1 1 0])% set REFRESH  button to yellow color (indicate activation)
713drawnow
714errormsg=''; % default
715
716
717%% get the input root name, indices, file extension and nomenclature NomType
718if isempty(regexp(InputFile,'^http', 'once')) && ~exist(InputFile,'file')
719    errormsg=['input file ' InputFile  ' does not exist'];
720    msgbox_uvmat('ERROR',errormsg)
721    set(handles.REFRESH,'BackgroundColor',[1 0 1])% set REFRESH  button to magenta color (refresh still needed)
722    return
723end
724
725%% Check the nature of the input file
726[FileInfo,MovieObject]=get_file_info(InputFile);
727CheckOpen=false;
728switch FileInfo.FileType
729    case 'txt'%text input file
730        CheckOpen=true;
731        edit(InputFile)
732    case 'xml'%xml input file
733        CheckOpen=true;
734        editxml(InputFile)
735    case 'figure'%Matlab figure
736        CheckOpen=true;
737        open(InputFile)
738end
739if CheckOpen
740    set(handles.REFRESH,'BackgroundColor',[1 0 1])% set REFRESH  button to magenta  color (end of activation)
741    return
742end
743Param.FileInfo=FileInfo;
744
745%% Look for file relabeling option
746[FilePath,RootFile,FileExt]=fileparts(InputFile);
747[RootPath,SubDir,SubDirExt]=fileparts(FilePath);
748[XmlFileName,Rank]=find_imadoc(RootPath,[SubDir SubDirExt]);
749Param.Relabel=false;%no file relabeling by default
750XmlData=[];
751if ~isempty(XmlFileName)
752    XmlData=read_imadoc(XmlFileName);
753    if isfield(XmlData,'FileSeries') && Rank==0
754        set(handles.Relabel,'Visible','on')
755        answer=msgbox_uvmat('INPUT_Y-N','relabel the frame  indices according to the xml info?');
756        if strcmp(answer,'Yes')
757            set(handles.Relabel,'Value',1)
758            NomType='*';
759            i1=1;i2=[];j1=1;j2=[];
760            Param.i1_series=1:size(XmlData.Time,1)-1;
761            Param.i2_series=[];
762            if size(XmlData.Time,2)>2
763            Param.j1_series=1:size(XmlData.Time,2)-1;
764            else
765                Param.j1_series=[];
766            end
767            Param.j2_series=[];
768            Param.Relabel=true;
769        end
770    end
771end
772Param.XmlData=XmlData;
773
774%% detect the list of file in the input series in the case of no relabeling
775if ~Param.Relabel
776            set(handles.Relabel,'Value',0)
777    %%%%%%%%%%%%%%%%%%
778    %TODO: case of input by uvmat: do not check again the input series %%%%%%%
779    %%%%%%%%%%%%%%%%%%%
780    % detect the file type, get the movie object if relevant, and look for the corresponding file series:
781    % the root name and indices may be corrected by including the first index i1 if a corresponding xml file exists
782    [RootPath,SubDir,RootFile,Param.i1_series,Param.i2_series,Param.j1_series,Param.j2_series,NomType,FileInfo,MovieObject,i1,i2,j1,j2]=find_file_series(FilePath,[RootFile FileExt]);
783    if isempty(RootFile)&&isempty(Param.i1_series)
784        errormsg='no input file in the series';
785        msgbox_uvmat('ERROR',errormsg)
786        set(handles.REFRESH,'BackgroundColor',[1 0 1])% set REFRESH  button to magenta color (end of activation)
787        return
788    end
789end
790
791%% enable other menus and uicontrols
792set(handles.RUN, 'Enable','On')
793set(handles.RUN,'BackgroundColor',[1 0 0])% set RUN button to red
794set(handles.InputTable,'BackgroundColor',[1 1 0]) % set RootPath edit box  to yellow to indicate that it is under modification
795drawnow
796
797
798%% refresh the list of file series according to the input option 'one' or 'append'
799InputTable=get(handles.InputTable,'Data');
800SeriesData=get(handles.series,'UserData');
801if strcmp(iview,'append') % display the input data as a new line in the table
802    iview=size(InputTable,1)+1; % the next line in InputTable becomes the current line
803elseif strcmp(iview,'one') % refresh the list of  input  file series
804    iview=1; % the first line in InputTable becomes the current line
805    InputTable={'','','','',''};
806    set(handles.TimeTable,'Data',[{''},{[]},{[]},{[]},{[]}])
807    set(handles.MinIndex_i,'Data',[])
808    set(handles.MaxIndex_i,'Data',[])
809    set(handles.MinIndex_j,'Data',[])
810    set(handles.MaxIndex_j,'Data',[])
811    set(handles.PairString,'Data',{''})
812    SeriesData.CheckPair=0; % reset the list of input lines with pairs
813    SeriesData.i1_series={};
814    SeriesData.i2_series={};
815    SeriesData.j1_series={};
816    SeriesData.j2_series={};
817 %   SeriesData.FileType={};
818    SeriesData.FileInfo={};
819    SeriesData.Time={};
820end
821if isfield(SeriesData,'i1_series')% remove the irrelevant data lines beyond iview in SeriesData
822    SeriesData.i1_series(iview+1:end)=[];
823    SeriesData.i2_series(iview+1:end)=[];
824    SeriesData.j1_series(iview+1:end)=[];
825    SeriesData.j2_series(iview+1:end)=[];
826    %SeriesData.FileType(iview+1:end)=[];
827    SeriesData.FileInfo(iview+1:end)=[];
828    SeriesData.Time(iview+1:end)=[];
829end
830
831%% fill the current Intput Table line
832InputTable(iview,:)=[{RootPath},{SubDir},{RootFile},{NomType},{FileExt}];%fill the current Intput Table line
833if iview >1
834    set(handles.InputLine,'String',num2str(iview))
835end
836set(handles.InputTable,'Data',InputTable)
837
838%% determine the selected reference field indices for pair display
839if isempty(i1)
840    i1=1;
841end
842if isempty(i2)
843    i2=i1;
844end
845ref_i=floor((i1+i2)/2); % reference image number corresponding to the file
846% set(handles.num_ref_i,'String',num2str(ref_i));
847if isempty(j1)
848    j1=1;
849end
850if isempty(j2)
851    j2=j1;
852end
853ref_j=floor((j1+j2)/2); % reference image number corresponding to the file
854SeriesData.ref_i=ref_i;
855SeriesData.ref_j=ref_j;
856
857%% update first and last indices to operate if the files do not exist
858if ~Param.Relabel
859    ParamGUI=read_GUI(handles.series);
860    first_j=[];
861    if isfield(ParamGUI.IndexRange,'first_j'); first_j=ParamGUI.IndexRange.first_j; end
862    last_j=[];
863    if isfield(ParamGUI.IndexRange,'last_j'); last_j=ParamGUI.IndexRange.last_j; end
864    PairString='';
865    if isfield(ParamGUI.IndexRange,'PairString'); PairString=ParamGUI.IndexRange.PairString; end
866    [i1,i2,j1,j2] = get_file_index(ParamGUI.IndexRange.first_i,first_j,PairString);
867    FirstFileName=fullfile_uvmat(ParamGUI.InputTable{1,1},ParamGUI.InputTable{1,2},ParamGUI.InputTable{1,3},...
868        ParamGUI.InputTable{1,5},ParamGUI.InputTable{1,4},i1,i2,j1,j2);
869    if ~exist(FirstFileName,'file')
870        set(handles.num_first_i,'String',num2str(ref_i))
871        set(handles.num_first_j,'String',num2str(ref_j))
872    end
873    [i1,i2,j1,j2] = get_file_index(ParamGUI.IndexRange.last_i,last_j,PairString);
874    LastFileName=fullfile_uvmat(ParamGUI.InputTable{1,1},ParamGUI.InputTable{1,2},ParamGUI.InputTable{1,3},...
875        ParamGUI.InputTable{1,5},ParamGUI.InputTable{1,4},i1,i2,j1,j2);
876    if ~exist(LastFileName,'file')
877        set(handles.num_last_i,'String',num2str(ref_i))
878        set(handles.num_last_j,'String',num2str(ref_j))
879    end
880end
881
882%% update the list of recent files in the menubar and save it for future opening
883MenuFile=[{get(handles.MenuFile_1,'Label')};{get(handles.MenuFile_2,'Label')};...
884    {get(handles.MenuFile_3,'Label')};{get(handles.MenuFile_4,'Label')};{get(handles.MenuFile_5,'Label')}];
885str_find=strcmp(InputFile,MenuFile);
886if isempty(find(str_find,1))
887    MenuFile=[{InputFile};MenuFile]; % insert the current file if not already in the list
888end
889for ifile=1:min(length(MenuFile),5)
890    ffname=['MenuFile_' num2str(ifile)];
891    set(handles.(ffname),'Label',MenuFile{ifile});
892end
893dir_perso=prefdir;
894profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
895if exist(profil_perso,'file')
896    save (profil_perso,'MenuFile','-append'); % store the file names for future opening of uvmat
897else
898    save (profil_perso,'MenuFile','-V6'); % store the file names for future opening of uvmat
899end
900% save the opened file to initiate future opening
901SeriesData.RefFile{iview}=InputFile; % reference opening file for line iview
902SeriesData.Ref_i1=i1;
903SeriesData.Ref_i2=i2;
904SeriesData.Ref_j1=j1;
905SeriesData.Ref_j2=j2;
906
907%% define the path for the output files
908[InputPath,Device,DeviceExt]=fileparts(InputTable{1,1});
909[InputPath,Experiment,ExperimentExt]=fileparts(InputPath);
910set(handles.Device,'String',[Device DeviceExt])
911set(handles.Experiment,'String',[Experiment ExperimentExt])
912if ~isempty(regexp(InputTable{1,1},'(^http://)|(^https://)', 'once'))
913    set(handles.OutputPathBrowse,'Value',1)% an output folder needs to be specified for OpenDAP data
914end
915
916%update the output path if needed
917if ~(isfield(SeriesData,'InputPath') && strcmp(SeriesData.InputPath,InputPath))
918    if get(handles.OutputPathBrowse,'Value')==1  % fix the output path in manual modei1_series
919        OutputPathOld=get(handles.OutputPath,'String');
920        OutputPath=uigetdir(OutputPathOld,'pick a root folder for output data');
921        set(handles.OutputPath,'String',OutputPath)
922    else %reproduce the input path for output
923        set(handles.OutputPath,'String',InputPath)
924    end
925    SeriesData.InputPath=InputPath;
926end
927
928
929set(handles.series,'UserData',SeriesData)
930
931set(handles.InputTable,'BackgroundColor',[1 1 1])
932
933
934
935%% initiate input file series and refresh the current field view:
936update_rootinfo(handles,Param,MovieObject,iview);
937
938%% enable field and veltype menus, in accordance with the current action
939ActionName_Callback([],[], handles)
940
941% %% set length of waitbar
942% displ_time(handles)
943
944set(handles.REFRESH,'BackgroundColor',[1 0 0])% set REFRESH  button to red color (end of activation)
945
946%------------------------------------------------------------------------
947% --- get info from the xml file XmlFileName
948function XmlData=read_imadoc(XmlFileName)
949
950[XmlData,errormsg]=imadoc2struct(XmlFileName);
951if ~isempty(errormsg)
952    msgbox_uvmat('WARNING',['error in reading ' XmlFileName ': ' errormsg]);
953end
954% read time if available
955if ~isfield(XmlData,'Time')
956    XmlData.Time=[];
957end
958XmlData.TimeUnit=[];
959if isfield(XmlData,'Camera') && isfield(XmlData.Camera,'TimeUnit')
960    XmlData.TimeUnit=XmlData.Camera.TimeUnit;
961end
962% number of slices
963XmlData.NbSlice=[];
964if isfield(XmlData,'TranslationMotor')&& isfield(XmlData.TranslationMotor,'NbSlice')
965    XmlData.NbSlice=XmlData.TranslationMotor.NbSlice;
966end
967if ~isfield(XmlData,'FileSeries')
968    XmlData.FileSeries=[];
969end
970
971%------------------------------------------------------------------------
972% --- Update information about a new field series (indices to scan, timing,
973%     calibration from an xml file
974function update_rootinfo(handles,Param,VideoObject,iview)
975
976%% default time settings
977TimeUnit='';
978% read  value set by the first series for the append mode (iwiew >1)
979if iview>1
980    TimeUnit=get(handles.TimeUnit,'String');
981end
982TimeName='';
983Time=[]; % default
984TimeMin=[];
985TimeFirst=[];
986TimeLast=[];
987TimeMax=[];
988
989%% determine the min and max indices for the whole file series
990i1_series=Param.i1_series;
991i2_series=Param.i2_series;
992j1_series=Param.j1_series;
993j2_series=Param.j2_series;
994 MaxIndex_j=1;
995if Param.Relabel
996    MinIndex_i=1;
997    MinIndex_j=1;
998    set(handles.num_incr_j,'String','1')
999    MaxIndex_i=numel(i1_series);
1000    set(handles.num_incr_i,'String','1')
1001    if ~isempty(j1_series)
1002        MaxIndex_j=numel(j1_series);
1003    end
1004    Time=Param.XmlData.Time;
1005    TimeMin=Time(2,2);
1006    TimeMax=Time(end,end);
1007    TimeFirst=TimeMin;
1008    TimeLast=TimeMin;
1009    TimeName='xml';
1010else
1011    if isempty(i1_series)
1012        MinIndex_j=1;MaxIndex_j=1;MinIndex_i=1;MaxIndex_i=1;
1013    elseif size(i1_series,2)==2 && min(min(i1_series(:,1,:)))==0
1014        MinIndex_j=1; % index j set to 1 by default
1015        MaxIndex_j=1;
1016        MinIndex_i=find(i1_series(1,2,:), 1 )-1; % min ref index i detected in the series (corresponding to the first non-zero value of i1_series, except for zero index)
1017        MaxIndex_i=find(i1_series(1,2,:),1,'last' )-1; % max ref index i detected in the series (corresponding to the last non-zero value of i1_series)
1018    else
1019        ref_i=squeeze(max(i1_series(1,:,:),[],2)); % select ref_j index for each ref_i
1020        ref_j=squeeze(max(j1_series(1,:,:),[],3)); % select ref_i index for each ref_j
1021        MinIndex_i=find(ref_i, 1 )-1;
1022        MaxIndex_i=find(ref_i, 1, 'last' )-1;
1023        MaxIndex_j=find(ref_j, 1, 'last' )-1;
1024        MinIndex_j=find(ref_j, 1 )-1;
1025        diff_j_max=diff(ref_j);
1026        diff_i_max=diff(ref_i);
1027        if ~isempty(diff_i_max) && isequal (diff_i_max,diff_i_max(1)*ones(size(diff_i_max)))
1028            set(handles.num_incr_i,'String',num2str(diff_i_max(1)))% detect an increment to dispaly by default
1029        end
1030        if ~isempty(diff_j_max) && isequal (diff_j_max,diff_j_max(1)*ones(size(diff_j_max)))
1031            set(handles.num_incr_j,'String',num2str(diff_j_max(1)))
1032        end
1033    end
1034    if isequal(MinIndex_i,-1)
1035        MinIndex_i=0;
1036    end
1037    if isequal(MinIndex_j,-1)
1038        MinIndex_j=0;
1039    end
1040    if isfield(Param,'FileInfo') && isfield(Param.FileInfo,'Software')&&~isempty(Param.FileInfo.Software) && ~isempty(regexp(Param.FileInfo.Software,'^pco.camware', 'once'))
1041        MinIndex_i=0;
1042    end
1043end
1044
1045%% make the j indices visible if relevant
1046if (isempty(j1_series)|| ~isempty(j2_series))% no j series or j1-j2 pair
1047    enable_j(handles,'off');
1048else
1049    enable_j(handles,'on')%%%%remark: put series with j index at the end in the case of a list
1050end
1051
1052SeriesData=get(handles.series,'UserData');
1053if ~Param.Relabel
1054    %% read timing  from the current file (prioritary)
1055    if ~isempty(VideoObject)% case of movies
1056        imainfo=get(VideoObject);
1057        if isfield(imainfo,'NumFrames')
1058            imainfo.NumberOfFrames=imainfo.NumFrames;
1059        end
1060        if isempty(j1_series) % frame index along i
1061            Time=zeros(imainfo.NumberOfFrames+1,2);
1062            Time(:,2)=(0:1/imainfo.FrameRate:(imainfo.NumberOfFrames)/imainfo.FrameRate)';
1063        else
1064            Time=[0;ones(size(i1_series,3)-1,1)]*(0:1/imainfo.FrameRate:(imainfo.NumberOfFrames)/imainfo.FrameRate);
1065        end
1066        TimeName='video';
1067    end
1068
1069    %% get index range in case of relabeling
1070    if isfield(Param,'XmlData') && ~isempty(Param.XmlData.Time)
1071        Time=Param.XmlData.Time;
1072        MinIndex_i=1;
1073        MaxIndex_i=size(Time,1)-1;
1074        MinIndex_j=1;
1075        MaxIndex_j=size(Time,2)-1;
1076        TimeName='xml';
1077    else
1078        InputTable=get(handles.InputTable,'Data');
1079        [XmlFileName,Rank]=find_imadoc(InputTable{iview,1},InputTable{iview,2});
1080        if isempty(XmlFileName)
1081            return
1082        else
1083            Param.XmlData=read_imadoc(XmlFileName);
1084        end
1085        [nbfield,nbfield_j]=size(Param.XmlData.Time);
1086        nbfield=nbfield-1; %remove the possible index 0
1087        nbfield_j=nbfield_j-1; %remove the possible index 0
1088%         MaxIndex_i=get(handles.MaxIndex_i,'Data');
1089%         MaxIndex_j=get(handles.MaxIndex_j,'Data');
1090%         MaxIndex_i(1,:)=nbfield;
1091%         MaxIndex_j(1,:)=nbfield_j;
1092%         MinIndex_i(1,:)=1;
1093%         MinIndex_j(1,:)=1;
1094         MaxIndex_i=nbfield;
1095         MaxIndex_j=nbfield_j;
1096         MinIndex_i=1;
1097         MinIndex_j=1;
1098
1099
1100        first_i=str2double(get(handles.num_first_i,'String'));
1101        first_j=str2double(get(handles.num_first_j,'String'));
1102        %i1=(first_i-SeriesData.FileSeries{1}.FirstFileIndex)*SeriesData.FileSeries{1}.NbFramePerFile+1;%frame index deduced from input file index
1103        i1=1;
1104        if isfield(SeriesData,'TimeName') && strcmp(SeriesData.TimeName,'xml')% indices i and j
1105            j1=mod(i1-1,nbfield_j)+first_j;
1106            i1=floor((i1-1)/nbfield_j)+1;
1107            set(handles.num_first_j,'String',num2str(j1))
1108        end
1109    end
1110end
1111
1112if isfield(Param,'FileInfo') && ~isempty(Param.FileInfo) && strcmp(Param.FileInfo.FileType,'rdvision')
1113    set(handles.OutputSubDir,'String','/im')
1114end
1115
1116%% determine the min and max times: case of Netcdf files will be treated later in FieldName_Callback
1117if ~isempty(TimeName)
1118    if size(Time)<[MaxIndex_i+1 MaxIndex_j+1]
1119        msgbox_uvmat('WARNING',['incomplete time info in xml file']);
1120    end
1121    TimeMin=Time(MinIndex_i+1,MinIndex_j+1);
1122    if size(Time)>=[MaxIndex_i+1 MaxIndex_j+1]
1123        TimeMax=Time(MaxIndex_i+1,MaxIndex_j+1);
1124    end
1125end
1126
1127%% update the tables of Min and Max indices
1128MinIndex_i_table=get(handles.MinIndex_i,'Data'); % retrieve the min indices in the table MinIndex
1129MinIndex_j_table=get(handles.MinIndex_j,'Data'); % retrieve the min indices in the table MinIndex
1130MaxIndex_i_table=get(handles.MaxIndex_i,'Data'); % retrieve the min indices in the table MinIndex
1131MaxIndex_j_table=get(handles.MaxIndex_j,'Data'); % retrieve the min indices in the table MinIndex
1132if ~isempty(MinIndex_i)&&~isempty(MaxIndex_i)
1133    MinIndex_i_table(iview,1)=MinIndex_i;
1134    MaxIndex_i_table(iview,1)=MaxIndex_i;
1135end
1136if ~isempty(MinIndex_j)&&~isempty(MaxIndex_j)
1137    MinIndex_j_table(iview,1)=MinIndex_j;
1138    MaxIndex_j_table(iview,1)=MaxIndex_j;
1139end
1140set(handles.MinIndex_i,'Data',MinIndex_i_table)%display the min indices in the table MinIndex
1141set(handles.MinIndex_j,'Data',MinIndex_j_table)%display the max indices in the table MaxIndex
1142set(handles.MaxIndex_i,'Data',MaxIndex_i_table)%display the min indices in the table MinIndex
1143set(handles.MaxIndex_j,'Data',MaxIndex_j_table)%display the max indices in the table MaxIndex
1144
1145if isfield(Param.XmlData,'NbSlice') && ~isempty(Param.XmlData.NbSlice)
1146    set(handles.num_NbSlice,'String',num2str(Param.XmlData.NbSlice))
1147    set(handles.num_NbSlice,'Visible','on')
1148end
1149
1150
1151%% adjust the first and last indices for the selected series, only if requested by the bounds
1152% i index, compare input to min index i
1153first_i=str2num(get(handles.num_first_i,'String')); % retrieve previous first i
1154% ref_i=str2num(get(handles.num_ref_i,'String')); % index i given by the input field
1155ref_i=1;
1156
1157if isfield(SeriesData,'ref_i')
1158    ref_i=SeriesData.ref_i;
1159end
1160if isempty(first_i)
1161    first_i=ref_i; % first_i updated by the input value
1162elseif first_i < MinIndex_i
1163    first_i=MinIndex_i; % first_i set to the min i index (restricted by oter input lines)
1164elseif first_i >MaxIndex_i
1165    first_i=MaxIndex_i; % first_i set to the max i index (restricted by oter input lines)
1166end
1167% j index,  compare input to min index j
1168first_j=str2num(get(handles.num_first_j,'String'));
1169ref_j=1;
1170if isfield(SeriesData,'ref_j')
1171    ref_j=SeriesData.ref_j;
1172end
1173if isempty(first_j)
1174    first_j=ref_j; % first_j updated by the input value
1175elseif first_j<MinIndex_j
1176    first_j=MinIndex_j; % first_j set to the min j index (restricted by oter input lines)
1177elseif first_j >MaxIndex_j
1178    first_j=MaxIndex_j; % first_j set to the max j index (restricted by oter input lines)
1179end
1180% i index, compare input to max index i
1181last_i=str2num(get(handles.num_last_i,'String'));
1182if isempty(last_i)
1183    last_i=ref_i;
1184elseif last_i > MaxIndex_i
1185    last_i=MaxIndex_i;
1186elseif last_i<first_i
1187    last_i=first_i;
1188end
1189% j index, compare input to max index j
1190last_j=str2num(get(handles.num_last_j,'String'));
1191if isempty(last_j)
1192    last_j=ref_j;
1193elseif last_j>MaxIndex_j
1194    last_j=MaxIndex_j;
1195elseif last_j<first_j
1196    last_j=first_j;
1197end
1198set(handles.num_first_i,'String',num2str(first_i));
1199set(handles.num_first_j,'String',num2str(first_j));
1200set(handles.num_last_i,'String',num2str(last_i));
1201set(handles.num_last_j,'String',num2str(last_j));
1202
1203%% number of slices set by default
1204NbSlice=[]; % default
1205% read  value set by the first series for the append mode (iwiew >1)
1206if iview>1 && strcmp(get(handles.num_NbSlice,'Visible'),'on')
1207    NbSlice=str2double(get(handles.num_NbSlice,'String'));
1208end
1209
1210
1211%% update the time table
1212TimeTable=get(handles.TimeTable,'Data');
1213TimeTable{iview,1}=TimeName;
1214TimeTable{iview,2}=TimeMin;
1215TimeTable{iview,3}=TimeFirst;
1216TimeTable{iview,4}=TimeLast;
1217TimeTable{iview,5}=TimeMax;
1218set(handles.TimeTable,'Data',TimeTable)
1219
1220%% update the series info in 'UserData'
1221SeriesData.i1_series{iview}=i1_series;
1222SeriesData.i2_series{iview}=i2_series;
1223SeriesData.j1_series{iview}=j1_series;
1224SeriesData.j2_series{iview}=j2_series;
1225%     SeriesData.FileType{iview}=FileInfo.FileType;
1226SeriesData.FileInfo{iview}=Param.FileInfo;
1227SeriesData.Time{iview}=Time;
1228SeriesData.TimeName=TimeName;
1229set(handles.series,'UserData',SeriesData)
1230
1231%% updtate the time info
1232displ_time(handles);
1233
1234%% update pair menus
1235InputTable=get(handles.InputTable,'Data');
1236hset_pair=findobj(allchild(0),'Tag','set_pairs');
1237if ~isempty(hset_pair), delete(hset_pair); end % delete the GUI set_pair if opened
1238CheckPair= ~isempty(i2_series)||~isempty(j2_series); % check whether index pairs need to be defined
1239PairString=get(handles.PairString,'Data');
1240PairString{iview,1}=''; % no pair for #iview by default
1241if CheckPair% if pairs need to be display for line iview
1242    [ModeMenu,ModeValue]=update_mode(i1_series,i2_series,j2_series);
1243    Menu=update_listpair(i1_series,i2_series,j1_series,j2_series,ModeMenu{ModeValue},Time,TimeUnit,ref_i,ref_j,TimeName,InputTable(iview,:),Param.FileInfo);
1244    if numel(Menu)>=1
1245        PairString{iview,1}=Menu{1};
1246    end
1247end
1248set(handles.PairString,'Data',PairString)
1249if isempty(find(cellfun('isempty',get(handles.PairString,'Data'))==0, 1))% if all lines of pairs are empty
1250    set(handles.PairString,'Visible','off')
1251    set(handles.SetPairs,'Visible','off')
1252else
1253    set(handles.PairString,'Visible','on')
1254    set(handles.SetPairs,'Visible','on')
1255end
1256
1257
1258%% display the set of existing files as an image with black bands for gaps showing gaps in the series
1259
1260%set(handles.FileStatus,'Units','normalized')
1261nbview=numel(SeriesData.i1_series);
1262i_max=cell(1,nbview);
1263MaxIndex_i=ones(1,nbview); % default
1264MinIndex_i=ones(1,nbview); % default
1265missing_indices=cell(1,nbview);
1266for iline=1:nbview
1267    pair_max=squeeze(max(SeriesData.i1_series{iline},[],1)); % max i1 indices from i1_series (as obtained by fct uvmat/find_file_series.m)
1268                                                            % needed in the case of mutiple pairs for the same index ref_i)
1269    i_max{iline}=max(pair_max,[],1); % max on j index
1270    if ~isempty(i_max{iline})&& ~isequal(pair_max,0)
1271        MaxIndex_i(iline)=find(i_max{iline}, 1, 'last' )-1; % max ref index i
1272        MinIndex_i(iline)=find(i_max{iline}, 1 )-1; % min ref index i
1273         exist_indices{iline}= find(i_max{iline}(2:end)~=0);
1274         index_series=i_max{iline}( exist_indices{iline});
1275    end
1276end
1277MinIndex_i=min(MinIndex_i);
1278MaxIndex_i=max(MaxIndex_i);
1279range_index=MaxIndex_i-MinIndex_i+1;
1280
1281set(handles.FileStatus,'Units','pixels')
1282Position=get(handles.FileStatus,'Position');
1283range_y=max(1,floor(Position(4)/nbview));
1284npx=floor(Position(3));%length of the bar image FileStatus in pixels
1285
1286%file_indices=MinIndex_i+floor(((0.5:npx-0.5)/npx)*range_index)+1;
1287CData=ones(nbview*range_y,npx); % initiate the image representing the existing files
1288if MaxIndex_i>MinIndex_i
1289    LineData=ones(1,npx);
1290    for iline=1:nbview
1291        ind_y=1+(iline-1)*range_y:iline*range_y;
1292%         missing_pixels=floor((missing_indices{iline}-MinIndex_i+1)*npx/range_index)+1;
1293%         LineData(missing_pixels)=0;
1294        %     LineData=zeros(size(file_indices));
1295        %     file_select=file_indices(file_indices<=numel(i_max{iline}));
1296        %     ind_select=file_indices<=numel(i_max{iline});
1297        %     LineData(ind_select)=i_max{iline}(file_select)~=0;
1298        CData(ind_y,:)=ones(numel(ind_y),1)*LineData;%create an image band with width numel(ind_y)
1299    end
1300end
1301CData=cat(3,zeros(size(CData)),CData,zeros(size(CData))); % make color images r=0,g,b=0
1302set(handles.FileStatus,'CData',CData);
1303set(handles.FileStatus,'Units','normalized')
1304%-----------------------------------------------------------guide -------------
1305%------------------------------------------------------------------------
1306%  III - FUNCTIONS ASSOCIATED TO THE FRAME IndexRange
1307%------------------------------------------------------------------------
1308
1309
1310% ---- determine the menu to put in mode and advice a default choice
1311%------------------------------------------------------------------------
1312function [ModeMenu,ModeValue]=update_mode(i1_series,i2_series,j2_series)
1313%------------------------------------------------------------------------
1314ModeMenu={''};
1315if isempty(j2_series)% no j pair
1316    ModeValue=1;
1317    if ~isempty(i2_series)
1318        ModeMenu={'series(Di)'}; % pair menu with only option Di
1319    end
1320else %existence of j pairs
1321    pair_max=squeeze(max(i1_series,[],1)); % max on pair index
1322    j_max=max(pair_max,[],1);
1323    MaxIndex_i=find(j_max, 1, 'last' )-1; % max ref index i
1324    MinIndex_i=find(j_max, 1 )-1; % min ref index i
1325    i_max=max(pair_max,[],2);
1326    MaxIndex_j=find(i_max, 1, 'last' )-1; % max ref index i
1327    MinIndex_j=find(i_max, 1 )-1; % min ref index i
1328    if MaxIndex_j==MinIndex_j
1329        ModeValue=1;
1330        ModeMenu={'bursts'};
1331    elseif MaxIndex_i==MinIndex_i
1332        ModeValue=1;
1333        ModeMenu={'series(Dj)'};
1334    else
1335        ModeMenu={'bursts';'series(Dj)'};
1336        if (MaxIndex_j-MinIndex_j)>10
1337            ModeValue=2; % set mode to series(Dj) if more than 10 j values
1338        else
1339            ModeValue=1;
1340        end
1341    end
1342end
1343
1344
1345%------------------------------------------------------------------------
1346%fill the menu of possible pairs as input
1347function displ_pair=update_listpair(i1_series,i2_series,j1_series,j2_series,mode,time,TimeUnit,ref_i,ref_j,TimeName,InputTable,FileInfo)
1348%------------------------------------------------------------------------
1349displ_pair={};
1350if isempty(TimeUnit)
1351    dtunit='e-03';
1352else
1353    dtunit=['m' TimeUnit];
1354end
1355switch mode
1356    case 'series(Di)'
1357        diff_i=i2_series-i1_series;
1358        min_diff=min(diff_i(diff_i>0));
1359        max_diff=max(diff_i(diff_i>0));
1360        for ipair=min_diff:max_diff
1361            if ~isempty(find(diff_i==ipair,1))% if the considered difference exists as input
1362                pair_string=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
1363                if size(time,1)>=ref_i+ceil(ipair/2)
1364                    if ref_i<=floor(ipair/2)
1365                        ref_i=floor(ipair/2)+1; % shift ref_i to get the first pair
1366                    end
1367                    Dt=time(ref_i+ceil(ipair/2),ref_j)-time(ref_i-floor(ipair/2),ref_j);
1368                    pair_string=[pair_string ', Dt=' num2str(Dt) ' ' dtunit];
1369                end
1370                displ_pair=[displ_pair;{pair_string}];
1371            end
1372        end
1373        if ~isempty(displ_pair)
1374            displ_pair=[displ_pair;{'Di=*|*'}];
1375        end
1376    case 'series(Dj)'
1377        if isempty(j2_series)
1378            msgbox_uvmat('ERROR','no j1-j2 pair available')
1379            return
1380        end
1381        diff_j=j2_series-j1_series;
1382        min_diff=min(diff_j(diff_j>0));
1383        max_diff=max(diff_j(diff_j>0));
1384        for ipair=min_diff:max_diff
1385            if numel(diff_j(diff_j==ipair))>0
1386                pair_string=['Dj= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
1387                if ~isempty(time)
1388                    if ref_j<=floor(ipair/2)
1389                        ref_j=floor(ipair/2)+1; % shift ref_i to get the first pair
1390                    end
1391                    Dt=time(ref_i,ref_j+ceil(ipair/2))-time(ref_i,ref_j-floor(ipair/2));
1392                    pair_string=[pair_string ', Dt=' num2str(Dt) ' ' dtunit];
1393                end
1394                displ_pair=[displ_pair;{pair_string}];
1395            end
1396        end
1397        if ~isempty(displ_pair)
1398            displ_pair=[displ_pair;{'Dj=*|*'}];
1399        end
1400    case 'bursts'
1401        if isempty(j2_series)
1402            msgbox_uvmat('ERROR','no j1-j2 pair available')
1403            return
1404        end
1405        %diff_j=j2_series-j1_series;
1406        min_j1=min(j1_series(j1_series>0));
1407        max_j1=max(j1_series(j1_series>0));
1408        min_j2=min(j2_series(j2_series>0));
1409        max_j2=max(j2_series(j2_series>0));
1410        for pair1=min_j1:min(max_j1,min_j1+20)
1411            for pair2=min_j2:min(max_j2,min_j2+20)
1412                if numel(j1_series(j1_series==pair1))>0 && numel(j2_series(j2_series==pair2))>0
1413                    pair_string=['j= ' num2str(pair1) '-' num2str(pair2)];
1414                    [TimeValue,DtValue]=get_time(ref_i,[],pair_string,InputTable,FileInfo,TimeName,'Dt');
1415                    %Dt=time(ref_i,pair2+1)-time(ref_i,pair1+1);
1416                    pair_string=[pair_string ', Dt=' num2str(DtValue) ' ' dtunit];
1417                    displ_pair=[displ_pair;{pair_string}];
1418                end
1419            end
1420        end
1421        if ~isempty(displ_pair)
1422            displ_pair=[displ_pair;{'j=*-*'}];
1423        end
1424end
1425
1426%------------------------------------------------------------------------
1427function num_first_i_Callback(hObject, eventdata, handles)
1428%------------------------------------------------------------------------
1429num_last_i_Callback(hObject, eventdata, handles)
1430
1431%------------------------------------------------------------------------
1432function num_last_i_Callback(hObject, eventdata, handles)
1433%------------------------------------------------------------------------
1434SeriesData=get(handles.series,'UserData');
1435if ~isfield(SeriesData,'Time')
1436    SeriesData.Time{1}=[];
1437end
1438displ_time(handles);
1439
1440%------------------------------------------------------------------------
1441function num_first_j_Callback(hObject, eventdata, handles)
1442%------------------------------------------------------------------------
1443 num_last_j_Callback(hObject, eventdata, handles)
1444
1445%------------------------------------------------------------------------
1446function num_last_j_Callback(hObject, eventdata, handles)
1447%------------------------------------------------------------------------
1448SeriesData=get(handles.series,'UserData');
1449if ~isfield(SeriesData,'Time')
1450    SeriesData.Time{1}=[];
1451end
1452displ_time(handles);
1453
1454%------------------------------------------------------------------------
1455% ---- find the times corresponding to the first and last indices of a series
1456function displ_time(handles)
1457%------------------------------------------------------------------------
1458SeriesData=get(handles.series,'UserData'); %
1459if ~isfield(SeriesData,'Time')
1460    return
1461end
1462PairString=get(handles.PairString,'Data');
1463ref_i_1=str2double(get(handles.num_first_i,'String')); % first reference index
1464if isnan(ref_i_1)
1465    ref_i_1=1;
1466end
1467ref_i_2=str2double(get(handles.num_last_i,'String')); % last reference index
1468if isnan(ref_i_2)
1469    ref_i_2=1;
1470end
1471ref_j_1=NaN;ref_j_2=NaN;
1472if strcmp(get(handles.num_first_j,'Visible'),'on')
1473    ref_j_1=str2double(get(handles.num_first_j,'String'));
1474    ref_j_2=str2double(get(handles.num_last_j,'String'));
1475end
1476[i1_1,i2_1,j1_1,j2_1] = get_file_index(ref_i_1,ref_j_1,PairString);
1477[i1_2,i2_2,j1_2,j2_2] = get_file_index(ref_i_2,ref_j_2,PairString);
1478TimeTable=get(handles.TimeTable,'Data');
1479%%%%%%
1480%TODO: read time in netcdf file, see ActionName_Callback
1481%%%%%%%
1482%Pairs=get(handles.PairString,'Data');
1483for iview=1:size(TimeTable,1)
1484    if numel(SeriesData.Time)<iview
1485        break
1486    end
1487    TimeTable{iview,3}=[];
1488    TimeTable{iview,4}=[];
1489    if size(SeriesData.Time{iview},1)>=i2_2+1 && (isnan(ref_j_1)||size(SeriesData.Time{iview},2)>=j2_2+1)
1490        if isnan(ref_j_1)
1491            time_first=(SeriesData.Time{iview}(i1_1+1,2)+SeriesData.Time{iview}(i2_1+1,2))/2;% take  the average between index i1 and i2
1492            time_last=(SeriesData.Time{iview}(i1_2+1,2)+SeriesData.Time{iview}(i2_2+1,2))/2;
1493        else
1494            time_first=(SeriesData.Time{iview}(i1_1+1,j1_1+1)+SeriesData.Time{iview}(i2_1+1,j2_1+1))/2;
1495            time_last=(SeriesData.Time{iview}(i1_2+1,j1_2+1)+SeriesData.Time{iview}(i2_2+1,j2_1+1))/2;
1496        end
1497        TimeTable{iview,3}=time_first; % TODO: take into account pairs
1498        TimeTable{iview,4}=time_last; % TODO: take into account pairs
1499    end
1500end
1501set(handles.TimeTable,'Data',TimeTable)
1502
1503%% set the waitbar position with respect to the min and max in the series
1504MinIndex_i=min(get(handles.MinIndex_i,'Data'));
1505MaxIndex_i=max(get(handles.MaxIndex_i,'Data'));
1506pos_first=(ref_i_1-MinIndex_i)/(MaxIndex_i-MinIndex_i+1);
1507pos_last=(ref_i_2-MinIndex_i+1)/(MaxIndex_i-MinIndex_i+1);
1508if isempty(pos_first), pos_first=0; end
1509if isempty(pos_last), pos_last=1; end
1510Position=get(handles.Waitbar,'Position'); % position of the waitbar:= [ x,y, width, height]
1511Position_status=get(handles.FileStatus,'Position');% position of the FileStatus bar:= [ x,y, width, height]
1512Position(1)=Position_status(1)+Position_status(3)*pos_first;
1513Position(3)=max(Position_status(3)*(pos_last-pos_first),0.001); % width must remain positive
1514set(handles.Waitbar,'Position',Position)
1515update_waitbar(handles.Waitbar,0)
1516
1517%------------------------------------------------------------------------
1518% --- Executes when selected cell(s) is changed in PairString.
1519function PairString_CellSelectionCallback(hObject, eventdata, handles)
1520%------------------------------------------------------------------------
1521if numel(eventdata.Indices)>=1
1522    PairString=get(hObject,'Data');
1523    if ~isempty(PairString{eventdata.Indices(1)})
1524        SetPairs_Callback(hObject, eventdata.Indices(1), handles)
1525    end
1526end
1527
1528
1529%-----------------------------------
1530function enable_j(handles,state)
1531set(handles.j_txt,'Visible',state)
1532set(handles.num_first_j,'Visible',state)
1533set(handles.num_last_j,'Visible',state)
1534set(handles.num_incr_j,'Visible',state)
1535set(handles.MinIndex_j,'Visible',state)
1536set(handles.MaxIndex_j,'Visible',state)
1537
1538
1539%%%%%%%%%%%%%%%%%%%%
1540%%  MAIN ActionName FUNCTIONS
1541%%%%%%%%%%%%%%%%%%%%
1542%------------------------------------------------------------------------
1543% --- Executes on button press in RUN.
1544%------------------------------------------------------------------------
1545function RUN_Callback(hObject, eventdata, handles)
1546
1547%% settings of the button RUN
1548if ~isequal(get(handles.ActionInput,'BackgroundColor'),[1 0 0])
1549    msgbox_uvmat('ERROR','first activate the button ActionInput')
1550    return
1551end
1552set(handles.RUN,'BusyAction','queue'); % activation of STOP button will set BusyAction to 'cancel'
1553set(handles.RUN, 'Enable','Off')% avoid further RUN action until the current one is finished
1554set(handles.RUN,'BackgroundColor',[1 1 0])%show activation of RUN by yellow color
1555drawnow
1556set(handles.status,'Value',0)% desable status display if relevant
1557status_Callback([], eventdata, handles)
1558
1559%% launch action
1560errormsg=launch_action(handles);
1561if ~isempty(errormsg)
1562     msgbox_uvmat('ERROR',errormsg)
1563end
1564
1565%% reset the GUI series
1566update_waitbar(handles.Waitbar,1); % put the waitbar to end position to indicate launching is finished
1567set(handles.RUN, 'Enable','On')
1568set(handles.RUN,'BackgroundColor',[1 0 0])
1569set(handles.RUN, 'Value',0)
1570
1571%------------------------------------------------------------------------
1572% --- called by RUN_Callback
1573%------------------------------------------------------------------------
1574% The calculations are launched in three different ways:
1575% RunMode='local': calculation on the local Matlab session, will prevent other actions during that time.
1576% RunMode='background': calculation on the local computer, but in a new Matlab session (with no graphic output).
1577% RunMode='cluster': calculations dispatched in a cluster, using a managing system, 'oar, 'sge, or 'sgb'.
1578% In the latter case, the calculation is split in 'packets' of i index (all j indices are contained in a single packet).
1579% This splitting is possible only if the different calculations in the series are independent. Otherwise the action
1580% function imposes a number of processes NbSlice in input, for instance NbSlice=1 for a time series.
1581% If NbSlice is not imposed, the splitting in packets (jobs) is determined
1582% so that a job is optimum length AdvisedJobCPUTime), and the total job number in any case smaller
1583% than MaxJobNumber (these parameters are defined in the file series.xml in
1584% accordance with the management strategy for the cluster). The jobs are
1585% dispatched in parallel into NbCore processors by the cluster managing system.
1586
1587function errormsg=launch_action(handles)
1588%errormsg=''; % default
1589
1590%% read the data on the GUI series
1591Param=read_GUI_series(handles); % displayed parameters
1592SeriesData=get(handles.series,'UserData'); % hidden parameters
1593if isfield(SeriesData,'TransformInput')
1594    Param.TransformInput=SeriesData.TransformInput;
1595end
1596if isfield(SeriesData,'ProjObject')
1597    Param.ProjObject=SeriesData.ProjObject;
1598end
1599if isfield(SeriesData,'FileSeries')
1600    Param.FileSeries=SeriesData.FileSeries{1};
1601end
1602if ~isfield(SeriesData,'i1_series')
1603    errormsg='The input field series needs to be refreshed: press REFRESH';
1604    return
1605end
1606if isfield(Param,'InputFields')&& isfield(Param.InputFields,'FieldName')&& isequal(Param.InputFields.FieldName,'add_field...')
1607    errormsg='input field name(s) not defined, select add_field...';
1608    return
1609end
1610[status,result]=system(['svn info ' Param.Action.ActionPath]);
1611if status==0
1612    t=regexp(result,'R.vision\s*:\s*(?<rev>\d+)','names');%detect 'revision' or 'Revision' in the text
1613    if ~isempty(t)
1614        Param.UvmatRevision=t.rev; %version nbre of the current package
1615    end
1616end
1617
1618%% select the Action mode, 'local', 'background' or 'cluster' (if available)
1619RunMode='local'; % default (needed for first opening of the GUI series)
1620if isfield(Param.Action,'RunMode')
1621    RunMode=Param.Action.RunMode;
1622    Param.Action=rmfield(Param.Action,'RunMode'); % remove from the recorded xml file to avoid interference during ImportConfig
1623    Param.RunMode=RunMode; % keep track of the mode
1624end
1625ActionExt='.m'; % default
1626if isfield(Param.Action,'ActionExt')
1627    ActionExt=Param.Action.ActionExt; % '.m', '.sh' (compiled)  or 'fluidimage' (Python)
1628    Param.Action=rmfield(Param.Action,'ActionExt'); % remove from the recorded xml file to avoid interference during ImportConfig
1629end
1630ActionName=Param.Action.ActionName;
1631ActionPath=Param.Action.ActionPath;
1632path_series=fileparts(which('series'));
1633
1634%% create the Action fct handle if RunMode option = 'local'
1635if strcmp(RunMode,'local')
1636    current_dir=pwd; % current working dir
1637    cd(ActionPath)
1638    h_fun=str2func(ActionName);% create the function handle for the function ActionName
1639    cd(current_dir)
1640end
1641
1642%% Get  parameters from series.xml
1643errormsg=''; % default error message
1644ActionFullName=fullfile(get(handles.ActionPath,'String'),ActionName);
1645
1646%% If a compiled version has been selected (ext .sh) check wether it needs to be recompiled
1647if strcmp(ActionExt,'.sh')
1648    TransformPath='';
1649    if isfield(SeriesData,'TransformPath')
1650        TransformPath=SeriesData.TransformPath;
1651        if isfield(SeriesData,'TransformList')
1652            TransformList=get(handles.TransformName,'String');
1653            TransformIndex=get(handles.TransformName,'Value');
1654            TransformName=TransformList{TransformIndex};
1655            if ~ismember(TransformName,SeriesData.TransformList)
1656                TransformPath='';
1657            end
1658        end
1659    end
1660    if ~isempty(TransformPath)&&...
1661          ~strcmp(TransformPath,get(handles.TransformPath,'String'))% if the transform is not in paths set for compilation
1662        msgbox_uvmat('ERROR', 'compilation not available for this transform function, select .m')
1663        return
1664    end
1665    set(handles.series,'Pointer','watch') % set the mouse pointer to 'watch'
1666    set(handles.ActionExt,'BackgroundColor',[1 1 0])
1667    [mcrmajor, mcrminor] = mcrversion;
1668    MCRROOT = ['MCRROOT',int2str(mcrmajor),int2str(mcrminor)];
1669    RunTime = getenv('MCRROOT'); % Just variable MCRROOT with no version in it's name
1670    if strcmp(RunTime,'')
1671        RunTime = getenv(MCRROOT); % Use specialize MCRROOT with version
1672    end
1673    ActionNameVersion=[ActionName '_' MCRROOT];
1674    ActionFullName=fullfile(get(handles.ActionPath,'String'),[ActionNameVersion '.sh']);
1675    % compile the .m file if the .sh file does not exist yet
1676    if ~exist(ActionFullName,'file')
1677        answer=msgbox_uvmat('INPUT_Y-N','compiled version has not been created: compile now?');
1678        if strcmp(answer,'Yes')
1679            set(handles.ActionExt,'BackgroundColor',[1 1 0])
1680            path_uvmat=fileparts(which('series'));
1681            currentdir=pwd;
1682            cd(get(handles.ActionPath,'String'))% go to the directory of Action
1683            addpath(path_uvmat)% add the path to uvmat to run the fct 'compile'
1684            compile(ActionName,TransformPath)
1685            cd(currentdir)
1686        else
1687            errormsg='Action launch interrupted';
1688            return
1689        end
1690    else
1691        sh_file_info=dir(fullfile(get(handles.ActionPath,'String'),[ActionNameVersion '.sh']));
1692        m_file_info=dir(fullfile(get(handles.ActionPath,'String'),[ActionName '.m']));
1693        if isfield(m_file_info,'datenum') && m_file_info.datenum>sh_file_info.datenum
1694            set(handles.ActionExt,'BackgroundColor',[1 1 0])
1695            drawnow
1696            answer=msgbox_uvmat('INPUT_Y-N',[ActionNameVersion '.sh needs to be updated: recompile now?']);
1697            if strcmp(answer,'Yes')
1698                path_uvmat=fileparts(which('series'));
1699                currentdir=pwd;
1700                cd(get(handles.ActionPath,'String'))% go to the directory of Action
1701                addpath(path_uvmat)% add the path to uvmat to run the fct 'compile'
1702                addpath(fullfile(path_uvmat,'transform_field'))% add the path to transform functions to run the fct 'compile'
1703                compile(ActionName,TransformPath)
1704                cd(currentdir)
1705            end
1706        end
1707    end
1708
1709    set(handles.ActionExt,'BackgroundColor',[1 1 1])
1710     set(handles.series,'Pointer','arrow') % set the mouse pointer to 'watch
1711end
1712
1713%% set nbre of cluster cores and processes:
1714% NbCore is the number of computer processors used
1715% NbProcess is the number of independent processes in which the required calculation is split.
1716if ~isfield(Param.IndexRange,'NbSlice')
1717    Param.IndexRange.NbSlice=[];
1718end
1719OutputPath=get(handles.OutputPath,'String');
1720
1721%% Look for processing on multiple experiments set by the GUI browse_data
1722NbExp=1;% initiate the number of experiments set by the GUI browse_data, =1 otherwise
1723if get(handles.Replicate,'Value')
1724    hh=findobj(allchild(0),'Tag','browse_data');
1725    if isempty(hh)
1726        set(handles.Replicate,'Value',0)
1727    else
1728        set(handles.Replicate,'BackgroundColor',[1 1 0])%paint Relicate button in yellow
1729        BrowseData=guidata(hh);
1730        SourceDir=get(BrowseData.SourceDir,'String');
1731        ListExp=get(BrowseData.ListExperiments,'String');
1732        ExpIndices=get(BrowseData.ListExperiments,'Value');
1733        ListExp=ListExp(ExpIndices);
1734        ListDevices=get(BrowseData.ListDevices,'String');
1735        DeviceIndices=get(BrowseData.ListDevices,'Value');
1736        ListDevices=ListDevices(DeviceIndices);
1737        ListDataSeries=get(BrowseData.DataSeries,'String');
1738        DataSeriesIndices=get(BrowseData.DataSeries,'Value');
1739        ListDataSeries=ListDataSeries(DataSeriesIndices);
1740        NbExp=0; % counter of the number of experiments set by the GUI browse_data
1741        for iexp=1:numel(ListExp)
1742            if ~isempty(regexp(ListExp{iexp},'^\+/'))% if it is a folder
1743                for idevice=1:numel(ListDevices)
1744                    if ~isempty(regexp(ListDevices{idevice},'^\+/'))% if it is a folder
1745                        for isubdir=1:numel(ListDataSeries)
1746                            if ~isempty(regexp(ListDataSeries{isubdir},'^\+/'))% if it is a folder
1747                                lpath= fullfile(SourceDir,regexprep(ListExp{iexp},'^\+/',''),...
1748                                    regexprep(ListDevices{idevice},'^\+/',''));
1749                                lpathout= fullfile(OutputPath,regexprep(ListExp{iexp},'^\+/',''),...
1750                                    regexprep(ListDevices{idevice},'^\+/',''));
1751                                ldir= regexprep(ListDataSeries{isubdir},'^\+/','');
1752                                if exist(fullfile(lpath,ldir),'dir')
1753                                    NbExp=NbExp+1;
1754                                    ExpIndex(NbExp)=ExpIndices(iexp);
1755                                    DeviceIndex(NbExp)=DeviceIndices(idevice);
1756                                    ListPath{NbExp}=lpath;
1757                                    ListPathOut{NbExp}=lpathout;
1758                                    ListDeviceOut{NbExp}=regexprep(ListDevices{idevice},'^\+/','');
1759                                    ListExpOut{NbExp}=regexprep(ListExp{iexp},'^\+/','');
1760                                    ListSubdir{NbExp}=ldir;
1761                                end
1762                            end
1763                        end
1764                    end
1765                end
1766                %                 end
1767            end
1768        end
1769        answer=msgbox_uvmat('INPUT_Y-N-Cancel',['replicate the processing on ' num2str(NbExp) ' data series']);
1770        if strcmp(answer,'Cancel')||strcmp(answer,'No')
1771            return
1772        end
1773    end
1774end
1775
1776%%%%%%%%%%%%%%%%%%% LOOP ON EXPERIMENTS POSSIBLY SET BY THE GUI browse_data, NbExp=1 otherwise %%%%%%%%%
1777
1778for iexp=1:NbExp
1779    if get(handles.Replicate,'Value')
1780        if ~strcmp(get(handles.RUN,'BusyAction'),'queue')% allow for STOP action
1781            disp('program stopped by user')
1782            return
1783        end
1784        set(BrowseData.ListExperiments,'Value',ExpIndex(iexp))
1785        set(BrowseData.ListDevices,'Value',DeviceIndex(iexp))
1786        Param.InputTable(:,1)=ListPath(:,iexp);
1787        Param.InputTable(:,2)=ListSubdir(:,iexp);
1788        OutputSubDir=unique(ListSubdir(:,iexp));
1789        Param.OutputSubDir=OutputSubDir{1};
1790        if numel(OutputSubDir)>1% case
1791            for iout=2:numel(OutputSubDir)
1792                Param.OutputSubDir=[Param.OutputSubDir '-' OutputSubDir{iout}];
1793            end
1794        end
1795    end
1796    [~,ExpName]=fileparts(Param.InputTable{1,1});
1797    Param.IndexRange.first_i=str2double(get(handles.num_first_i,'String'));%reset the firrst_i and last_i for multiple experiments, modified by the splitting into NbProcess
1798    Param.IndexRange.last_i=str2double(get(handles.num_last_i,'String'));
1799
1800    %% create the output data directory if needed, after checking its existence
1801    OutputDir='';
1802    answer='';
1803    if isfield(Param,'OutputSubDir')&& isfield(Param,'OutputDirExt')% possibly update the output dir if it already exists
1804        PathOut=get(handles.OutputPath,'String');
1805        if ~exist(PathOut,'dir') % test if  the dir  already exist
1806            PathOut=uigetdir(PathOut,'pick the output root path');
1807            set(handles.OutputPath,'String',PathOut);
1808        end
1809        if get(handles.Replicate,'Value')
1810        PathExpOut=fileparts(ListPath{iexp});
1811        PathExpDeviceOut=ListPath{iexp};
1812        else
1813            PathExpOut=fullfile(PathOut,get(handles.Experiment,'String'));
1814            PathExpDeviceOut=fullfile(PathExpOut,get(handles.Device,'String'));
1815        end
1816        if ~exist(PathExpOut,'dir')
1817            [~,msg1]=mkdir(PathExpOut);
1818            if ~strcmp(msg1,'')
1819                errormsg=['cannot create ' PathExpOut ': ' msg1]; % error message for directory creation
1820                return
1821            end
1822        end
1823        if ~exist(PathExpDeviceOut,'dir')
1824            [~,msg1]=mkdir(PathExpDeviceOut);
1825            if ~strcmp(msg1,'')
1826                errormsg=['cannot create ' PathExpDeviceOut ': ' msg1]; % error message for directory creation
1827                return
1828            end
1829        end
1830
1831        SubDirOut=[Param.OutputSubDir Param.OutputDirExt];
1832        SubDirOutNew=SubDirOut;
1833        detect=exist(fullfile(PathExpDeviceOut,SubDirOutNew),'dir'); % test if  the dir  already exist
1834        check_create=1; % need to create the result directory by default
1835        CheckOverwrite=1;
1836        if isfield(Param,'CheckOverwrite')
1837            CheckOverwrite=Param.CheckOverwrite;% will overwrite previous data if it is equal to 1
1838        end
1839        while detect
1840            if CheckOverwrite
1841                comment=', possibly overwrite previous data';
1842            else
1843                comment=', will complement existing result files (no overwriting)';
1844            end
1845            answer=msgbox_uvmat('INPUT_Y-N-Cancel',['use existing ouput directory: ' fullfile(PathExpDeviceOut,SubDirOutNew) comment]);
1846            if strcmp(answer,'Cancel')
1847                break
1848            elseif strcmp(answer,'Yes')
1849                detect=0;
1850                check_create=0;
1851            else
1852                r=regexp(SubDirOutNew,'(?<root>.*\D)(?<num1>\d+)$','names'); % detect whether name ends by a number
1853                if isempty(r)
1854                    r(1).root=[SubDirOutNew '_'];
1855                    r(1).num1='0';
1856                end
1857                SubDirOutNew=[r(1).root num2str(str2num(r(1).num1)+1)]; % increment the index by 1 or put 1
1858                detect=exist(fullfile(PathExpDeviceOut,SubDirOutNew),'dir'); % test if  the dir  already exists
1859                check_create=1;
1860            end
1861        end
1862        if strcmp(answer,'Cancel')
1863            continue
1864        end
1865        Param.OutputDirExt=regexprep(SubDirOutNew,['^' Param.OutputSubDir],'');
1866        Param.OutputRootFile=Param.InputTable{1,3}; % the first sorted RootFile taken for output
1867        OutputDir=fullfile(PathExpDeviceOut,[Param.OutputSubDir Param.OutputDirExt]); % full name (with path) of output directory
1868        if check_create    % create output directory if it does not exist
1869            [~,msg1]=mkdir(OutputDir);
1870            if ~strcmp(msg1,'')
1871                errormsg=['cannot create ' OutputDir ': ' msg1]; % error message for directory creation
1872                return
1873            end
1874        end
1875
1876    elseif isfield(Param,'ActionInput')&&isfield(Param.ActionInput,'LogPath')% custom definition of the output dir
1877        OutputDir=Param.ActionInput.LogPath;
1878    end
1879    if isfield(Param,'OutputSubDir')&& isfield(Param,'OutputDirExt')
1880        set(handles.OutputSubDir,'String',Param.OutputSubDir)
1881        set(handles.OutputDirExt,'String',Param.OutputDirExt)
1882        drawnow
1883    end
1884    if get(handles.Replicate,'Value')
1885        set(handles.InputTable,'Data',Param.InputTable)
1886        set(handles.OutputPath,'String',OutputPath)
1887         set(handles.Experiment,'String',ListExpOut{iexp})
1888        set(handles.Device,'String',ListDeviceOut{iexp})
1889        Param.Experiment=ListExpOut{iexp};
1890        Param.Device=ListDeviceOut{iexp};
1891        check_input_file_series(handles)
1892    end
1893    DirXml=fullfile(OutputDir,'0_XML');
1894    if ~exist(DirXml,'dir')
1895        [~,msg1]=mkdir(DirXml);
1896        if ~strcmp(msg1,'')
1897            errormsg=['cannot create ' DirXml ': ' msg1]; % error message for directory creation
1898            return
1899        end
1900        [success,msg] = fileattrib(DirXml,'+w','g','s'); % allow writing access for the group of users, recursively in the folder
1901        if success==0
1902            msgbox_uvmat('WARNING',{['unable to set group write access to ' DirXml ':']; msg}); % error message for directory creation
1903        end
1904    end
1905    OutputNomType=nomtype2pair(Param.InputTable{1,4}); % nomenclature for output files
1906
1907    %% get the set of reference input field indices
1908    first_i=1; % first i index to process
1909    last_i=1; % last i index to process
1910    incr_i=1; % increment step in i index
1911    first_j=1; % first j index to process
1912    last_j=1; % last j index to process
1913    incr_j=1; % increment step in j index
1914    if isfield(Param.IndexRange,'first_i')
1915        first_i=Param.IndexRange.first_i;
1916        incr_i=Param.IndexRange.incr_i;
1917        last_i=Param.IndexRange.last_i;
1918    end
1919    if isfield(Param.IndexRange,'incr_j')
1920        first_j=Param.IndexRange.first_j;
1921        last_j=Param.IndexRange.last_j;
1922        incr_j=Param.IndexRange.incr_j;
1923    end
1924    if last_i < first_i || last_j < first_j
1925        errormsg= 'series/Run_Callback:last field index must be larger or equal to the first one';
1926        return
1927    end
1928    %incr_i must be defined, =1 by default, if NbSlice is active
1929    if isempty(incr_i)&& ~isempty(Param.IndexRange.NbSlice)
1930        incr_i=1;
1931        set(handles.num_incr_i,'String','1')
1932    end
1933    % case of no increment i defined: processing is done on the available files found in i1_series
1934    if isempty(incr_i)
1935        if isempty(incr_j)
1936            [ref_j,ref_i]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1937            ref_j=ref_j(ref_j>=first_j & ref_j<=last_j);
1938            ref_i=ref_i(ref_i>=first_i & ref_i<=last_i);
1939            ref_j=ref_j-1;
1940            ref_i=ref_i-1;
1941        else
1942            ref_j=first_j:incr_j:last_j;
1943            [~,ref_i]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1944            ref_i=ref_i-1;
1945            ref_i=ref_i(ref_i>=first_i & ref_i<=last_i);
1946        end
1947        % increment i is defined: processing is done on first_i:incr_i:last_i;
1948    else
1949        ref_i=first_i:incr_i:last_i;
1950        if isempty(incr_j)% automatic finding of the existing j indices
1951            ref_j=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1952            ref_j=ref_j-1;
1953            ref_j=ref_j(ref_j>=first_j & ref_j<=last_j);
1954        else
1955            ref_j=first_j:incr_j:last_j;
1956        end
1957    end
1958    nbfield_j=numel(ref_j); % number of j indices
1959    BlockLength=numel(ref_i); % by default, job involves the full set of i field indicesNbProcess
1960    NbProcess=1;
1961    NbCore=1;
1962    switch RunMode
1963        case 'cluster'
1964            if (isfield(Param.Action, 'CPUTime') && ~isempty(Param.Action.CPUTime) && isnumeric(Param.Action.CPUTime))
1965                CPUTime=Param.Action.CPUTime; % Note: CpUTime for one iteration ref_i has to be multiplied by the number of j indices nbfield_j
1966            else
1967                answer=msgbox_uvmat('INPUT_TXT','estimate the CPU time(in minutes) for each value of index i:' ,'');
1968                CPUTime=str2double(answer);
1969                set(handles.num_CPUTime,'String',answer)
1970                Param.Action.CPUTime=CPUTime;
1971            end
1972            if isfield(SeriesData.ClusterParam,'JobNumberMax')
1973                JobNumberMax=SeriesData.ClusterParam.JobNumberMax;
1974            else
1975                disp('ClusterParam.JobNumberMax not documented in series.xml, set to 500 by default')
1976                JobNumberMax=500;
1977            end
1978            if isfield(SeriesData.ClusterParam,'JobCPUTimeAdvised')
1979                JobCPUTimeAdvised=SeriesData.ClusterParam.JobCPUTimeAdvised;
1980            else
1981                disp('ClusterParam.JobCPUTimeAdvised not documented in series.xml, set to 120 minutes by default')
1982                JobCPUTimeAdvised=120;
1983            end
1984            if isempty(Param.IndexRange.NbSlice)% if NbSlice is not defined
1985                BlockLength= ceil(JobCPUTimeAdvised/(CPUTime*nbfield_j)); % iterations are grouped in sets with length BlockLength  such that the typical CPU time of a job is JobCPUTimeAdvised.
1986                BlockLength=max(BlockLength,ceil(numel(ref_i)*NbExp/JobNumberMax)); % possibly increase the BlockLength to have less than MaxJobNumber jobs
1987                NbProcess=ceil(numel(ref_i)/BlockLength) ; % nbre of processes sent to oar
1988            else
1989                NbProcess=Param.IndexRange.NbSlice; % the parameter NbSlice sets the nbre of run processes
1990            end
1991           
1992            %         %proposed number of cores to reserve in the cluster
1993             if isfield(SeriesData.ClusterParam,'NbCoreAdvised')
1994                NbCoreAdvised=SeriesData.ClusterParam.NbCoreAdvised;
1995            else
1996                disp('ClusterParam.NbCoreAdvised not documented in series.xml, set to 16 by default')
1997                NbCoreAdvised=16;
1998             end
1999                if isfield(SeriesData.ClusterParam,'NbCoreMax')
2000                NbCoreMax=min(NbProcess,SeriesData.ClusterParam.NbCoreMax);% reduces the number of cores if it exceeds the number of processes
2001            else
2002                disp('ClusterParam.NbCoreMax not documented in series.xml, set to 36 by default')
2003                NbCoreMax=min(NbProcess,36);
2004                end
2005            if NbCoreMax~=1
2006                if strcmp(ActionExt,'.m')% case of Matlab function (uncompiled)
2007                    warning_string=', preferably use .sh option to save Matlab licences';
2008                else
2009                    warning_string=')';
2010                end
2011                answer=msgbox_uvmat('INPUT_TXT',['Number of cores (limited to ' num2str(NbCoreMax) warning_string],num2str(NbCoreAdvised));
2012                if isempty(answer)||strcmp(answer,'Cancel')
2013                    errormsg='Action launch interrupted by user';
2014                    return
2015                end
2016                NbCore=str2double(answer);
2017                if NbCore > NbCoreMax
2018                    NbCore=NbCoreMax;
2019                end
2020            end
2021        otherwise
2022            if ~isempty(Param.IndexRange.NbSlice)
2023                NbProcess=Param.IndexRange.NbSlice; % the parameter NbSlice sets the nbre of run processes
2024            end
2025    end
2026
2027    %% record nbre of output files and starting time for computation for status
2028    StatusData=get(handles.status,'UserData');
2029    if isfield(StatusData,'OutputFileMode')
2030        switch StatusData.OutputFileMode
2031            case 'NbInput'
2032                StatusData.NbOutputFile=numel(ref_i)*nbfield_j;
2033            case 'NbInput_i'
2034                StatusData.NbOutputFile=numel(ref_i);
2035            case 'NbSlice'
2036                StatusData.NbOutputFile=str2num(get(handles.num_NbSlice,'String'));
2037        end
2038    end
2039    StatusData.TimeStart=now;
2040    set(handles.status,'UserData',StatusData)
2041
2042    %% case of a function in Python
2043    if strcmp(ActionExt, 'fluidimage')
2044        fprintf([
2045            '\n' ...
2046            '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n' ...
2047            'The computation should be done by fluidimage (https://fluidimage.readthedocs.io).\n' ...
2048            'Warning: Fluidimage parameters will be guessed from UVmat parameters but \n' ...
2049            'there is no direct correspondance between UVMAT and fluidimage parameters.\n' ...
2050            'Please report issues here https://foss.heptapod.net/fluiddyn/fluidimage/-/issues\n' ...
2051            '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n'])
2052        RunMode = 'python';
2053    end
2054
2055
2056    %% direct processing on the current Matlab session or creation of command files
2057    filexml=cell(1,NbProcess); % initialisation of the names of the files containing the processing parameters
2058    extxml=cell(1,NbProcess); % initialisation of the set of labels used for the files documenting each process
2059    for iprocess=1:NbProcess
2060        extxml{iprocess}='.xml';
2061    end
2062    for iprocess=1:NbProcess
2063        if ~strcmp(get(handles.RUN,'BusyAction'),'queue')% allow for STOP action
2064            disp('program stopped by user')
2065            return
2066        end
2067        Param.IndexRange.incr_slice=incr_i;
2068        if isempty(Param.IndexRange.NbSlice)
2069            Param.IndexRange.first_i=first_i+(iprocess-1)*BlockLength*incr_i;
2070            if Param.IndexRange.first_i>last_i
2071                NbProcess=iprocess-1; % leave the loop, we are at the end of the calculation
2072                break
2073            end
2074            Param.IndexRange.last_i=min(last_i,first_i+(iprocess)*BlockLength*incr_i-1);
2075        else %multislices (then incr_i is not empty)
2076            Param.IndexRange.first_i= first_i+iprocess-1;
2077            Param.IndexRange.incr_slice=incr_i*Param.IndexRange.NbSlice;
2078        end
2079        for ilist=1:size(Param.InputTable,1)
2080            Param.InputTable{ilist,1}=regexprep(Param.InputTable{ilist,1},'\','/'); % correct path name for PCWIN system
2081        end
2082
2083        if isfield(Param,'OutputSubDir')
2084            t=struct2xml(Param);
2085            t=set(t,1,'name','Series');
2086            extxml{iprocess}=fullfile_uvmat('','',Param.InputTable{1,3},'.xml',OutputNomType,...
2087                Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
2088            filexml{iprocess}=fullfile(OutputDir,'0_XML',extxml{iprocess});
2089            try
2090                save(t, filexml{iprocess}); % save the xml file containing the processing parameters
2091            catch ME
2092                if ~strcmp (RunMode,'local')
2093                    errormsg=['error writting ' filexml{iprocess} ': ' ME.message];
2094                    return
2095                end
2096            end
2097        end
2098        if strcmp (RunMode,'local')
2099            switch ActionExt
2100                case '.m'
2101                    h_fun(Param); % direct launching
2102
2103                case '.sh'
2104                    switch computer
2105                        case {'PCWIN','PCWIN64'} %Windows system
2106                            filexml=regexprep(filexml,'\\','\\\\'); % add '\' so that '\' are left as characters
2107                            system([ActionFullName ' ' RunTime ' ' filexml{iprocess}]); % TODO: adapt to DOS system
2108                        case {'GLNX86','GLNXA64','MACI64'}%Linux  system
2109                            system([ActionFullName ' ' RunTime ' ' filexml{iprocess}]);
2110                    end
2111            end
2112        end
2113    end
2114
2115    if ~strcmp (RunMode,'local') && ~strcmp(RunMode,'python')
2116        %% processing on a different session of the same computer (background) or cluster, create executable files
2117        batch_file_list=cell(NbProcess,1); % initiate the list of executable files
2118        DirExe=fullfile(OutputDir,'0_EXE'); % directory name for executable files
2119        switch computer
2120            case {'PCWIN','PCWIN64'} %Windows system
2121                ExeExt='.bat';
2122            case {'GLNX86','GLNXA64','MACI64'}%Linux  system
2123                ExeExt='.sh';
2124        end
2125        %create subdirectory for executable files
2126        if ~exist(DirExe,'dir')
2127            [tild,msg1]=mkdir(DirExe);
2128            if ~strcmp(msg1,'')
2129                errormsg=['cannot create ' DirExe ': ' msg1]; % error message for directory creation
2130                return
2131            end
2132            [success,msg] = fileattrib(DirExe,'+w','g','s'); % allow writing access for the group of users, recursively in the folder
2133            if success==0
2134                msgbox_uvmat('WARNING',{['unable to set group write access to ' DirExe ':']; msg}); % error message for directory creation
2135            end
2136        end
2137        %create subdirectory for log files
2138        DirLog=fullfile(OutputDir,'0_LOG');
2139        if ~exist(DirLog,'dir')
2140            [tild,msg1]=mkdir(DirLog);
2141            if ~strcmp(msg1,'')
2142                errormsg=['cannot create ' DirLog ': ' msg1]; % error message for directory creation
2143                return
2144            end
2145            [success,msg] = fileattrib(DirLog,'+w','g','s'); % allow writing access for the group of users, recursively in the folder
2146            if success==0
2147                msgbox_uvmat('WARNING',{['unable to set group write access to ' DirLog ':']; msg}); % error message for directory creation
2148            end
2149        end
2150
2151        %create the executable and log file names
2152        file_exe_global=fullfile_uvmat('','',Param.InputTable{1,3},ExeExt,OutputNomType,...
2153            first_i,last_i,first_j,last_j);
2154        file_exe_global=fullfile(OutputDir,'0_EXE',file_exe_global);
2155        filelog_global=fullfile_uvmat('','',Param.InputTable{1,3},'.log',OutputNomType,...
2156            first_i,last_i,first_j,last_j);
2157        filelog_global=fullfile(OutputDir,'0_LOG',filelog_global);
2158
2159        for iprocess=1:NbProcess
2160            batch_file_list{iprocess}=fullfile(OutputDir,'0_EXE',regexprep(extxml{iprocess},'.xml$',ExeExt)); % executable file names
2161            filelog{iprocess}=fullfile(OutputDir,'0_LOG',regexprep(extxml{iprocess},'.xml$','.log'));% corresponding log file names
2162        end
2163    end
2164
2165    %% launch the executable files for background or cluster processing
2166
2167    switch RunMode
2168
2169        case 'background'
2170            [fid,message]=fopen(file_exe_global,'w');
2171            if isequal(fid,-1)
2172                errormsg=['creation of ' file_exe_global ':' message];
2173                return
2174            end
2175            switch ActionExt
2176                case '.m'% Matlab function
2177                    switch computer
2178                        case {'GLNX86','GLNXA64','MACI64'}
2179                            cmd=command_launch_matlab(filelog_global,path_series,Param.Action.ActionPath,Param.Action.ActionName,filexml,'background');
2180                            fprintf(fid,cmd); % fill the executable file with the  char string cmd
2181                            fclose(fid); % close the executable filefilelog_global
2182                            system(['chmod +x ' file_exe_global]); % set the file to executable
2183                        case {'PCWIN','PCWIN64'}
2184                            cmd=['matlab -automation -logfile ' regexprep(filelog{iprocess},'\\','\\\\')...
2185                                ' -r "addpath(''' regexprep(path_series,'\\','\\\\') ''');'...
2186                                'addpath(''' regexprep(Param.Action.ActionPath,'\\','\\\\') ''');'];
2187                            for iprocess=1:NbProcess
2188                                cmd=[cmd '' Param.Action.ActionName  '( ''' regexprep(filexml{iprocess},'\\','\\\\') ''');']
2189                            end
2190                            cmd=[cmd ';exit"'];
2191                            fprintf(fid,cmd); % fill the executable file with the  char string cmd
2192                            fclose(fid); % close the executable file
2193                    end
2194                    system([file_exe_global ' &'])% directly execute the command file
2195                case '.sh' % compiled Matlab function
2196                    for iprocess=1:NbProcess
2197                        switch computer
2198                            case {'GLNX86','GLNXA64','MACI64'}
2199                                [fid,message]=fopen(batch_file_list{iprocess},'w'); % create the executable file
2200                                if isequal(fid,-1)
2201                                    errormsg=['creation of .bat file: ' message];
2202                                    return
2203                                end
2204                                cmd=['#!/bin/bash \n '...
2205                                    '#$ -cwd \n '...
2206                                    'hostname && date \n '...
2207                                    'umask 002 \n'...
2208                                    ActionFullName ' ' RunTime ' ' filexml{iprocess}]; % allow writting access to created files for user group
2209                                fprintf(fid,cmd); % fill the executable file with the  char string cmd
2210                                fclose(fid); % close the executable file
2211                                system(['chmod +x ' batch_file_list{iprocess}]); % set the file to executable
2212                                system([batch_file_list{iprocess} ' &'])% directly execute the command file
2213                            case {'PCWIN','PCWIN64'}
2214                                msgbox_uvmat('ERROR','option for compiled Matlab functions not implemented for Windows system')
2215                                return
2216                        end
2217                    end
2218                    msgbox_uvmat('CONFIRMATION',[ActionFullName ' launched in background for ' ExpName ': press STATUS to see results'])
2219            end
2220
2221        case 'cluster' % option 'oar-parexec' used
2222            %create subdirectory for oar commands
2223            for iprocess=1:NbProcess
2224                [fid,message]=fopen(batch_file_list{iprocess},'w'); % create the executable file
2225                if isequal(fid,-1)
2226                    errormsg=['creation of .bat file: ' message];
2227                    return
2228                end
2229                if  strcmp(ActionExt,'.sh')
2230                    cmd=['#!/bin/bash \n '...
2231                        '#$ -cwd \n '...
2232                        'hostname && date \n '...
2233                        'umask 002 \n'...
2234                        ActionFullName ' ' RunTime ' ' filexml{iprocess}]; % allow writting access to created files for user group
2235                else
2236                    cmd=command_launch_matlab(filelog_global,path_series,Param.Action.ActionPath,Param.Action.ActionName,filexml{iprocess},'cluster');
2237 
2238                end
2239                fprintf(fid,cmd); % fill the executable file with the  char string cmd
2240                fclose(fid); % close the executable file
2241                system(['chmod +x ' batch_file_list{iprocess}]); % set the file to executable
2242            end
2243            DIR_CLUSTER=fullfile(OutputDir,'0_CLUSTER');
2244            if exist(DIR_CLUSTER,'dir')% delete the content of the dir 0_LOG to allow new input
2245                curdir=pwd;
2246                cd(DIR_CLUSTER)
2247                delete('*')
2248                cd(curdir)
2249            else
2250                [~,msg1]=mkdir(DIR_CLUSTER);
2251                if ~strcmp(msg1,'')
2252                    errormsg=['cannot create ' DIR_CLUSTER ': ' msg1]; % error message for directory creation
2253                    return
2254                end
2255            end
2256            % create file containing the list of jobs
2257            ListProcess=fullfile(DIR_CLUSTER,'job_list.txt'); % name of the file containing the list of executables
2258            [fid,errormsg]=fopen(ListProcess,'w'); % open it for writting
2259            if isempty(errormsg)
2260            for iprocess=1:length(batch_file_list)
2261                fprintf(fid,[batch_file_list{iprocess} '\n']); % write list of exe files
2262            end
2263            fclose(fid);
2264            system(['chmod +x ' ListProcess]); % set the file to executable
2265            else
2266                errormsg=['error for writting the executable file:' errormsg];
2267            end
2268            CPUTimeProcess=CPUTime*BlockLength*nbfield_j; % estimated CPU time for one individual process (in minutes)
2269            if isfield(SeriesData.ClusterParam,'LaunchCmdFcn')&& exist(SeriesData.ClusterParam.LaunchCmdFcn,'file')
2270            LaunchCmdFcn=SeriesData.ClusterParam.LaunchCmdFcn;% command obtained from the function
2271            else
2272                disp('no ClusterParam.LaunchCmdFcn defined in series.xml')
2273                return
2274            end
2275            oar_command=feval(LaunchCmdFcn,ListProcess,ActionFullName,DirLog,NbProcess, NbCore,CPUTimeProcess)
2276            [status,result]=system(oar_command)% execute system command and show the result (ID number of the launched job) on the Matlab command window
2277            filename_oarcommand=fullfile(DIR_CLUSTER,'0_cluster_command'); % keep track of the command in file '0-OAR/0_cluster_command'
2278            [fid,errormsg]=fopen(filename_oarcommand,'w');
2279            if ~isempty(errormsg)
2280                msgbox_uvmat('ERROR',['cannot create ' filename_oarcommand ': ' errormsg])
2281                return
2282            end
2283            fprintf(fid,oar_command); % store the command
2284            fprintf(fid,result); % store the result (job ID number)
2285            fclose(fid);
2286            if status==0
2287                msgbox_uvmat('CONFIRMATION',[ActionFullName ' launched for ' ExpName ' as ' num2str(NbProcess) ' processes in cluster: press STATUS to see results'])
2288            else
2289                msgbox_uvmat('ERROR',result)
2290            end
2291            %     case 'cluster_pbs' % for LMFA Kepler machine:  trqnsferred to fct
2292
2293            %         %create subdirectory for pbs command and log files
2294            %         DirPBS=fullfile(OutputDir,'0_PBS'); % todo : common name OAR/PBS
2295            %         if exist(DirPBS,'dir')% delete the content of the dir 0_LOG to allow new input
2296            %             curdir=pwd;
2297            %             cd(DirPBS)
2298            %             delete('*')
2299            %             cd(curdir)
2300            %         else
2301            %             [tild,msg1]=mkdir(DirPBS);
2302            %             if ~strcmp(msg1,'')
2303            %                 errormsg=['cannot create ' DirPBS ': ' msg1]; % error message for directory creation
2304            %                 return
2305            %             end
2306            %         end
2307            %         max_walltime=3600*20; % 20h max total calculation (cannot exceed 24 h)
2308            %         walltime_onejob=1800; % seconds, max estimated time for asingle file index value
2309            %         ListProcess=fullfile(DirPBS,'job_list.txt'); % create name of the global executable file
2310            %         fid=fopen(ListProcess,'w');
2311            %         for iprocess=1:length(batch_file_list)
2312            %             fprintf(fid,[batch_file_list{iprocess} '\n']); % list of exe files
2313            %         end
2314            %         fclose(fid);
2315            %         system(['chmod +x ' ListProcess]); % set the file to executable
2316            %         pbs_command=['qsub -n CIVX '...
2317            %             '-t idempotent --checkpoint ' num2str(walltime_onejob+60) ' '...
2318            %             '-l /core=' num2str(NbCore) ','...
2319            %             'walltime=' datestr(min(1.05*walltime_onejob/86400*max(NbProcess*BlockLength*nbfield_j,NbCore)/NbCore,max_walltime/86400),13) ' '...
2320            %             '-E ' regexprep(ListProcess,'\.txt\>','.stderr') ' '...
2321            %             '-O ' regexprep(ListProcess,'\.txt\>','.log') ' '...
2322            %             extra_qstat ' '...
2323            %             '"oar-parexec -s -f ' ListProcess ' '...
2324            %             '-l ' ListProcess '.log"'];
2325            %         filename_oarcommand=fullfile(DirPBS,'pbs_command');
2326            %         fid=fopen(filename_oarcommand,'w');
2327            %         fprintf(fid,pbs_command);
2328            %         fclose(fid);
2329            %         fprintf(pbs_command); % display in command line
2330            %         %system(pbs_command);
2331            %         msgbox_uvmat('CONFIRMATION',[ActionFullName ' command ready to be launched in cluster'])
2332
2333        case 'cluster_sge' % for PSMN % TODO: use the standard 'cluster' config with an external fct
2334            % Au PSMN, on ne cr??e pas 1 job avec plusieurs c??urs, mais N jobs de 1 c??urs
2335            % o?? N < 1000.
2336            %create subdirectory for pbs command and log files
2337
2338            DirSGE=fullfile(OutputDir,'0_SGE');
2339            if exist(DirSGE,'dir')% delete the content of the dir 0_LOG to allow new input
2340                curdir=pwd;
2341                cd(DirSGE)
2342                delete('*')
2343                cd(curdir)
2344            else
2345                [~,msg1]=mkdir(DirSGE);
2346                if ~strcmp(msg1,'')
2347                    errormsg=['cannot create ' DirSGE ': ' msg1]; % error message for directory creation
2348                    return
2349                end
2350            end
2351            maxImgsPerJob = ceil(length(batch_file_list)/NbCore);
2352            disp(['Max number of jobs: ' num2str(NbCore)])
2353            disp(['Images per job: ' num2str(maxImgsPerJob)])
2354
2355            iprocess = 1;
2356            imgsInJob = [];
2357            currJobIndex = 1;
2358            done = 0;
2359            while(~done)
2360                if(iprocess <= length(batch_file_list))
2361                    imgsInJob = [imgsInJob, iprocess];
2362                end
2363                if((numel(imgsInJob) >= maxImgsPerJob) || (iprocess == length(batch_file_list)))
2364                    cmd=['#!/bin/sh \n'...
2365                        '#$ -cwd \n'...
2366                        'hostname && date\n']
2367                    for ii=1:numel(imgsInJob)
2368                        cmd=[cmd ActionFullName ' /softs/matlab ' filexml{imgsInJob(ii)} '\n'];
2369                    end
2370                    fid = fopen([DirSGE '/job' num2str(currJobIndex) '.sh'], 'w');
2371                    fprintf(fid, cmd);
2372                    fclose(fid);
2373                    system(['chmod +x ' DirSGE '/job' num2str(currJobIndex) '.sh'])
2374                    sge_command=['qsub -N civ_' num2str(currJobIndex) ' '...
2375                        '-q ' qstat_Queue ' '...
2376                        '-e ' fullfile([DirSGE '/job' num2str(currJobIndex) '.out']) ' '...
2377                        '-o ' fullfile([DirSGE '/job' num2str(currJobIndex) '.out']) ' '...
2378                        fullfile([DirSGE '/job' num2str(currJobIndex) '.sh'])];
2379                    fprintf(sge_command); % display in command line
2380                    [~, result] = system(sge_command);
2381                    fprintf(result);
2382                    currJobIndex = currJobIndex + 1;
2383                    imgsInJob = [];
2384                end
2385                if(iprocess == length(batch_file_list))
2386                    done = 1;
2387                end
2388                iprocess = iprocess + 1;
2389            end
2390            msgbox_uvmat('CONFIRMATION',[num2str(currJobIndex-1) ' jobs launched on queue ' qstat_Queue '.'])
2391        case 'python'
2392            command = ['python -m fluidimage.run_from_xml ' filexml{iprocess}];
2393            fprintf(['command:\n' command '\n\n'])
2394          %  [status, result] = call_command_clean(command);
2395    end
2396    if exist(OutputDir,'dir')
2397        [~,MESSAGE] = fileattrib (OutputDir);
2398        if MESSAGE.GroupWrite~=1
2399            [success,msg] = fileattrib(OutputDir,'+w','g','s'); % allow writing access for the group of users, recursively in the folder
2400            if success==0
2401                msgbox_uvmat('WARNING',{['unable to set group write access to ' OutputDir ':']; msg}); % error message for directory creation
2402            end
2403        end
2404    end
2405end
2406set(handles.Replicate,'BackgroundColor',[0 1 0])
2407
2408%------------------------------------------------------------------------
2409function STOP_Callback(hObject, eventdata, handles)
2410%------------------------------------------------------------------------
2411set(handles.RUN, 'BusyAction','cancel')
2412set(handles.RUN,'BackgroundColor',[1 0 0])
2413set(handles.RUN,'enable','on')
2414set(handles.RUN, 'Value',0)
2415
2416%------------------------------------------------------------------------
2417% --- read parameters from the GUI series
2418%------------------------------------------------------------------------
2419function Param=read_GUI_series(handles)
2420
2421%% read raw parameters from the GUI series
2422Param=read_GUI(handles.series);
2423
2424%% clean the output structure by removing unused information
2425if isfield(Param,'Pairs')
2426    Param=rmfield(Param,'Pairs'); % info Pairs not needed for output
2427end
2428if isfield(Param,'InputLine')
2429    Param=rmfield(Param,'InputLine');
2430end
2431if isfield(Param,'EditObject')
2432    Param=rmfield(Param,'EditObject');
2433end
2434Param.IndexRange.TimeSource=Param.IndexRange.TimeTable{end,1};
2435Param.IndexRange=rmfield(Param.IndexRange,'TimeTable');
2436empty_line=false(size(Param.InputTable,1),1);
2437for iline=1:size(Param.InputTable,1)
2438    empty_line(iline)=isempty(cell2mat(Param.InputTable(iline,1:3)));
2439end
2440Param.InputTable(empty_line,:)=[];
2441
2442%------------------------------------------------------------------------
2443% --- Executes on selection change in ActionName.
2444function ActionName_Callback(hObject, ActionPath, handles)
2445%------------------------------------------------------------------------
2446
2447%% stop any ongoing series processing
2448if isequal(get(handles.RUN,'Value'),1)
2449    answer= msgbox_uvmat('INPUT_Y-N','stop current Action process?');
2450    if strcmp(answer,'Yes')
2451        STOP_Callback(hObject, [], handles)
2452    else
2453        return
2454    end
2455end
2456set(handles.ActionName,'BackgroundColor',[1 1 0])
2457huigetfile=findobj(allchild(0),'tag','status_display');
2458if ~isempty(huigetfile)
2459    delete(huigetfile)
2460end
2461drawnow
2462
2463%% get Action name and path
2464NbBuiltinAction=get(handles.Action,'UserData'); % nbre of functions initially proposed in the menu ActionName (as defined in the Opening fct of series)
2465ActionList=get(handles.ActionName,'String'); % list menu fields
2466ActionIndex=get(handles.ActionName,'Value');
2467if ~isequal(ActionIndex,1)% if we are not just opening series
2468    InputTable=get(handles.InputTable,'Data');
2469    if isempty(InputTable{1,4})
2470        msgbox_uvmat('ERROR','no input file available: use Open in the menu bar')
2471        return
2472    end
2473end
2474ActionName= ActionList{get(handles.ActionName,'Value')}; % selected function name
2475ActionPathList=get(handles.ActionName,'UserData'); % list of recorded paths to functions of the list ActionName
2476
2477%% add a new function to the menu if 'more...' has been selected in the menu ActionName
2478if isequal(ActionName,'more...')
2479    if ~ischar(ActionPath)
2480        ActionPath=get(handles.ActionPath,'String');
2481    end
2482    [FileName, PathName] = uigetfile( ...
2483        {'*.m', ' (*.m)';
2484        '*.m',  '.m files '; ...
2485        '*.*', 'All Files (*.*)'}, ...
2486        'Pick a series processing function ',ActionPath);
2487    if length(FileName)<2
2488        return
2489    end
2490    [~,ActionName,ActionExt]=fileparts(FileName);
2491
2492    % insert the choice in the menu ActionName
2493    ActionIndex=find(strcmp(ActionName,ActionList),1); % look for the selected function in the menu Action
2494    PathName=regexprep(PathName,'/$','');
2495    if ~isempty(ActionIndex) && ~strcmp(ActionPathList{ActionIndex},PathName)%compare the path to the existing fct
2496        ActionIndex=[]; % the selected path is different than the recorded one
2497    end
2498    if isempty(ActionIndex)%the qselected fct (with selected path) does not exist in the menu
2499        ActionIndex= length(ActionList);
2500        ActionList=[ActionList(1:end-1);{ActionName};ActionList(end)]; % the selected function is appended in the menu, before the last item 'more...'
2501         ActionPathList=[ActionPathList; PathName];
2502    end
2503
2504    % record the file extension and extend the path list if it is a new extension
2505    ActionExtList=get(handles.ActionExt,'String');
2506    ActionExtIndex=find(strcmp(ActionExt,ActionExtList), 1);
2507    if isempty(ActionExtIndex)
2508        set(handles.ActionExt,'String',[ActionExtList;{ActionExt}])
2509    end
2510
2511    % remove old Action options in the menu (keeping a menu length <nb_builtin_ACTION+5)
2512    if length(ActionList)>NbBuiltinAction+5% nb_builtin_ACTION=nbre of functions always remaining in the initial menu
2513        nbremove=length(ActionList)-NbBuiltinAction-5;
2514        ActionList(NbBuiltinAction+1:end-5)=[];
2515        ActionPathList(NbBuiltinAction+1:end-4,:)=[];
2516        ActionIndex=ActionIndex-nbremove;
2517    end
2518
2519    % record action menu, choice and path
2520    set(handles.ActionName,'Value',ActionIndex)
2521    set(handles.ActionName,'String',ActionList)
2522       set(handles.ActionName,'UserData',ActionPathList);
2523    set(handles.ActionExt,'Value',ActionExtIndex)
2524
2525    %record the user defined menu additions in personal file profil_perso
2526    dir_perso=prefdir;
2527    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
2528    if NbBuiltinAction+1<=numel(ActionList)-1
2529        ActionListUser=ActionList(NbBuiltinAction+1:numel(ActionList)-1);
2530        ActionPathListUser=ActionPathList(NbBuiltinAction+1:numel(ActionList)-1);
2531        ActionExtListUser={};
2532        if numel(ActionExtList)>2
2533            ActionExtListUser=ActionExtList(3:end);
2534        end
2535        if exist(profil_perso,'file')
2536            save(profil_perso,'ActionListUser','ActionPathListUser','ActionExtListUser','-append')
2537        else
2538            save(profil_perso,'ActionListUser','ActionPathListUser','ActionExtListUser','-V6')
2539        end
2540    end
2541end
2542
2543%% check the current ActionPath to the selected function
2544ActionPath=ActionPathList{ActionIndex}; % current recorded path
2545set(handles.ActionPath,'String',ActionPath); % show the path to the selected function
2546
2547%% reinitialise the waitbar
2548update_waitbar(handles.Waitbar,0)
2549
2550%% Put the first line of the selected Action fct as tooltip help
2551try
2552    fid=fopen([fullfile(ActionPath,ActionName) '.m']);
2553    InputText=textscan(fid,'%s',1,'delimiter','\n');
2554    fclose(fid);
2555    set(handles.ActionName,'ToolTipString',InputText{1}{1})% put the first line of the selected function as tooltip help
2556end
2557set(handles.ActionName,'BackgroundColor',[1 1 1])
2558set(handles.ActionInput,'BackgroundColor',[1 0 1])% set ActionInput button to magenta color to indicate that input refr
2559set(handles.num_CPUTime,'String','')
2560
2561% --- Executes on button press in ActionInput.
2562function ActionInput_Callback(hObject, eventdata, handles)
2563
2564set(handles.ActionInput,'BackgroundColor',[1 1 0])
2565SeriesData=get(handles.series,'UserData'); % info on the input file series
2566
2567%% create the function handle for Action
2568ActionPath=get(handles.ActionPath,'String');
2569ActionList=get(handles.ActionName,'String');
2570ActionName= ActionList{get(handles.ActionName,'Value')}; % selected function name
2571if ~exist(ActionPath,'dir')
2572    ActionName_Callback(handles.ActionName, ActionPath, handles)% update the function
2573    return
2574end
2575current_dir=pwd; % current working dir
2576cd(ActionPath)
2577h_fun=str2func(ActionName);% create the function handle for the function ActionName
2578cd(current_dir)
2579
2580%% Activate the Action fct to adapt the configuration of the GUI series and bring specific parameters in SeriesData
2581Param=read_GUI_series(handles); % read the parameters from the GUI series
2582Param.Action.RUN=0;% indicate that we are in the mode of parameter input, not program run
2583Param.SeriesData=SeriesData;% info stored in 'UserData' of the fig 'series'
2584ParamOut=h_fun(Param); % run the selected Action function to get the relevant input
2585
2586
2587%% Visibility of VelType and VelType_1 menus asked by ActionName
2588VelTypeRequest=1; % VelType requested by default
2589VelTypeRequest_1=1; % VelType requested by default
2590if isfield(ParamOut,'VelType')
2591    VelTypeRequest=ismember(ParamOut.VelType,{'on','one','two'});
2592    VelTypeRequest_1=strcmp( ParamOut.VelType,'two');
2593end
2594FieldNameRequest=0;  %hidden by default
2595FieldNameRequest_1=0;  %hidden by default
2596if isfield(ParamOut,'FieldName')
2597    FieldNameRequest=ismember(ParamOut.FieldName,{'on','one','two'});
2598    FieldNameRequest_1=strcmp( ParamOut.FieldName,'two');
2599end
2600
2601%% Detect the types of input files and set menus and default options in 'VelType'
2602% if ~isfield(SeriesData,'FileType')
2603%     SeriesData.FileType={'none'};
2604% end
2605iview_civ=[];
2606iview_netcdf=[];
2607for iview=1:numel(SeriesData.FileInfo)
2608    if ismember(SeriesData.FileInfo{iview}.FileType,{'civx','civdata','civdata_compress','netcdf'})
2609         iview_netcdf=[iview_netcdf iview];
2610         if ismember(SeriesData.FileInfo{iview}.FileType,{'civx','civdata','civdata_compress'})
2611             iview_civ=[iview_civ iview];
2612         end
2613    end
2614end
2615
2616FieldList=get(handles.FieldName,'String'); % previous list as default
2617if ~iscell(FieldList),FieldList={FieldList};end
2618FieldList_1=get(handles.FieldName_1,'String'); % previous list as default
2619% if ~iscell(FieldList_1),FieldList_1={FieldList_1};end
2620CheckPivData_1=0; % indicate whether FieldName_1 has been updated with civ data, 0 by default
2621handles_coord=[handles.Coord_x handles.Coord_y handles.Coord_z handles.Coord_x_title handles.Coord_y_title handles.Coord_z_title];
2622if VelTypeRequest && numel(iview_civ)>=1
2623    menu=set_veltype_display(SeriesData.FileInfo{iview_civ(1)}.CivStage,SeriesData.FileInfo{iview_civ(1)}.FileType);
2624    set(handles.VelType,'Value',1)% set first choice by default
2625    set(handles.VelType,'String',[{'*'};menu])
2626    set(handles.VelType,'Visible','on')
2627    set(handles.VelType_title,'Visible','on')
2628    FieldList=set_field_list('U','V'); % standard menu for civx data
2629    if max(get(handles.FieldName,'Value'))>numel(FieldList)
2630        set(handles.FieldName,'Value',1); % velocity vector choice by default
2631    end
2632    if  VelTypeRequest_1 && numel(iview_civ)>=2
2633        menu=set_veltype_display(SeriesData.FileInfo{iview_civ(2)}.CivStage,SeriesData.FileInfo{iview_civ(2)}.FileType);
2634        set(handles.VelType_1,'Value',1)% set first choice by default
2635        set(handles.VelType_1,'String',[{'*'};menu])
2636        set(handles.VelType_1,'Visible','on')
2637        set(handles.VelType_title_1,'Visible','on')
2638        FieldList_1=[set_field_list('U','V');{'C'};{'add_field...'}]; % standard menu for civx data
2639        CheckPivData_1=1;
2640        set(handles.FieldName_1,'Value',1); % velocity vector choice by default
2641    else
2642        set(handles.VelType_1,'Visible','off')
2643        set(handles.VelType_title_1,'Visible','off')
2644    end
2645else
2646    set(handles.VelType,'Visible','off')
2647    set(handles.VelType_title,'Visible','off')
2648end
2649
2650%% Detect the types of input files and set menus and default options in 'FieldName'
2651if (FieldNameRequest || VelTypeRequest) && numel(iview_netcdf)>=1
2652    set(handles.InputFields,'Visible','on')% set the frame InputFields visible
2653    if FieldNameRequest && isfield(SeriesData.FileInfo{iview_netcdf(1)},'ListVarName')
2654        set(handles.FieldName,'Visible','on')
2655        set(handles.Field_text,'Visible','on')
2656        ListVarName=SeriesData.FileInfo{iview_netcdf(1)}.ListVarName;
2657        ind_var=get(handles.FieldName,'Value'); % indices of previously selected variables
2658        for ilist=1:numel(ind_var)
2659            if isempty(find(strcmp(FieldList{ind_var(ilist)},ListVarName), 1))
2660                FieldList={}; % previous choice not consistent with new input field
2661                set(handles.FieldName,'Value',1)
2662                break
2663            end
2664        end
2665        if ~isempty(FieldList)
2666            if isempty(find(strcmp(get(handles.Coord_x,'String'),ListVarName), 1))||...
2667                    isempty(find(strcmp(get(handles.Coord_y,'String'),ListVarName), 1))
2668                FieldList={};
2669                set(handles.Coord_x,'String','')
2670                set(handles.Coord_y,'String','')
2671            end
2672            Coord_z=get(handles.Coord_z,'String');
2673            if ~isempty(Coord_z) && isempty(find(strcmp(Coord_z,ListVarName), 1))
2674                FieldList={};
2675                set(handles.Coord_z,'String','')
2676            end
2677        end
2678    else
2679        set(handles.FieldName,'Visible','off')
2680        set(handles.Field_text,'Visible','off')
2681    end
2682    set(handles_coord,'Visible','on')
2683    if isempty(find(strcmp('add_field...',FieldList), 1))
2684        FieldList=[FieldList;{'add_field...'}];%add 'add_field...' to the menu FieldName if it is not already
2685    end
2686    if FieldNameRequest_1 && numel(iview_netcdf)>=2
2687        set(handles.FieldName_1,'Visible','on')
2688        set(handles.Field_text_1,'Visible','on')
2689        if CheckPivData_1==0        % not civ input made
2690            FieldList_1={'add_field...'};
2691            ListVarName=SeriesData.FileInfo{iview_netcdf(2)}.ListVarName;
2692            ind_var=get(handles.FieldName,'Value'); % indices of previously selected variables
2693            for ilist=1:numel(ind_var)
2694                if isempty(find(strcmp(FieldList{ind_var(ilist)},ListVarName), 1))
2695                    %FieldList_1={}; % previous choice not consistent with new input field
2696                    set(handles.FieldName_1,'Value',1)
2697                    break
2698                end
2699            end
2700            warn_coord=0;
2701            if isempty(find(strcmp(get(handles.Coord_x,'String'),ListVarName), 1))||...
2702                    isempty(find(strcmp(get(handles.Coord_y,'String'),ListVarName), 1))
2703                warn_coord=1;
2704            end
2705            if ~isempty(Coord_z) && isempty(find(strcmp(Coord_z,ListVarName), 1))
2706                FieldList_1={'add_field...'};
2707                warn_coord=1;
2708            end
2709            if warn_coord
2710                msgbox_uvmat('WARNING','coordinate names do not exist in the second netcdf input file')
2711            end
2712
2713            set(handles.FieldName_1,'Visible','on')
2714            set(handles.FieldName_1,'Value',1)
2715            set(handles.FieldName_1,'String',FieldList_1)
2716        end
2717    else
2718        set(handles.FieldName_1,'Visible','off')
2719    end
2720    if isempty(FieldList)
2721        set(handles.Field_text,'Visible','off')
2722        set(handles.FieldName,'Visible','off')
2723    else
2724        set(handles.Field_text,'Visible','on')
2725        set(handles.FieldName,'Visible','on')
2726        set(handles.FieldName,'String',FieldList)
2727    end
2728else
2729    set(handles.InputFields,'Visible','off')
2730end
2731
2732%% Introduce visibility of file overwrite option
2733if isfield(ParamOut,'CheckOverwriteVisible')&& strcmp(ParamOut.CheckOverwriteVisible,'on')
2734    set(handles.CheckOverwrite,'Visible','on')
2735else
2736    set(handles.CheckOverwrite,'Visible','off')
2737end
2738
2739%% Check whether alphabetical sorting of input Subdir is allowed by the Action fct  (for multiples series entries)
2740if isfield(ParamOut,'AllowInputSort')&&isequal(ParamOut.AllowInputSort,'on')&& size(Param.InputTable,1)>1
2741    [~,iview]=sort(Param.InputTable(:,2)); % subdirectories sorted in alphabetical order
2742    set(handles.InputTable,'Data',Param.InputTable(iview,:));
2743    MinIndex_i=get(handles.MinIndex_i,'Data');
2744    MinIndex_j=get(handles.MinIndex_j,'Data');
2745    MaxIndex_i=get(handles.MaxIndex_i,'Data');
2746    MaxIndex_j=get(handles.MaxIndex_j,'Data');
2747    set(handles.MinIndex_i,'Data',MinIndex_i(iview,:));
2748    set(handles.MinIndex_j,'Data',MinIndex_j(iview,:));
2749    set(handles.MaxIndex_i,'Data',MaxIndex_i(iview,:));
2750    set(handles.MaxIndex_j,'Data',MaxIndex_j(iview,:));
2751    TimeTable=get(handles.TimeTable,'Data');
2752    if size(TimeTable,1)<size(Param.InputTable,1)%if the time table is not complete, copy the missing lines from the previous ones
2753        for iline=size(TimeTable,1)+1:size(Param.InputTable,1)
2754            TimeTable(iline,:)=TimeTable(iline-1,:);
2755        end
2756    end
2757    set(handles.TimeTable,'Data',TimeTable(iview,:));% sort the time tables
2758    PairString=get(handles.PairString,'Data');
2759    set(handles.PairString,'Data',PairString(iview,:));
2760end
2761
2762%% Impose the whole input file index range if requested
2763if ~isfield(ParamOut,'WholeIndexRange')
2764    ParamOut.WholeIndexRange='off';
2765end
2766if ~isfield(ParamOut,'IndexRange_j')
2767    ParamOut.IndexRange_j='on';% accept Index_j as input by default
2768end
2769if strcmp(ParamOut.WholeIndexRange,'on')
2770    MinIndex_i=get(handles.MinIndex_i,'Data');
2771    MaxIndex_i=get(handles.MaxIndex_i,'Data');
2772    set(handles.num_first_i,'String',num2str(MinIndex_i(1)))% set first as the min index (for the first line)
2773    set(handles.num_last_i,'String',num2str(MaxIndex_i(1)))% set last as the max index (for the first line)
2774    set(handles.num_incr_i,'String','1')
2775else
2776    first_i=1;last_i=1;
2777    if isfield(Param.IndexRange,'first_i')
2778        first_i=Param.IndexRange.first_i;
2779        last_i=Param.IndexRange.last_i;
2780    end
2781end
2782if strcmp(ParamOut.WholeIndexRange,'on')||strcmp(ParamOut.IndexRange_j,'whole')
2783    MinIndex_j=get(handles.MinIndex_j,'Data');
2784    MaxIndex_j=get(handles.MaxIndex_j,'Data');
2785    set(handles.num_first_j,'String',num2str(MinIndex_j(1)))% set first as the min index (for the first line)
2786    set(handles.num_last_j,'String',num2str(MaxIndex_j(1)))% set last as the max index (for the first line)
2787    set(handles.num_incr_j,'String','1')
2788else  % check index ranges
2789    first_j=1;last_j=1;
2790    if isfield(Param.IndexRange,'first_j')
2791        first_j=Param.IndexRange.first_j;
2792        last_j=Param.IndexRange.last_j;
2793    end
2794    if last_i < first_i || last_j < first_j , msgbox_uvmat('ERROR','last field number must be larger than the first one'),...
2795            set(handles.RUN, 'Enable','On'), set(handles.RUN,'BackgroundColor',[1 0 0]),return,end
2796end
2797num_first_i_Callback(hObject, eventdata, handles)
2798num_first_j_Callback(hObject, eventdata, handles)
2799
2800%% enable or desable j index visibility
2801if strcmp(ParamOut.IndexRange_j,'off')%do not show the j index
2802    enable_j(handles,'off')
2803else% show j index if relevant in the input series
2804    if isfield(SeriesData,'j1_series')
2805    j1_series=SeriesData.j1_series;
2806    for iview=1:size(j1_series,1)
2807        if ~isempty(j1_series{iview})
2808            enable_j(handles,'on')
2809            break
2810        end
2811    end
2812    end
2813end
2814
2815%% NbSlice visibility
2816if isfield(ParamOut,'NbSlice') && (strcmp(ParamOut.NbSlice,'on')||isnumeric(ParamOut.NbSlice))
2817    set(handles.num_NbSlice,'Visible','on')
2818    set(handles.NbSlice_title,'Visible','on')
2819    if isnumeric(ParamOut.NbSlice)
2820        set(handles.num_NbSlice,'String',num2str(ParamOut.NbSlice))
2821    end
2822else
2823    set(handles.num_NbSlice,'Visible','off')
2824    set(handles.NbSlice_title,'Visible','off')
2825end
2826if isfield(ParamOut,'NbSlice') && isnumeric(ParamOut.NbSlice)
2827    set(handles.num_NbSlice,'String',num2str(ParamOut.NbSlice))
2828    set(handles.num_NbSlice,'Enable','off'); % NbSlice set by the activation of the Action function
2829else
2830    set(handles.num_NbSlice,'Enable','on'); % NbSlice can be modified on the GUI series
2831end
2832
2833%% Visibility of FieldTransform menu
2834FieldTransformVisible='off';  %hidden by default
2835if isfield(ParamOut,'FieldTransform')
2836    if ~strcmp(ParamOut.FieldTransform,'off')
2837    FieldTransformVisible='on';
2838    end
2839    if iscell(ParamOut.FieldTransform)
2840        SeriesData.TransformList=ParamOut.FieldTransform;
2841    end
2842    TransformName_Callback([],[], handles)
2843end
2844set(handles.FieldTransform,'Visible',FieldTransformVisible)
2845if isfield(ParamOut,'TransformPath')% record the path of transform function requested for compilation
2846    set(handles.TransformPath,'UserData',ParamOut.TransformPath)
2847else
2848    set(handles.TransformPath,'UserData',[])
2849end
2850
2851%% Visibility of projection object
2852ProjObjectVisible='off';  %hidden by default
2853if isfield(ParamOut,'ProjObject')
2854    ProjObjectVisible=ParamOut.ProjObject;
2855end
2856set(handles.CheckObject,'Visible',ProjObjectVisible)
2857if ~get(handles.CheckObject,'Value')
2858    ProjObjectVisible='off';
2859end
2860set(handles.ProjObjectName,'Visible',ProjObjectVisible)
2861set(handles.DeleteObject,'Visible',ProjObjectVisible)
2862set(handles.ViewObject,'Visible',ProjObjectVisible)
2863set(handles.EditObject,'Visible',ProjObjectVisible)
2864
2865%% Visibility of mask input
2866MaskVisible='off';  %hidden by default
2867if isfield(ParamOut,'Mask')
2868    MaskVisible=ParamOut.Mask;
2869end
2870set(handles.CheckMask,'Visible',MaskVisible);
2871set(handles.MaskTable,'Visible',MaskVisible);
2872
2873%% Setting of expected iteration time
2874if isfield(ParamOut,'CPUTime')
2875    set(handles.num_CPUTime,'String',num2str(ParamOut.CPUTime));
2876end
2877
2878%% definition of the path for the output files
2879InputTable=get(handles.InputTable,'Data');
2880[OutputPath,Device,DeviceExt]=fileparts(InputTable{1,1});
2881[~,Experiment,ExperimentExt]=fileparts(OutputPath);
2882set(handles.Device,'String',[Device DeviceExt])
2883set(handles.Device,'Visible','on')
2884set(handles.Device_title,'Visible','on')
2885set(handles.Experiment,'String',[Experiment ExperimentExt])
2886set(handles.Experiment,'Visible','on')
2887set(handles.Experiment_title,'Visible','on')
2888set(handles.Experiment_title,'Visible','on')
2889set(handles.OutputPath,'Visible','on')
2890set(handles.OutputPathBrowse,'Visible','on')
2891
2892%% definition of the subdirectory containing the output files
2893if  ~(isfield(SeriesData,'ActionName') && strcmp(ActionName,SeriesData.ActionName))
2894    OutputDirExt='.series'; % default
2895    if isfield(ParamOut,'OutputDirExt')&&~isempty(ParamOut.OutputDirExt)
2896        OutputDirExt=ParamOut.OutputDirExt;
2897    end
2898    set(handles.OutputDirExt,'String',OutputDirExt)
2899end
2900OutputDirVisible='off';
2901OutputSubDirMode='auto'; % default
2902SubDirOut='';
2903if isfield(ParamOut,'OutputSubDirMode')
2904    OutputSubDirMode=ParamOut.OutputSubDirMode;
2905end
2906switch OutputSubDirMode
2907    case 'auto' % default
2908        OutputDirVisible='on';
2909        SubDir=InputTable(1:end,2); % set of subdirectories
2910        SubDirOut=SubDir{1};
2911        if numel(SubDir)>1
2912            for ilist=2:numel(SubDir)
2913                SubDirOut=[SubDirOut '-' regexprep(SubDir{ilist},'^/','')];
2914            end
2915        end
2916    case 'one'
2917        OutputDirVisible='on';
2918        SubDirOut=InputTable{1,2}; % use the first subdir name (+OutputDirExt) as output  subdirectory
2919    case 'two'
2920        OutputDirVisible='on';
2921        SubDir=InputTable(1:2,2); % set of subdirectories
2922        SubDirOut=SubDir{1};
2923        if numel(SubDir)>1
2924                SubDirOut=[SubDirOut '-' regexprep(SubDir{2},'^/','')];
2925        end
2926    case 'last'
2927        OutputDirVisible='on';
2928        SubDirOut=InputTable{end,2}; % use the last subdir name (+OutputDirExt) as output  subdirectory
2929end
2930set(handles.OutputSubDir,'String',SubDirOut)
2931set(handles.OutputSubDir,'BackgroundColor',[1 1 1])% set edit box to white color to indicate refreshment
2932set(handles.OutputDirExt,'Visible',OutputDirVisible)
2933set(handles.OutputSubDir,'Visible',OutputDirVisible)
2934SeriesData.ActionName=ActionName; % record ActionName for next use
2935
2936
2937%% visibility of the run mode (local or background or cluster)
2938if strcmp(OutputSubDirMode,'none')
2939    RunModeVisible='off'; % only local mode available if no output file is produced
2940else
2941    RunModeVisible='on';
2942end
2943set(handles.RunMode,'Visible',RunModeVisible)
2944set(handles.ActionExt,'Visible',RunModeVisible)
2945set(handles.RunMode_title,'Visible',RunModeVisible)
2946set(handles.ActionExt_title,'Visible',RunModeVisible)
2947
2948
2949%% Expected nbre of output files
2950if isfield(ParamOut,'OutputFileMode')
2951    StatusData.OutputFileMode=ParamOut.OutputFileMode;
2952    set(handles.status,'UserData',StatusData)
2953end
2954
2955%% definition of an additional parameter set, determined by an ancillary GUI
2956if isfield(ParamOut,'ActionInput')
2957    ParamOut.ActionInput.Program=ActionName; % record the program in ActionInput
2958    SeriesData.ActionInput=ParamOut.ActionInput;
2959else
2960    if isfield(SeriesData,'ActionInput')
2961        SeriesData=rmfield(SeriesData,'ActionInput');
2962    end
2963end
2964set(handles.series,'UserData',SeriesData)
2965set(handles.ActionInput,'BackgroundColor',[1 0 0])
2966
2967
2968%------------------------------------------------------------------------
2969% --- Executes on button press in RefreshField.
2970function RefreshField_Callback(hObject, eventdata, handles)
2971%------------------------------------------------------------------------
2972set(handles.FieldName,'String',{'add_field...'});
2973set(handles.FieldName,'Value',1);
2974FieldName_Callback(hObject, eventdata, handles)
2975
2976
2977%------------------------------------------------------------------------
2978% --- Executes on selection change in FieldName.
2979function FieldName_Callback(hObject, eventdata, handles)
2980%------------------------------------------------------------------------
2981FieldListInit=get(handles.FieldName,'String');
2982field_index=get(handles.FieldName,'Value');
2983field=FieldListInit{field_index(1)};
2984if strcmp(field,'add_field...')
2985    FieldListInit(field_index(1))=[];
2986    SeriesData=get(handles.series,'UserData');
2987    for iview=1:numel(SeriesData.FileInfo)
2988    FileType{iview}=SeriesData.FileInfo{iview}.FileType;
2989    end
2990    % input line for which the field choice is relevant
2991    iview=find(ismember(FileType,{'netcdf','civx','civdata','civdata_compress'})); % all nc files, icluding civ
2992    hget_field=findobj(allchild(0),'name','get_field');
2993    if ~isempty(hget_field)
2994        delete(hget_field)%delete opened versions of get_field
2995    end
2996    Param=read_GUI(handles.series);
2997    InputTable=Param.InputTable(iview,:);
2998    % check the existence of the first file in the series
2999    first_j=[];last_j=[];MinIndex_j=1;MaxIndex_j=1; % default setting for index j
3000    if isfield(Param.IndexRange,'first_j') % if index j is used
3001        first_j=Param.IndexRange.first_j;
3002        last_j=Param.IndexRange.last_j;
3003        MinIndex_j=Param.IndexRange.MinIndex_j(iview);
3004        MaxIndex_j=Param.IndexRange.MaxIndex_j(iview);
3005    end
3006    PairString='';
3007    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString{iview}; end
3008    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
3009    LineIndex=iview(1);
3010    if numel(iview)>1
3011        answer=msgbox_uvmat('INPUT_TXT',['select the line of the input table:' num2str(iview)] ,num2str(iview(1)));
3012        LineIndex=str2num(answer);
3013    end
3014    FirstFileName=fullfile_uvmat(InputTable{LineIndex,1},InputTable{LineIndex,2},InputTable{LineIndex,3},...
3015        InputTable{LineIndex,5},InputTable{LineIndex,4},i1,i2,j1,j2);
3016    if exist(FirstFileName,'file') || ~isempty(regexp(InputTable{LineIndex,1},'^http'))
3017        ParamIn.Title='get_field: pick input variables and coordinates for series processing';
3018        ParamIn.SeriesInput=1;
3019        GetFieldData=get_field(FirstFileName,ParamIn);
3020        FieldList={};
3021        if isfield(GetFieldData,'FieldOption')% if a field has been selected
3022        switch GetFieldData.FieldOption
3023            case 'vectors'
3024                UName=GetFieldData.PanelVectors.vector_x;
3025                VName=GetFieldData.PanelVectors.vector_y;
3026                YName={GetFieldData.Coordinates.Coord_y};
3027                FieldList={['vec(' UName ',' VName ')'];...
3028                    ['norm(' UName ',' VName ')'];...
3029                    UName;VName};
3030                set(handles.VelType,'Visible','off')
3031            case {'scalar'}
3032                FieldList=GetFieldData.PanelScalar.scalar;
3033                YName={GetFieldData.Coordinates.Coord_y};
3034                if ischar(FieldList)
3035                    FieldList={FieldList};
3036                end
3037                set(handles.VelType,'Visible','off')
3038            case 'civdata...'
3039                FieldList=[set_field_list('U','V') ;{'C'}];
3040                set(handles.FieldName,'Value',1) % set menu to 'velocity
3041                XName='X';
3042                YName='y';
3043                set(handles.VelType,'Visible','on')
3044        end
3045        set(handles.FieldName,'Value',1)
3046        set(handles.FieldName,'String',[FieldListInit; FieldList; {'add_field...'}]);
3047        if ~strcmp(GetFieldData.FieldOption,'civdata...')
3048           if ~isempty(regexp(FieldList{1},'^vec', 'once'))
3049                set(handles.FieldName,'Value',1)
3050           else
3051                set(handles.FieldName,'Value',1:numel(FieldList))%select all input fields by default
3052           end
3053            XName=GetFieldData.Coordinates.Coord_x;
3054            YName=GetFieldData.Coordinates.Coord_y;
3055            TimeNameStr=GetFieldData.Time.SwitchVarIndexTime;
3056            % get the time info
3057            TimeTable=get(handles.TimeTable,'Data');
3058            switch TimeNameStr
3059                case 'file index'
3060                    TimeName='';
3061                case 'attribute'
3062                    TimeName=['att:' GetFieldData.Time.TimeName];
3063                    % update the time table
3064                    TimeTable{LineIndex,2}=get_time(Param.IndexRange.MinIndex_i(LineIndex),MinIndex_j,PairString,InputTable,SeriesData.FileInfo{LineIndex},GetFieldData.Time.TimeName);  % Min time
3065                    TimeTable{LineIndex,3}=get_time(Param.IndexRange.first_i,first_j,PairString,InputTable,SeriesData.FileInfo{LineIndex},GetFieldData.Time.TimeName);  % first time
3066                    TimeTable{LineIndex,4}=get_time(Param.IndexRange.last_i,last_j,PairString,InputTable,SeriesData.FileInfo{LineIndex},GetFieldData.Time.TimeName);  % last time
3067                    TimeTable{LineIndex,5}=get_time(Param.IndexRange.MaxIndex_i(LineIndex),MaxIndex_j,PairString,InputTable,SeriesData.FileInfo{LineIndex},GetFieldData.Time.TimeName);  % Max time
3068                case 'variable'
3069                    TimeName=['var:' GetFieldData.Time.TimeName];
3070                   % set(handles.TimeName,'String',['var:' GetFieldData.Time.TimeName])
3071%                     set(handles.NomType,'String','*')
3072%                     set(handles.RootFile,'String',[get(handles.RootFile,'String') get(handles.FileIndex,'String')])% A VERIFIER !!!!!!
3073%                     set(handles.FileIndex,'String','')
3074                    ParamIn.TimeVarName=GetFieldData.Time.TimeName;
3075                case 'matrix_index'
3076                    TimeName=['dim:' GetFieldData.Time.TimeName];
3077                    set(handles.NomType,'String','*')
3078                    set(handles.RootFile,'String',[get(handles.RootFile,'String') get(handles.FileIndex,'String')])
3079                    set(handles.FileIndex,'String','')
3080                    ParamIn.TimeDimName=GetFieldData.Time.TimeName;
3081            end
3082            TimeTable{LineIndex,1}=TimeName;
3083            set(handles.TimeTable,'Data',TimeTable);
3084        end
3085        set(handles.Coord_x,'String',XName)
3086        set(handles.Coord_y,'String',YName)
3087        set(handles.Coord_x,'Visible','on')
3088        set(handles.Coord_y,'Visible','on')
3089        end
3090    else
3091        msgbox_uvmat('ERROR',[FirstFileName ' does not exist'])
3092    end
3093end
3094
3095
3096function [TimeValue,DtValue]=get_time(ref_i,ref_j,PairString,InputTable,FileInfo,TimeName,DtName)
3097[i1,i2,j1,j2] = get_file_index(ref_i,ref_j,PairString);
3098FileName=fullfile_uvmat(InputTable{1},InputTable{2},InputTable{3},InputTable{5},InputTable{4},i1,i2,j1,j2);
3099%Data=nc2struct(FileName,[]);
3100TimeValue=[];
3101DtValue=[];
3102switch FileInfo.FileType
3103    case 'civdata'
3104    Data=nc2struct(FileName,[]);
3105    if ismember(TimeName,{'civ1','filter1'})
3106        if isfield(Data,'Civ1_Time')
3107        TimeValue=Data.Civ1_Time;
3108        end
3109        if isfield(Data,'Civ1_Dt')
3110        DtValue=Data.Civ1_Dt;
3111        end
3112    else
3113        if isfield(Data,'Civ2_Time')
3114        TimeValue=Data.Civ2_Time;
3115        end
3116        if isfield(Data,'Civ2_Dt')
3117        DtValue=Data.Civ2_Dt;
3118        end
3119    end
3120    case 'pivdata_fluidimage'
3121      TimeValue=ref_i;%default
3122      DtValue=1;%default
3123    case 'netcdf'
3124        Data=nc2struct(FileName,[]);
3125    if ~isempty(TimeName)&& isfield(Data,TimeName)
3126        TimeValue=Data.(TimeName);
3127    end
3128    if exist('DtName','var') && isfield(Data,DtName)
3129        DtValue=Data.(DtName);
3130    end
3131end
3132
3133%------------------------------------------------------------------------
3134% --- Executes on selection change in FieldName_1.
3135function FieldName_1_Callback(hObject, eventdata, handles)
3136%------------------------------------------------------------------------
3137field_str=get(handles.FieldName_1,'String');
3138field_index=get(handles.FieldName_1,'Value');
3139field=field_str{field_index(1)};
3140if strcmp(field,'add_field...')
3141    %iview=find(ismember(SeriesData.FileType,{'netcdf','civx','civdata'})); % all nc files, icluding civ
3142    hget_field=findobj(allchild(0),'name','get_field');
3143    if ~isempty(hget_field)
3144        delete(hget_field)%delete opened versions of get_field
3145    end
3146    Param=read_GUI(handles.series);
3147    %InputTable=Param.InputTable(2,:);
3148    % check the existence of the first file in the series
3149    first_j=[];
3150    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
3151    if isfield(Param.IndexRange,'last_j'); last_j=Param.IndexRange.last_j; end
3152    PairString='';
3153    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
3154    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
3155    FirstFileName=fullfile_uvmat(Param.InputTable{2,1},Param.InputTable{2,2},Param.InputTable{2,3},...
3156        Param.InputTable{2,5},Param.InputTable{2,4},i1,i2,j1,j2);
3157    if exist(FirstFileName,'file')
3158        ParamIn.SeriesInput=1;
3159        GetFieldData=get_field(FirstFileName,ParamIn);
3160        FieldList={};
3161        switch GetFieldData.FieldOption
3162            case 'vectors'
3163                UName=GetFieldData.PanelVectors.vector_x;
3164                VName=GetFieldData.PanelVectors.vector_y;
3165                FieldList={['vec(' UName ',' VName ')'];...
3166                    ['norm(' UName ',' VName ')'];...
3167                    UName;VName};
3168            case {'scalar','pick variables'}
3169                FieldList=GetFieldData.PanelScalar.scalar;
3170                if ischar(FieldList)
3171                    FieldList={FieldList};
3172                end
3173            case '1D plot'
3174
3175            case 'civdata...'
3176                FieldList=set_field_list('U','V','C');
3177                set(handles.FieldName,'Value',2) % set menu to 'velocity
3178        end
3179        set(handles.FieldName_1,'Value',1)
3180        set(handles.FieldName_1,'String',[FieldList; {'add_field...'}]);
3181    end
3182end
3183
3184
3185%%%%%%%%%%%%%
3186function [ind_remove]=find_pairs(dirpair,ind_i,last_i)
3187indsel=ind_i;
3188indiff=diff(ind_i); % test index increment to detect multiplets (several pairs with the same index ind_i) and holes in the series
3189indiff=[1 indiff last_i-ind_i(end)+1]; % for testing gaps with the imposed bounds
3190if ~isempty(indiff)
3191    indiff2=diff(indiff);
3192    indiffp=[indiff2 1];
3193    indiffm=[1 indiff2];
3194    ind_multi_m=find((indiff==0)&(indiffm<0))-1; % indices of first members of multiplets
3195    ind_multi_p=find((indiff==0)&(indiffp>0)); % indices of last members of multiplets
3196    %for each multiplet, select the most recent file
3197    ind_remove=[];
3198    for i=1:length(ind_multi_m)
3199        ind_pairs=ind_multi_m(i):ind_multi_p(i);
3200        for imulti=1:length(ind_pairs)
3201            datepair(imulti)=datenum(dirpair(ind_pairs(imulti)).date); % dates of creation
3202        end
3203        [~,indsort2]=sort(datepair); % sort the multiplet by creation date
3204        ind_s=indsort2(1:end-1); %
3205        ind_remove=[ind_remove ind_pairs(ind_s)]; % remove these indices, leave the last one
3206    end
3207end
3208
3209%------------------------------------------------------------------------
3210% --- determine the list of index pairstring of processing file
3211function [num_i1,num_i2,num_j1,num_j2,num_i_out,num_j_out]=find_file_indices(num_i,num_j,ind_shift,NomType,mode)
3212%------------------------------------------------------------------------
3213num_i1=num_i; % set of first image numbers by default
3214num_i2=num_i;
3215num_j1=num_j;
3216num_j2=num_j;
3217num_i_out=num_i;
3218num_j_out=num_j;
3219% if isequal (NomType,'_1-2_1') || isequal (NomType,'_1-2')
3220if isequal(mode,'series(Di)')
3221    num_i1_line=num_i+ind_shift(3); % set of first image numbers
3222    num_i2_line=num_i+ind_shift(4);
3223    % adjust the first and last field number
3224        indsel=find(num_i1_line >= 1);
3225    num_i_out=num_i(indsel);
3226    num_i1_line=num_i1_line(indsel);
3227    num_i2_line=num_i2_line(indsel);
3228    num_j1=meshgrid(num_j,ones(size(num_i1_line)));
3229    num_j2=meshgrid(num_j,ones(size(num_i1_line)));
3230    [~,num_i1]=meshgrid(num_j,num_i1_line);
3231    [~,num_i2]=meshgrid(num_j,num_i2_line);
3232elseif isequal (mode,'series(Dj)')||isequal (mode,'bursts')
3233    if isequal(mode,'bursts') %case of bursts (png_old or png_2D)
3234        num_j1=ind_shift(1)*ones(size(num_i));
3235        num_j2=ind_shift(2)*ones(size(num_i));
3236    else
3237        num_j1_col=num_j+ind_shift(1); % set of first image numbers
3238        num_j2_col=num_j+ind_shift(2);
3239        % adjust the first field number
3240        indsel=find((num_j1_col >= 1));
3241        num_j_out=num_j(indsel);
3242        num_j1_col=num_j1_col(indsel);
3243        num_j2_col=num_j2_col(indsel);
3244        [num_i1,num_j1]=meshgrid(num_i,num_j1_col);
3245        [num_i2,num_j2]=meshgrid(num_i,num_j2_col);
3246    end
3247end
3248
3249%------------------------------------------------------------------------
3250% --- Executes on button press in CheckObject.
3251function CheckObject_Callback(hObject, eventdata, handles)
3252%------------------------------------------------------------------------
3253hset_object=findobj(allchild(0),'tag','set_object'); % find the set_object interface handle
3254if get(handles.CheckObject,'Value')
3255    SeriesData=get(handles.series,'UserData');
3256    if isfield(SeriesData,'ProjObject') && ~isempty(SeriesData.ProjObject)% a projection object is already loaded in the GUI series
3257        set(handles.ViewObject,'Value',1)
3258        ViewObject_Callback(hObject, eventdata, handles)
3259    else
3260        if ishandle(hset_object)% a projection object is already displayed in a GUI set_object
3261            uistack(hset_object,'top')% show the GUI set_object if opened
3262        else
3263            %get the object file
3264            InputTable=get(handles.InputTable,'Data');
3265            defaultname=InputTable{1,1};
3266            if isempty(defaultname)
3267                defaultname={''};
3268            end
3269            fileinput=uigetfile_uvmat('pick a xml object file (or use uvmat to create it)',defaultname,'.xml');
3270            if isempty(fileinput)% exit if no object file is selected
3271                set(handles.CheckObject,'Value',0)
3272                return
3273            end
3274            %read the file
3275            data=xml2struct(fileinput);
3276            if ~isfield(data,'Type')
3277                msgbox_uvmat('ERROR',[fileinput ' is not an object xml file'])
3278                set(handles.CheckObject,'Value',0)
3279                return
3280            end
3281            if ~isfield(data,'ProjMode')
3282                data.ProjMode='none';
3283            end
3284            hset_object=set_object(data); % call the set_object interface
3285            set(hset_object,'Name','set_object_series')% name to distinguish from set_object used with uvmat
3286        end
3287        ProjObject=read_GUI(hset_object);
3288        set(handles.ProjObjectName,'String',ProjObject.Name); % display the object name
3289        SeriesData=get(handles.series,'UserData');
3290        SeriesData.ProjObject=ProjObject;
3291        set(handles.series,'UserData',SeriesData);
3292    end
3293    set(handles.EditObject,'Visible','on');
3294    set(handles.DeleteObject,'Visible','on');
3295    set(handles.ViewObject,'Visible','on');
3296    set(handles.ProjObjectName,'Visible','on');
3297else
3298    set(handles.EditObject,'Visible','off');
3299    set(handles.DeleteObject,'Visible','off');
3300    set(handles.ViewObject,'Visible','off');
3301    if ~ishandle(hset_object)
3302        set(handles.ViewObject,'Value',0);
3303    end
3304    set(handles.ProjObjectName,'Visible','off');
3305end
3306
3307%------------------------------------------------------------------------
3308% --- Executes on button press in ViewObject.
3309%------------------------------------------------------------------------
3310function ViewObject_Callback(hObject, eventdata, handles)
3311
3312UserData=get(handles.series,'UserData');
3313hset_object=findobj(allchild(0),'Tag','set_object');
3314if ~isempty(hset_object)
3315    delete(hset_object)% refresh set_object if already opened
3316end
3317hset_object=set_object(UserData.ProjObject);
3318set(hset_object,'Name','view_object_series')
3319
3320
3321%------------------------------------------------------------------------
3322% --- Executes on button press in EditObject.
3323function EditObject_Callback(hObject, eventdata, handles)
3324%------------------------------------------------------------------------
3325if get(handles.EditObject,'Value')
3326    set(handles.ViewObject,'Value',0)
3327    UserData=get(handles.series,'UserData');
3328    if isfield(UserData,'ProjObject')
3329    hset_object=set_object(UserData.ProjObject);
3330    set(hset_object,'Name','edit_object_series')
3331    set(get(hset_object,'Children'),'Enable','on')
3332    else
3333        msgbox_uvmat('ERROR','no projection object available');
3334    end
3335else
3336    hset_object=findobj(allchild(0),'Tag','set_object');
3337    if ~isempty(hset_object)
3338        set(get(hset_object,'Children'),'Enable','off')
3339    end
3340end
3341
3342%------------------------------------------------------------------------
3343% --- Executes on button press in DeleteObject.
3344function DeleteObject_Callback(hObject, eventdata, handles)
3345%------------------------------------------------------------------------
3346SeriesData=get(handles.series,'UserData');
3347SeriesData.ProjObject=[];
3348set(handles.series,'UserData',SeriesData)
3349set(handles.ProjObjectName,'String','')
3350set(handles.ProjObjectName,'Visible','off')
3351set(handles.CheckObject,'Value',0)
3352set(handles.ViewObject,'Visible','off')
3353set(handles.EditObject,'Visible','off')
3354hset_object=findobj(allchild(0),'name','set_object_series');
3355if ~isempty(hset_object)
3356    delete(hset_object)
3357end
3358set(handles.DeleteObject,'Visible','off')
3359
3360%------------------------------------------------------------------------
3361% --- Executed when CheckMask is activated
3362%------------------------------------------------------------------------
3363function CheckMask_Callback(hObject, eventdata, handles)
3364% SeriesData=get(handles.series,'UserData');
3365
3366if get(handles.CheckMask,'Value')
3367   
3368    set(handles.DeleteMask,'Visible','on')
3369    Param=read_GUI_series(handles); % displayed parameters
3370    NbView=size(Param.InputTable,1);
3371    MaskTable=cell(NbView,2);
3372   
3373    %RootPath=Param.InputTable{1,1};
3374    first_j=[];% note that the function will propose to cover the whole range of indices
3375    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
3376   %last_j=[];
3377    if isfield(Param.IndexRange,'last_j'); last_j=Param.IndexRange.last_j; end
3378    PairString='';
3379    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
3380    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
3381    %checkmask=zeros(NbView,1);
3382    for iview=1:NbView
3383        checkmask=false;
3384        FirstFileName=fullfile_uvmat(Param.InputTable{iview,1},Param.InputTable{iview,2},Param.InputTable{iview,3},...
3385            Param.InputTable{iview,5},Param.InputTable{iview,4},i1,i2,j1,j2);
3386       
3387        [FileInfo,VideoObject]=get_file_info(FirstFileName);
3388       
3389       
3390       %  Data=nc2struct(FirstFileName);
3391        if isfield(FileInfo,'MaskFile') && isfield(FileInfo,'MaskExt')
3392           if  isfield(FileInfo,'MaskNbSlice')&& exist([FileInfo.MaskFile '_1' FileInfo.MaskExt],'file')
3393            MaskTable{iview,1}=[FileInfo.MaskFile '_1' FileInfo.MaskExt];
3394            MaskTable{iview,2}=num2str(FileInfo.MaskNbSlice);
3395            checkmask=true;
3396           elseif exist([FileInfo.MaskFile FileInfo.MaskExt],'file')
3397                 MaskTable{iview,1}=[FileInfo.MaskFile FileInfo.MaskExt];
3398                 MaskTable{iview,2}='';
3399                  checkmask=true;
3400            end
3401        end
3402        if ~checkmask
3403            MaskTable{iview,1}=uigetfile_uvmat('select a mask file:',Param.InputTable{iview,1},'image');
3404        end
3405    end
3406    for iview=1:NbView
3407        [Path,Name]=fileparts(MaskTable{iview,1});
3408        Name=regexprep(Name,'_\d+','');
3409        maskfiles=dir(fullfile(Path,[Name '_*.png']));%look for mask files       
3410        if ~isempty(maskfiles)
3411            for ilist=1:numel(maskfiles)
3412                r=regexp(maskfiles(ilist).name,'_(?<num1>\d+)','names');%look for burst pairs
3413                index(ilist)=str2double(r.num1);
3414            end
3415            MaskTable{iview,2}=max(index);
3416        end
3417    end
3418    set(handles.MaskTable,'Data',MaskTable)
3419end
3420
3421%       
3422% if ~isempty(NewMask)
3423%     if isempty(MaskList)
3424%         MaskList={NewMask};
3425%     else
3426%     MaskList={MaskList;NewMask};
3427%     end
3428%     set(handles.Mask,'String',MaskList)
3429% end
3430% end
3431% %     MaskTable=cell(nbview,1); % default
3432% %     ListMask=cell(nbview,1); % default
3433% %     MaskData=get(handles.MaskTable,'Data');
3434% %     MaskData(size(MaskData,1):nbview,1)=cell(size(MaskData,1):nbview,1); % complement if undefined lines
3435%     for iview=1:nbview
3436%         ListMask{iview,1}=num2str(iview);
3437%         RootPath=InputTable{iview,1};
3438%         if ~isempty(RootPath)
3439%             if isempty(MaskData{iview})
3440%                 SubDir=InputTable{iview,2};
3441%                 MaskPath=fullfile(RootPath,[regexprep(SubDir,'\..*','') '.mask']); % take the root part of SubDir, before the first dot '.'
3442%                 if exist(MaskPath,'dir')
3443%                     ListStruct=dir(MaskPath); % look for a mask file
3444%                     ListCells=struct2cell(ListStruct); % transform dir struct to a cell arrray
3445%                     check_dir=cell2mat(ListCells(4,:)); % =1 for directories, =0 for files
3446%                     ListFiles=ListCells(1,:); % list of file and dri names
3447%                     ListFiles=ListFiles(~check_dir); % list of file names (excluding dir)
3448%                     mdetect=0;
3449%                     if ~isempty(ListFiles)
3450%                         for ifile=1:numel(ListFiles)
3451%                             [tild,tild,MaskFile{ifile},i1_series,i2_series,j1_series,j2_series,MaskNomType,MaskFileType]=find_file_series(MaskPath,ListFiles{ifile},0);
3452%                             if strcmp(MaskFileType,'image') && isempty(i2_series) && isempty(j2_series)
3453%                                 mdetect=1;
3454%                                 MaskName=ListFiles{ifile};
3455%                             end
3456%                             if ~strcmp(MaskFile{ifile},MaskFile{1})
3457%                                 mdetect=0; % cancel detection test in case of multiple masks, use the brower for selection
3458%                                 break
3459%                             end
3460%                         end
3461%                     end
3462%                     if mdetect==1
3463%                         MaskName=fullfile(MaskPath,'mask_1.png');
3464%                     else
3465%                         MaskName=uigetfile_uvmat('select a mask file:',MaskPath,'image');
3466%                     end
3467%                 else
3468%                     MaskName=uigetfile_uvmat('select a mask file:',RootPath,'image');
3469%                 end
3470%                 MaskTable{iview,1}=MaskName ;
3471%                 ListMask{iview,1}=num2str(iview);
3472%             end
3473%         end
3474%     end
3475%     set(handles.MaskTable,'Data',MaskTable)
3476%     set(handles.MaskTable,'Visible','on')
3477%     set(handles.MaskBrowse,'Visible','on')
3478%     set(handles.ListMask,'Visible','on')
3479%     set(handles.ListMask,'String',ListMask)
3480%     set(handles.ListMask,'Value',1)
3481
3482
3483
3484%------------------------------------------------------------------------
3485% --- Executes when selected cell(s) is changed in MaskTable.
3486%------------------------------------------------------------------------
3487function MaskTable_CellSelectionCallback(hObject, eventdata, handles)
3488
3489if numel(eventdata.Indices)>=1
3490set(handles.ListMask,'Value',eventdata.Indices(1))
3491end
3492
3493%-------------------------------------------------------------------
3494function MenuHelp_Callback(hObject, eventdata, handles)
3495%-------------------------------------------------------------------
3496
3497
3498% path_to_uvmat=which ('uvmat'); % check the path of uvmat
3499% pathelp=fileparts(path_to_uvmat);
3500% helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
3501% if isempty(dir(helpfile)), msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
3502% else
3503%     addpath (fullfile(pathelp,'uvmat_doc'))
3504%     web([helpfile '#series'])
3505% end
3506
3507%-------------------------------------------------------------------
3508% --- Executes on selection change in TransformName.
3509function TransformName_Callback(hObject, eventdata, handles)
3510%----------------------------------------------------------------------
3511TransformList=get(handles.TransformName,'String');
3512TransformIndex=get(handles.TransformName,'Value');
3513TransformName=TransformList{TransformIndex};
3514TransformPathList=get(handles.TransformName,'UserData');
3515nb_builtin_transform=4;
3516
3517%% browse transform functions with the input menu option more...
3518if isequal(TransformName,'more...')% browse transform functions
3519    FileName=uigetfile_uvmat('Pick a transform function',get(handles.TransformPath,'String'),'.m');
3520    if isempty(FileName)
3521        return     %browser closed without choice
3522    end
3523    [TransformPath,TransformName,TransformExt]=fileparts(FileName); % removes extension .m
3524    if ~strcmp(TransformExt,'.m')
3525        msgbox_uvmat('ERROR','a Matlab function .m must be introduced');
3526        return
3527    end
3528     % insert the choice in the menu
3529    TransformIndex=find(strcmp(TransformName,TransformList),1); % look for the selected function in the menu Action
3530    if isempty(TransformIndex)%the input string does not exist in the menu
3531        TransformIndex= length(TransformList);
3532        TransformList=[TransformList(1:end-1);{TransformName};TransformList(end)]; % the selected function is appended in the menu, before the last item 'more...'
3533        set(handles.TransformName,'String',TransformList)
3534        TransformPathList=[TransformPathList;{TransformPath}];
3535    else% the input function already exist, we update its path (possibly new)
3536        TransformPathList{TransformIndex}=TransformPath; %
3537        set(handles.TransformName,'Value',TransformIndex)
3538    end
3539   % save the new menu in the personal file 'uvmat_perso.mat'
3540   dir_perso=prefdir; % personal Matalb directory
3541   profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
3542   if exist(profil_perso,'file')
3543       for ilist=nb_builtin_transform+1:numel(TransformPathList)
3544           TransformListUser{ilist-nb_builtin_transform}=TransformList{ilist};
3545           TransformPathListUser{ilist-nb_builtin_transform}=TransformPathList{ilist};
3546       end
3547       TransformPathListUser=TransformPathListUser';
3548       TransformListUser=TransformListUser';
3549       save (profil_perso,'TransformPathListUser','TransformListUser','-append'); % store the root name for future opening of uvmat
3550   end
3551end
3552
3553%% display the current function path
3554set(handles.TransformPath,'String',TransformPathList{TransformIndex}); % show the path to the senlected function
3555set(handles.TransformName,'UserData',TransformPathList);
3556
3557%% create the function handle of the selected fct
3558if ~isempty(TransformName)
3559    if ~exist(TransformPathList{TransformIndex},'dir')
3560        msgbox_uvmat('ERROR',['The prescribed transform function path ' TransformPathList{TransformIndex} ' does not exist']);
3561        return
3562    end
3563    current_dir=pwd; % current working dir
3564    cd(TransformPathList{TransformIndex})
3565    transform_handle=str2func(TransformName);
3566    cd(current_dir)
3567    Field.Action.RUN=0;% indicate that the transform fct is called only to get input param
3568    SeriesData=get(handles.series,'UserData');
3569    ParamIn=[];
3570    if isfield(SeriesData,'TransformInput')
3571        ParamIn.TransformInput=SeriesData.TransformInput;
3572    end
3573    DataOut=feval(transform_handle,Field,ParamIn);% execute the transform fct to get its input parameters
3574    if isfield(DataOut,'TransformInput')%  used to add transform parameters at selection of the transform fct
3575        SeriesData.TransformInput=DataOut.TransformInput;
3576        set(handles.series,'UserData',SeriesData)
3577    end
3578end
3579
3580%------------------------------------------------------------------------
3581% --- fct activated by the upper bar menu ExportConfig
3582%------------------------------------------------------------------------
3583function MenuDisplayConfig_Callback(hObject, eventdata, handles)
3584
3585global Param
3586Param=read_GUI_series(handles);
3587evalin('base','global Param')%make CurData global in the workspace
3588display('current series config :')
3589evalin('base','Param') %display CurData in the workspace
3590commandwindow; % brings the Matlab command window to the front
3591
3592%------------------------------------------------------------------------
3593% --- fct activated by the upper bar menu InportConfig: import
3594%     menu settings from an xml file (stored in /0_XML for each run)
3595%------------------------------------------------------------------------
3596function MenuImportConfig_Callback(hObject, eventdata, handles)
3597
3598%% use a browser to choose the xml file containing the processing config
3599InputTable=get(handles.InputTable,'Data');
3600oldfile=InputTable{1,1}; % current path in InputTable
3601if isempty(oldfile)
3602    % use a file name stored in prefdir
3603    dir_perso=prefdir;
3604    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
3605    if exist(profil_perso,'file')
3606        h=load (profil_perso);
3607        if isfield(h,'RootPath') && ischar(h.RootPath)
3608            oldfile=h.RootPath;
3609        end
3610    end
3611end
3612filexml=uigetfile_uvmat('pick a xml parameter file',oldfile,'.xml'); % get the xml file containing processing parameters
3613if isempty(filexml), return, end % quit function if an xml file has not been opened
3614
3615%% fill the GUI series with the content of the xml file
3616[Param,RootTag,errormsg]=xml2struct(filexml); % read the input xml file as a Matlab structure
3617if ~isempty(errormsg)
3618    msgbox_uvmat('ERROR',errormsg);
3619    return
3620end
3621% ask to stop current Action if button RUN is in action (another process is already running)
3622if isequal(get(handles.RUN,'Value'),1)
3623    answer= msgbox_uvmat('INPUT_Y-N','stop current Action process?');
3624    if strcmp(answer,'Yes')
3625        STOP_Callback(hObject, eventdata, handles)
3626    else
3627        return
3628    end
3629end
3630Param.Action.RUN=0; % desactivate the input RUN=1
3631
3632fill_GUI(Param,handles.series)% fill the elements of the GUI series with the input parameters
3633SeriesData=get(handles.series,'UserData');
3634if isfield(Param,'InputFields')
3635    ListField=Param.InputFields.FieldName;
3636    if ischar(ListField),ListField={ListField}; end
3637    set(handles.FieldName,'String',[ListField;{'add_field...'}])
3638     set(handles.FieldName,'Value',1:numel(ListField))
3639     set(handles.FieldName,'Visible','on')
3640end
3641if isfield(Param,'ActionInput')%  introduce  parameters specific to an Action fct, for instance PIV parameters
3642%     set(handles.ActionInput,'Visible','on')
3643%     set(handles.ActionInput,'Value',0)
3644    Param.ActionInput.ConfigSource=filexml; % record the source of config for future info
3645    SeriesData.ActionInput=Param.ActionInput;
3646end
3647if isfield(Param,'TransformInput')%  introduce  parameters specific to a transform fct
3648    SeriesData.TransformInput=Param.TransformInput;
3649end
3650if isfield(Param,'ProjObject') %introduce projection object if relevant
3651    SeriesData.ProjObject=Param.ProjObject;
3652end
3653set(handles.series,'UserData',SeriesData)
3654if isfield(Param,'CheckObject') && isequal(Param.CheckObject,1)
3655    set(handles.ProjObjectName,'String',Param.ProjObject.Name)
3656    set(handles.ViewObject,'Visible','on')
3657    set(handles.EditObject,'Visible','on')
3658    set(handles.DeleteObject,'Visible','on')
3659else
3660    set(handles.ProjObjectName,'String','')
3661    set(handles.ProjObjectName,'Visible','off')
3662    set(handles.ViewObject,'Visible','off')
3663    set(handles.EditObject,'Visible','off')
3664    set(handles.DeleteObject,'Visible','off')
3665end
3666set(handles.REFRESH,'BackgroundColor',[1 0 1]); % paint REFRESH button in magenta to indicate that it should be activated
3667
3668
3669%------------------------------------------------------------------------
3670% --- Executes when the GUI series is resized.
3671%------------------------------------------------------------------------
3672function series_ResizeFcn(hObject, eventdata, handles)
3673
3674%% input table
3675set(handles.InputTable,'Unit','pixel')
3676Pos=get(handles.InputTable,'Position');
3677set(handles.InputTable,'Unit','normalized')
3678ColumnWidth=round([0.5 0.14 0.14 0.14 0.08]*(Pos(3)-52));
3679ColumnWidth=num2cell(ColumnWidth);
3680set(handles.InputTable,'ColumnWidth',ColumnWidth)
3681
3682%% MaskTable
3683set(handles.MaskTable,'Unit','pixel')
3684Pos=get(handles.MaskTable,'Position');
3685set(handles.MaskTable,'Unit','normalized')
3686ColumnWidth=round([0.9 0.1]*(Pos(3)-52));
3687ColumnWidth=num2cell(ColumnWidth);
3688set(handles.MaskTable,'ColumnWidth',ColumnWidth)
3689
3690%% MinIndex_j and MaxIndex_i
3691unit=get(handles.MinIndex_i,'Unit');
3692set(handles.MinIndex_i,'Unit','pixel')
3693Pos=get(handles.MinIndex_i,'Position');
3694set(handles.MinIndex_i,'Unit',unit)
3695set(handles.MinIndex_i,'ColumnWidth',{Pos(3)-18})
3696set(handles.MaxIndex_i,'ColumnWidth',{Pos(3)-18})
3697set(handles.MinIndex_j,'ColumnWidth',{Pos(3)-18})
3698set(handles.MaxIndex_j,'ColumnWidth',{Pos(3)-18})
3699
3700%% TimeTable
3701set(handles.TimeTable,'Unit','pixel')
3702Pos=get(handles.TimeTable,'Position');
3703set(handles.TimeTable,'Unit','normalized')
3704% ColumnWidth=get(handles.TimeTable,'ColumnWidth');
3705ColumnWidth=num2cell(floor([0.2 0.2 0.2 0.2 0.2]*(Pos(3)-20)));
3706set(handles.TimeTable,'ColumnWidth',ColumnWidth)
3707
3708
3709%% PairString
3710set(handles.PairString,'Unit','pixel')
3711Pos=get(handles.PairString,'Position');
3712set(handles.PairString,'Unit','normalized')
3713set(handles.PairString,'ColumnWidth',{Pos(3)-5})
3714
3715%% MaskTable
3716% % set(handles.MaskTable,'Unit','pixel')
3717% % Pos=get(handles.MaskTable,'Position');
3718% % set(handles.MaskTable,'Unit','normalized')
3719% % set(handles.MaskTable,'ColumnWidth',{Pos(3)-5})
3720
3721%------------------------------------------------------------------------
3722% --- Executes on button press in status.
3723%------------------------------------------------------------------------
3724function status_Callback(hObject, eventdata, handles)
3725
3726if get(handles.status,'Value')
3727    set(handles.status,'BackgroundColor',[1 1 0])
3728    drawnow
3729    Param=read_GUI(handles.series);
3730    RootPath=fullfile(Param.OutputPath,Param.Experiment,Param.Device);
3731    if ~isfield(Param,'OutputSubDir')
3732        msgbox_uvmat('ERROR','no standard sub-directory definition for output files, use a browser to check the output')
3733        set(handles.status,'BackgroundColor',[0 1 0])
3734        return
3735    end
3736    OutputSubDir=[Param.OutputSubDir Param.OutputDirExt]; % subdirectory for output files
3737    OutputDir=fullfile(RootPath,OutputSubDir);
3738    if exist(OutputDir,'dir')
3739        uigetfile_uvmat('status_display',OutputDir)
3740    else
3741        msgbox_uvmat('ERROR','output folder not created yet: calculation did not start')
3742        set(handles.status,'BackgroundColor',[0 1 0])
3743    end
3744else
3745    %% delete current display fig if selection is off
3746    set(handles.status,'BackgroundColor',[0 1 0])
3747    hfig=findobj(allchild(0),'name','status_display');
3748    if ~isempty(hfig)
3749        delete(hfig)
3750    end
3751    return
3752end
3753
3754
3755%------------------------------------------------------------------------
3756% launched by selecting a file on the list
3757%------------------------------------------------------------------------
3758function view_file(hObject, eventdata)
3759
3760list=get(hObject,'String');
3761index=get(hObject,'Value');
3762rootroot=get(hObject,'UserData');
3763selectname=list{index};
3764ind_dot=regexp(selectname,'\.\.\.');
3765if ~isempty(ind_dot)
3766    selectname=selectname(1:ind_dot-1);
3767end
3768FullSelectName=fullfile(rootroot,selectname);
3769if exist(FullSelectName,'dir')% a directory has been selected
3770    ListFiles=dir(FullSelectName);
3771    ListDisplay=cell(numel(ListFiles),1);
3772    for ilist=2:numel(ListDisplay)% suppress the first line '.'
3773        ListDisplay{ilist-1}=ListFiles(ilist).name;
3774    end
3775    set(hObject,'Value',1)
3776    set(hObject,'String',ListDisplay)
3777    if strcmp(selectname,'..')
3778        FullSelectName=fileparts(fileparts(FullSelectName));
3779    end
3780    set(hObject,'UserData',FullSelectName)
3781    hfig=get(hObject,'parent');
3782    htitlebox=findobj(hfig,'tag','titlebox');
3783    set(htitlebox,'String',FullSelectName)
3784elseif exist(FullSelectName,'file')%visualise the vel field if it exists
3785    FileInfo=get_file_info(FullSelectName);
3786    if strcmp(FileInfo.FileType,'txt')
3787        edit(FullSelectName)
3788    elseif strcmp(FileInfo.FileType,'xml')
3789        editxml(FullSelectName)
3790    else
3791        uvmat(FullSelectName)
3792    end
3793    set(gcbo,'Value',1)
3794end
3795
3796
3797%------------------------------------------------------------------------
3798% launched by refreshing the status figure
3799%------------------------------------------------------------------------
3800function refresh_GUI(hfig)
3801
3802htitlebox=findobj(hfig,'tag','titlebox');
3803hlist=findobj(hfig,'tag','list');
3804hseries=findobj(allchild(0),'tag','series');
3805hstatus=findobj(hseries,'tag','status');
3806StatusData=get(hstatus,'UserData');
3807OutputDir=get(htitlebox,'String');
3808if ischar(OutputDir),OutputDir={OutputDir};end
3809ListFiles=dir(OutputDir{1});
3810if numel(ListFiles)<1
3811    return
3812end
3813ListFiles(1)=[]; % removes the first line ='.'
3814ListDisplay=cell(numel(ListFiles),1);
3815testrecent=0;
3816datnum=zeros(numel(ListDisplay),1);
3817for ilist=1:numel(ListDisplay)
3818    ListDisplay{ilist}=ListFiles(ilist).name;
3819      if ~ListFiles(ilist).isdir && isfield(ListFiles(ilist),'datenum')
3820            datnum(ilist)=ListFiles(ilist).datenum; % only available in recent matlab versions
3821            testrecent=1;
3822       end
3823end
3824set(hlist,'String',ListDisplay)
3825
3826%% Look at date of creation
3827ListDisplay=ListDisplay(datnum~=0);
3828datnum=datnum(datnum~=0); % keep the non zero values corresponding to existing files
3829NbOutputFile=[];
3830if isempty(datnum)
3831    if testrecent
3832        message='no civ result created yet';
3833    else
3834        message='';
3835    end
3836else
3837    [first,indfirst]=min(datnum);
3838    [last,indlast]=max(datnum);
3839    NbOutputFile_str='?';
3840    NbOutputFile=[];
3841    if isfield(StatusData,'NbOutputFile')
3842        NbOutputFile=StatusData.NbOutputFile;
3843        NbOutputFile_str=num2str(NbOutputFile);
3844    end
3845    message={[num2str(numel(datnum)) ' file(s) done over ' NbOutputFile_str] ;['oldest modification:  ' ListDisplay{indfirst} ' : ' datestr(first)];...
3846        ['latest modification:  ' ListDisplay{indlast} ' : ' datestr(last)]};
3847end
3848set(htitlebox,'String', [OutputDir{1};message])
3849
3850%% update the waitbar
3851hwaitbar=findobj(hfig,'tag','waitbar');
3852if ~isempty(NbOutputFile)
3853    BarPosition=get(hwaitbar,'Position');
3854    BarPosition(3)=0.9*numel(datnum)/NbOutputFile;
3855    set(hwaitbar,'Position',BarPosition)
3856end
3857
3858%------------------------------------------------------------------------
3859% --- Executes on selection change in ActionExt.
3860%------------------------------------------------------------------------
3861function ActionExt_Callback(hObject, eventdata, handles)
3862
3863ActionExtList=get(handles.ActionExt,'String');
3864ActionExt=ActionExtList{get(handles.ActionExt,'Value')};
3865if strcmp(ActionExt,'fluidimage')
3866    set(handles.RunMode,'Value',2)
3867end
3868
3869
3870function num_NbSlice_Callback(hObject, eventdata, handles)
3871NbSlice=str2num(get(handles.num_NbSlice,'String'));
3872
3873%------------------------------------------------------------------------
3874% --- set the visibility of relevant velocity type menus:
3875function menu=set_veltype_display(CivStage,FileType)
3876%------------------------------------------------------------------------
3877if ~exist('FileType','var')
3878    FileType='civx';
3879end
3880imin=1;
3881switch FileType
3882    case 'civx'
3883        menu={'civ1';'interp1';'filter1';'civ2';'interp2';'filter2'};
3884        if isequal(CivStage,0)
3885            imax=0;
3886        elseif isequal(CivStage,1) || isequal(CivStage,2)
3887            imax=1;
3888        elseif isequal(CivStage,3)
3889            imax=3;
3890        elseif isequal(CivStage,4) || isequal(CivStage,5)
3891            imax=4;
3892        elseif isequal(CivStage,6) %patch2
3893            imax=6;
3894        end
3895    case {'civdata','civdata_compress'}
3896        menu={'civ1';'filter1';'civ2';'filter2'};
3897        if isequal(CivStage,0)
3898            imax=0;
3899        elseif isequal(CivStage,1) || isequal(CivStage,2)
3900            imax=1;
3901        elseif isequal(CivStage,3)
3902            imax=2;
3903        elseif isequal(CivStage,4) || isequal(CivStage,5)
3904            imax=3;
3905        else%if isequal(CivStage,6) %patch2
3906            imax=4;
3907        end
3908        if strcmp(FileType,'civdata_compress') && CivStage>=4
3909            imin=CivStage-3;
3910        end
3911end
3912menu=menu(imin:imax);
3913
3914
3915% --- Executes on mouse motion over figure - except title and menu.
3916% function series_WindowButtonMotionFcn(hObject, eventdata, handles)
3917% set(hObject,'Pointer','arrow');
3918
3919
3920% --- Executes on button press in SetPairs.
3921function SetPairs_Callback(hObject, eventdata, handles)
3922
3923%% delete previous occurrence of 'set_pairs'
3924hfig=findobj(allchild(0),'Tag','set_pairs');
3925if ~isempty(hfig)
3926delete(hfig)
3927end
3928
3929%% create the GUI set_pairs
3930set(0,'Unit','points')
3931ScreenSize=get(0,'ScreenSize'); % get the size of the screen, to put the fig on the upper right
3932Width=220; % fig width in points (1/72 inch)
3933Height=min(0.8*ScreenSize(4),300);
3934Left=ScreenSize(3)- Width-40; % right edge close to the right, with margin=40
3935Bottom=ScreenSize(4)-Height-40; % put fig at top right
3936hfig=findobj(allchild(0),'Tag','set_slice');
3937if ~isempty(hfig),delete(hfig), end; % delete existing version of the GUI
3938hfig=figure('name','set_pairs','tag','set_pairs','MenuBar','none','NumberTitle','off','Unit','points','Position',[Left,Bottom,Width,Height]);
3939BackgroundColor=get(hfig,'Color');
3940SeriesData=get(handles.series,'UserData');
3941TimeUnit=get(handles.TimeUnit,'String');
3942PairString=get(handles.PairString,'Data');
3943ListViewLines=find(cellfun('isempty',PairString)==0); % find list of non empty pairs
3944ListViewMenu=cell(numel(ListViewLines),1);
3945%iview=get(handles.PairString,'Value');
3946iview=[];
3947for ilist=1:numel(ListViewLines)
3948    ListViewMenu{ilist}=num2str(ListViewLines(ilist));
3949end
3950if isempty(iview)
3951    ListViewValue=numel(ListViewLines); % we work by default on the pair option for the last line which requires pairs
3952    iview=ListViewLines(end);
3953else
3954    ListViewValue=find(ListViewLines==iview);
3955end
3956ref_i=str2num(get(handles.num_first_i,'String'));
3957ref_j=1; % default
3958if strcmp(get(handles.num_first_j,'String'),'Visible')
3959    ref_j=str2num(get(handles.num_first_j,'String'));
3960end
3961[ModeMenu,ModeValue]=update_mode(SeriesData.i1_series{1},SeriesData.i2_series{1},SeriesData.j2_series{1});
3962InputTable=get(handles.InputTable,'Data');
3963displ_pair=update_listpair(SeriesData.i1_series{1},SeriesData.i2_series{1},SeriesData.j1_series{1},SeriesData.j2_series{1},ModeMenu{ModeValue},...
3964                                                 SeriesData.Time{1},TimeUnit,ref_i,ref_j,SeriesData.TimeName,InputTable,SeriesData.FileInfo{1});
3965for iline=1:size(InputTable,1)
3966    viewcell{iline}=num2str(iline);
3967end
3968viewcell=viewcell';
3969ModeMenu={'bursts';'series(Dj)'};
3970ModeValue=1;
3971                   %i1_series,i2_series,j1_series,j2_series,mode,time,TimeUnit,ref_i,ref_j,TimeName,InputTable,FileInfo
3972% first raw of the GUI
3973uicontrol('Style','text','Units','normalized', 'Position', [0.05 0.88 0.5 0.1],'BackgroundColor',BackgroundColor,...
3974    'String','row to edit #','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','right'); % title
3975uicontrol('Style','popupmenu','Units','normalized', 'Position', [0.54 0.8 0.3 0.2],'BackgroundColor',[1 1 1],...
3976    'Callback',@(hObject,eventdata)ListView_Callback(hObject,eventdata),'String',viewcell,'Value',1,'FontUnits','points','FontSize',12,'FontWeight','bold',...
3977    'Tag','ListView','TooltipString','''ListView'':choice of the file series w for pair display');
3978% second raw of the GUI
3979uicontrol('Style','text','Units','normalized', 'Position', [0.05 0.79 0.7 0.1],'BackgroundColor',BackgroundColor,...
3980    'String','mode of index pairing:','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','left'); % title
3981uicontrol('Style','popupmenu','Units','normalized', 'Position', [0.05 0.62 0.9 0.2],'BackgroundColor',[1 1 1],...
3982    'Callback',@(hObject,eventdata)Mode_Callback(hObject,eventdata),'String',ModeMenu,'Value',ModeValue,'FontUnits','points','FontSize',12,'FontWeight','bold',...
3983    'Tag','Mode','TooltipString','''Mode'': choice of the image pair mode');
3984% third raw
3985uicontrol('Style','text','Units','normalized', 'Position', [0.05 0.6 0.7 0.1],'BackgroundColor',BackgroundColor,...
3986    'String','pair choice:','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','left'); % title
3987uicontrol('Style','listbox','Units','normalized', 'Position', [0.05 0.42 0.9 0.2],'BackgroundColor',[1 1 1],...
3988    'Callback',@(hObject,eventdata)ListPair_Callback(hObject,eventdata),'String',displ_pair,'Value',1,'FontUnits','points','FontSize',12,'FontWeight','bold',...
3989    'Tag','ListPair','TooltipString','''ListPair'': menu for selecting the image pair');
3990uicontrol('Style','text','Units','normalized', 'Position', [0.1 0.22 0.8 0.1],'BackgroundColor',BackgroundColor,...
3991    'String','ref_i           ref_j','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','center'); % title
3992uicontrol('Style','edit','Units','normalized', 'Position', [0.15 0.17 0.3 0.08],'BackgroundColor',[1 1 1],...
3993    'Callback',@(hObject,eventdata)num_ref_i_Callback(hObject,eventdata),'String',num2str(ref_i),'FontUnits','points','FontSize',12,'FontWeight','bold',...
3994    'Tag','num_ref_i','TooltipString','''num_ref_i'': reference field index i used to display dt in ''list_pair_civ''');
3995uicontrol('Style','edit','Units','normalized', 'Position', [0.55 0.17 0.3 0.08],'BackgroundColor',[1 1 1],...
3996    'Callback',@(hObject,eventdata)num_ref_j_Callback(hObject,eventdata),'String',num2str(ref_j),'FontUnits','points','FontSize',12,'FontWeight','bold',...
3997    'Tag','num_ref_j','TooltipString','''num_ref_j'': reference field index i used to display dt in ''list_pair_civ''');
3998uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.01 0.01 0.3 0.12],'BackgroundColor',[0 1 0],...
3999    'Callback',@(hObject,eventdata)OK_Callback(hObject,eventdata),'String','OK','FontUnits','points','FontSize',12,'FontWeight','bold',...
4000    'Tag','OK','TooltipString','''OK'': validate the choice');
4001%  last raw  of the GUI: pushbuttons
4002% uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.35 0.01 0.3 0.15],'BackgroundColor',[0 1 0],'String','OK','Callback',@(hObject,eventdata)OK_Callback(hObject,eventdata),...
4003%     'FontWeight','bold','FontUnits','points','FontSize',12,'TooltipString','''OK'': apply the output to the current field series in uvmat');
4004drawnow
4005
4006%------------------------------------------------------------------------
4007function ListView_Callback(hObject,eventdata)
4008Mode_Callback(hObject,eventdata)
4009
4010%------------------------------------------------------------------------
4011function Mode_Callback(hObject,eventdata)
4012%% get input info
4013hseries=findobj(allchild(0),'tag','series'); % handles of the GUI series
4014hhseries=guidata(hseries); % handles of the elements in the GUI series
4015TimeUnit=get(hhseries.TimeUnit,'String');
4016SeriesData=get(hseries,'UserData');
4017mode_list=get(hObject,'String');
4018mode=mode_list{get(hObject,'Value')};
4019hListView=findobj(get(hObject,'parent'),'Tag','ListView');
4020iview=get(hListView,'Value');
4021i1_series=SeriesData.i1_series{iview};
4022i2_series=SeriesData.i2_series{iview};
4023j1_series=SeriesData.j1_series{iview};
4024j2_series=SeriesData.j2_series{iview};
4025
4026%% enable j index visibility after the new choice
4027
4028if strcmp(mode,'series(Dj)')
4029   status_j='on'; % default
4030else
4031       status_j='off'; % no j index needed for bust case
4032end
4033enable_j(hhseries,status_j) % no j index needed
4034
4035%% get the reference indices for the time interval Dt
4036href_i=findobj(get(hObject,'parent'),'Tag','ref_i');
4037ref_i=[];ref_j=[];
4038if strcmp(get(href_i,'Visible'),'on')
4039    ref_i=str2num(get(href_i,'String'));
4040end
4041if isempty(ref_i)
4042    ref_i=1;
4043end
4044if isempty(ref_j)
4045    ref_j=1;
4046end
4047
4048%% update the menu ListPair
4049Menu=update_listpair(i1_series,i2_series,j1_series,j2_series,mode,SeriesData.Time{iview},TimeUnit,ref_i,ref_j,SeriesData.FileInfo);
4050hlist_pairs=findobj(get(hObject,'parent'),'Tag','ListPair');
4051set(hlist_pairs,'Value',1)% set the first choice by default in ListPair
4052set(hlist_pairs,'String',Menu)% set the menu in ListPair
4053ListPair_Callback(hlist_pairs,[])% apply the default choice in ListPair
4054
4055%-------------------------------------------------------------
4056% --- Executes on selection in ListPair.
4057function ListPair_Callback(hObject,eventdata)
4058%------------------------------------------------------------
4059list_pair=get(hObject,'String'); % get the menu of image pairs
4060if isempty(list_pair)
4061    string='';
4062else
4063    string=list_pair{get(hObject,'Value')};
4064   % string=regexprep(string,',.*',''); % removes time indication (after ',')
4065end
4066hseries=findobj(allchild(0),'tag','series');
4067hPairString=findobj(hseries,'tag','PairString');
4068PairString=get(hPairString,'Data');
4069hListView=findobj(get(hObject,'parent'),'Tag','ListView');
4070iview=get(hListView,'Value');
4071PairString{iview,1}=string;
4072% report the selected pair string to the table PairString
4073set(hPairString,'Data',PairString)
4074
4075
4076%------------------------------------------------------------------------
4077function num_ref_i_Callback(hObject, eventdata)
4078%------------------------------------------------------------------------
4079Mode_Callback([],[])
4080
4081%------------------------------------------------------------------------
4082function num_ref_j_Callback(hObject, eventdata)
4083%------------------------------------------------------------------------
4084Mode_Callback([],[])
4085
4086%------------------------------------------------------------------------
4087function OK_Callback(hObject, eventdata)
4088%------------------------------------------------------------------------
4089delete(get(hObject,'parent'))
4090
4091
4092%------------------------------------------------------------------------
4093% --- Executes on button press in ClearLine.
4094%------------------------------------------------------------------------
4095function ClearLine_Callback(hObject, eventdata, handles)
4096InputTable=get(handles.InputTable,'Data');
4097iline=str2double(get(handles.InputLine,'String'));
4098if size(InputTable,1)>1
4099    InputTable(iline,:)=[]; % suppress the current line if not the first
4100    set(handles.InputTable,'Data',InputTable);
4101end
4102set(handles.REFRESH,'BackgroundColor',[1 0 1])% set REFRESH button to magenta color to indicate that input refr
4103
4104
4105% --- Executes on button press in MonitorCluster.
4106function MonitorCluster_Callback(hObject, eventdata, handles)
4107
4108[rr,ss]=system('oarstat |grep N=UVmat');% check the list of jobs launched with uvmat
4109if isempty(ss)
4110   disp( 'no job presently submitted with uvmat')
4111else
4112    disp('format: R/W=run/wait, time lapsed, R=nbre of cores,W=walltime')
4113    disp(ss)
4114end
4115
4116
4117function OutputSubDir_Callback(hObject, eventdata, handles)
4118set(handles.OutputSubDir,'BackgroundColor',[1 1 1])
4119
4120
4121% --- Executes on button press in CheckOverwrite.
4122function CheckOverwrite_Callback(hObject, eventdata, handles)
4123
4124% --- Executes on button press in TestCPUTime.
4125function TestCPUTime_Callback(hObject, eventdata, handles)
4126% hObject    handle to TestCPUTime (see GCBO)
4127% eventdata  reserved - to be defined in a future version of MATLAB
4128% handles    structure with handles and user data (see GUIDATA)
4129
4130
4131% --- Executes on button press in DiskQuota.
4132function DiskQuota_Callback(hObject, eventdata, handles)
4133SeriesData=get(handles.series,'UserData');
4134system(SeriesData.DiskQuotaCmd)
4135
4136
4137% --- Executes on button press in Replicate.
4138function Replicate_Callback(hObject, eventdata, handles)
4139if get(handles.Replicate,'Value')
4140    InputTable=get(handles.InputTable,'Data');
4141    for ilist=1:size(InputTable,1)
4142        InputDir{ilist}=fullfile(InputTable{ilist,1},InputTable{ilist,2});
4143    end
4144    browse_data(InputDir)
4145else
4146    hh=findobj(allchild(0),'Tag','browse_data');
4147    if ~isempty(hh)
4148        delete(hh)
4149    end
4150end
4151
4152
4153function OutputPath_Callback(hObject, eventdata, handles)
4154
4155
4156function Experiment_Callback(hObject, eventdata, handles)
4157
4158
4159function Device_Callback(hObject, eventdata, handles)
4160
4161
4162% --- Executes on button press in OutputPathBrowse.
4163function OutputPathBrowse_Callback(hObject, eventdata, handles)
4164CheckValue=get(handles.OutputPathBrowse,'Value');
4165if CheckValue
4166OutputPath=uigetdir(get(handles.OutputPath,'String'));
4167set(handles.OutputPath,'String',OutputPath)
4168else
4169    InputTable=get(handles.InputTable,'Data');
4170    set(handles.OutputPath,'String',InputTable{1,1})
4171end
4172
4173
4174% --- Executes on button press in DeleteMask.
4175function DeleteMask_Callback(hObject, eventdata, handles)
4176set(handles.MaskTable,'Data',{})
4177
4178
4179% --- Executes on button press in Relabel.
4180function Relabel_Callback(hObject, eventdata, handles)
4181CheckRelabel=get(hObject,'Value');
4182if CheckRelabel
4183    InputTable=get(handles.InputTable,'Data');%read the table of input file series
4184    XmlFileName=find_imadoc(InputTable{1,1},InputTable{1,2});
4185    if ~isempty(XmlFileName)
4186        XmlData=read_imadoc(XmlFileName);
4187        if isempty(XmlData.FileSeries)
4188            browse_data(fullfile(InputTable{1,1},InputTable{1,2}))
4189        else
4190            hbrowse=findobj(allchild(0),'Tag','browse_data');
4191            if ~isempty(hbrowse)
4192                delete(hbrowse)
4193            end
4194        end
4195    end
4196end
4197check_input_file_series(handles,CheckRelabel)
4198ActionInput_Callback([],[], handles)
4199
4200
Note: See TracBrowser for help on using the repository browser.