source: trunk/src/series.m @ 1067

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