source: trunk/src/series.m @ 1068

Last change on this file since 1068 was 1068, checked in by sommeria, 20 months ago

replicate updated

File size: 171.6 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 processing on multiple experiments set by the GUI browse_data
1597NbExp=1;% initiate the number of experiments set by the GUI browse_data, =1 otherwise
1598if get(handles.Replicate,'Value')
1599    set(handles.Replicate,'BackgroundColor',[1 1 0])%paint Relicate button in yellow
1600    hh=findobj(allchild(0),'Tag','browse_data');
1601    BrowseData=guidata(hh);
1602    SourceDir=get(BrowseData.SourceDir,'String');
1603    ListExp=get(BrowseData.ListExperiments,'String');
1604    ExpIndices=get(BrowseData.ListExperiments,'Value');
1605    ListExp=ListExp(ExpIndices);
1606    ListDevices=get(BrowseData.ListDevices,'String');
1607    DeviceIndices=get(BrowseData.ListDevices,'Value');
1608    ListDevices=ListDevices(DeviceIndices);
1609    ListDataSeries=get(BrowseData.DataSeries,'String');
1610    DataSeriesIndices=get(BrowseData.DataSeries,'Value');
1611    ListDataSeries=ListDataSeries(DataSeriesIndices);
1612    NbExp=0; % counter of the number of experiments set by the GUI browse_data
1613    for iexp=1:numel(ListExp)
1614        if ~isempty(regexp(ListExp{iexp},'^\+/'))% if it is a folder
1615            for idevice=1:numel(ListDevices)
1616                if ~isempty(regexp(ListDevices{idevice},'^\+/'))% if it is a folder
1617                    for isubdir=1:numel(ListDataSeries)
1618                        if ~isempty(regexp(ListDataSeries{isubdir},'^\+/'))% if it is a folder
1619                            lpath= fullfile(SourceDir,regexprep(ListExp{iexp},'^\+/',''),...
1620                                regexprep(ListDevices{idevice},'^\+/',''));
1621                            ldir= regexprep(ListDataSeries{isubdir},'^\+/','');
1622                            if exist(fullfile(lpath,ldir),'dir')
1623                                NbExp=NbExp+1;
1624                                ListPath{NbExp}=lpath;
1625                                ListSubdir{NbExp}=ldir;
1626                                ExpIndex{NbExp}=iexp;
1627                            end
1628                        end
1629                    end
1630                end
1631            end
1632        end
1633    end
1634    answer=msgbox_uvmat('INPUT_Y-N-Cancel',['replicate the processing on ' num2str(NbExp) ' data series']);
1635    if strcmp(answer,'Cancel')||strcmp(answer,'No')
1636        return
1637    end
1638end
1639%      set(handles.OutputSubDir,'String',SubDir)
1640%      Param.OutputSubDir=SubDir;
1641%%%%%%%%%%%%%%%%%%% LOOP ON EXPERIMENTS POSSIBLY SET BY THE GUI browse_data, NbExp=1 otherwise %%%%%%%%%
1642for iexp=1:NbExp
1643    if get(handles.Replicate,'Value')
1644        if ~strcmp(get(handles.RUN,'BusyAction'),'queue')% allow for STOP action
1645            disp('program stopped by user')
1646            return
1647        end
1648        set(BrowseData.ListExperiments,'Value',ExpIndex{iexp})
1649        Param.InputTable{1,1}=ListPath{iexp};
1650        Param.InputTable{1,2}=ListSubdir{iexp};
1651        Param.OutputSubDir=ListSubdir{iexp};
1652        set(handles.InputTable,'Data',Param.InputTable)
1653%         set(handles.OutputSubDir,'String',ListSubdir{iexp})
1654    end
1655    [xx,ExpName]=fileparts(Param.InputTable{1,1});
1656    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
1657    Param.IndexRange.last_i=str2num(get(handles.num_last_i,'String'));
1658    %% create the output data directory if needed
1659    OutputDir='';
1660    answer='';
1661    if isfield(Param,'OutputSubDir')% possibly update the output dir if it already exists
1662        SubDirOut=[get(handles.OutputSubDir,'String') Param.OutputDirExt];
1663        SubDirOutNew=SubDirOut;
1664        detect=exist(fullfile(Param.InputTable{1,1},SubDirOutNew),'dir'); % test if  the dir  already exist
1665        check_create=1; % need to create the result directory by default
1666        CheckOverwrite=1;
1667        if isfield(Param,'CheckOverwrite')
1668            CheckOverwrite=Param.CheckOverwrite;
1669        end
1670        while detect
1671            if CheckOverwrite
1672                comment=', possibly overwrite previous data';
1673            else
1674                comment=', will complement existing result files (no overwriting)';
1675            end
1676            answer=msgbox_uvmat('INPUT_Y-N-Cancel',['use existing ouput directory: ' fullfile(Param.InputTable{1,1},SubDirOutNew) comment]);
1677            if strcmp(answer,'Cancel')
1678                break
1679            elseif strcmp(answer,'Yes')
1680                detect=0;
1681                check_create=0;
1682            else
1683                r=regexp(SubDirOutNew,'(?<root>.*\D)(?<num1>\d+)$','names'); % detect whether name ends by a number
1684                if isempty(r)
1685                    r(1).root=[SubDirOutNew '_'];
1686                    r(1).num1='0';
1687                end
1688                SubDirOutNew=[r(1).root num2str(str2num(r(1).num1)+1)]; % increment the index by 1 or put 1
1689                detect=exist(fullfile(Param.InputTable{1,1},SubDirOutNew),'dir'); % test if  the dir  already exists
1690                check_create=1;
1691            end
1692        end
1693        if strcmp(answer,'Cancel')
1694            continue
1695        end
1696        Param.OutputDirExt=regexprep(SubDirOutNew,Param.OutputSubDir,'');
1697        Param.OutputRootFile=Param.InputTable{1,3}; % the first sorted RootFile taken for output
1698        set(handles.OutputDirExt,'String',Param.OutputDirExt)
1699        OutputDir=fullfile(Param.InputTable{1,1},[Param.OutputSubDir Param.OutputDirExt]) % full name (with path) of output directory
1700        if check_create    % create output directory if it does not exist
1701            [tild,msg1]=mkdir(OutputDir);
1702            if ~strcmp(msg1,'')
1703                errormsg=['cannot create ' OutputDir ': ' msg1]; % error message for directory creation
1704                return
1705            end
1706        end
1707       
1708    elseif isfield(Param,'ActionInput')&&isfield(Param.ActionInput,'LogPath')% custom definition of the output dir
1709        OutputDir=Param.ActionInput.LogPath;
1710    end
1711    DirXml=fullfile(OutputDir,'0_XML');
1712    if ~exist(DirXml,'dir')
1713        [~,msg1]=mkdir(DirXml);
1714        if ~strcmp(msg1,'')
1715            errormsg=['cannot create ' DirXml ': ' msg1]; % error message for directory creation
1716            return
1717        end
1718        [success,msg] = fileattrib(DirXml,'+w','g','s'); % allow writing access for the group of users, recursively in the folder
1719        if success==0
1720            msgbox_uvmat('WARNING',{['unable to set group write access to ' DirXml ':']; msg}); % error message for directory creation
1721        end
1722    end
1723    OutputNomType=nomtype2pair(Param.InputTable{1,4}); % nomenclature for output files
1724   
1725    %% get the set of reference input field indices
1726    first_i=1; % first i index to process
1727    last_i=1; % last i index to process
1728    incr_i=1; % increment step in i index
1729    first_j=1; % first j index to process
1730    last_j=1; % last j index to process
1731    incr_j=1; % increment step in j index
1732    if isfield(Param.IndexRange,'first_i')
1733        first_i=Param.IndexRange.first_i;
1734        incr_i=Param.IndexRange.incr_i;
1735        last_i=Param.IndexRange.last_i;
1736    end
1737    if isfield(Param.IndexRange,'incr_j')
1738        first_j=Param.IndexRange.first_j;
1739        last_j=Param.IndexRange.last_j;
1740        incr_j=Param.IndexRange.incr_j;
1741    end
1742    if last_i < first_i || last_j < first_j
1743        errormsg= 'series/Run_Callback:last field index must be larger or equal to the first one';
1744        return
1745    end
1746    %incr_i must be defined, =1 by default, if NbSlice is active
1747    if isempty(incr_i)&& ~isempty(Param.IndexRange.NbSlice)
1748        incr_i=1;
1749        set(handles.num_incr_i,'String','1')
1750    end
1751    % case of no increment i defined: processing is done on the available files found in i1_series
1752    if isempty(incr_i)
1753        if isempty(incr_j)
1754            [ref_j,ref_i]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1755            ref_j=ref_j(ref_j>=first_j & ref_j<=last_j);
1756            ref_i=ref_i(ref_i>=first_i & ref_i<=last_i);
1757            ref_j=ref_j-1;
1758            ref_i=ref_i-1;
1759        else
1760            ref_j=first_j:incr_j:last_j;
1761            [tild,ref_i]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1762            ref_i=ref_i-1;
1763            ref_i=ref_i(ref_i>=first_i & ref_i<=last_i);
1764        end
1765        % increment i is defined: processing is done on first_i:incr_i:last_i;
1766    else
1767        ref_i=first_i:incr_i:last_i;
1768        if isempty(incr_j)% automatic finding of the existing j indices
1769            [ref_j,tild]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1770            ref_j=ref_j-1;
1771            ref_j=ref_j(ref_j>=first_j & ref_j<=last_j);
1772        else
1773            ref_j=first_j:incr_j:last_j;
1774        end
1775    end
1776    CPUTime=1; % job time estimated at 1 min per iteration (on index i and j) by default
1777    if isfield(Param.Action, 'CPUTime') && ~isempty(Param.Action.CPUTime)
1778        CPUTime=Param.Action.CPUTime; % Note: CpUTime for one iteration ref_i has to be multiplied by the number of j indices nbfield_j
1779    end
1780    nbfield_j=numel(ref_j); % number of j indices
1781    BlockLength=numel(ref_i); % by default, job involves the full set of i field indices
1782    NbProcess=1;
1783    switch RunMode
1784        case 'cluster'
1785            JobNumberMax=SeriesData.SeriesParam.ClusterParam.JobNumberMax;
1786            JobCPUTimeAdvised=SeriesData.SeriesParam.ClusterParam.JobCPUTimeAdvised;
1787            if isempty(Param.IndexRange.NbSlice)% if NbSlice is not defined
1788                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.
1789                BlockLength=max(BlockLength,ceil(numel(ref_i)*NbExp/JobNumberMax)); % possibly increase the BlockLength to have less than MaxJobNumber jobs
1790                NbProcess=ceil(numel(ref_i)/BlockLength) ; % nbre of processes sent to oar
1791            else
1792                NbProcess=Param.IndexRange.NbSlice; % the parameter NbSlice sets the nbre of run processes
1793            end
1794            NbCore=min(NbCore,NbProcess); % reduces the number of cores if it exceeds the number of processes
1795        otherwise
1796            if ~isempty(Param.IndexRange.NbSlice)
1797                NbProcess=Param.IndexRange.NbSlice; % the parameter NbSlice sets the nbre of run processes
1798            end
1799    end
1800   
1801    %% record nbre of output files and starting time for computation for status
1802    StatusData=get(handles.status,'UserData');
1803    if isfield(StatusData,'OutputFileMode')
1804        switch StatusData.OutputFileMode
1805            case 'NbInput'
1806                StatusData.NbOutputFile=numel(ref_i)*nbfield_j;
1807            case 'NbInput_i'
1808                StatusData.NbOutputFile=numel(ref_i);
1809            case 'NbSlice'
1810                StatusData.NbOutputFile=str2num(get(handles.num_NbSlice,'String'));
1811        end
1812    end
1813    StatusData.TimeStart=now;
1814    set(handles.status,'UserData',StatusData)
1815   
1816    %% case of a function in Python
1817    if strcmp(ActionExt, '.py (in dev.)')
1818        fprintf([
1819            '\n' ...
1820            '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n' ...
1821            'The option .py is used. It is still in development.\n' ...
1822            'To try it, first install pyper and the most recent version of fluidimage\n' ...
1823            '(see https://bitbucket.org/fluiddyn/fluidimage).\n' ...
1824            'Warning: there is no direct correspondance between UVMAT and fluidimage parameters\n' ...
1825            '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n'])
1826        RunMode = 'python';
1827    end
1828   
1829   
1830    %% direct processing on the current Matlab session or creation of command files
1831    filexml=cell(1,NbProcess); % initialisation of the names of the files containing the processing parameters
1832    extxml=cell(1,NbProcess); % initialisation of the set of labels used for the files documenting each process
1833    for iprocess=1:NbProcess
1834        extxml{iprocess}='.xml';
1835    end
1836    for iprocess=1:NbProcess
1837        if ~strcmp(get(handles.RUN,'BusyAction'),'queue')% allow for STOP action
1838            disp('program stopped by user')
1839            return
1840        end
1841        if isempty(Param.IndexRange.NbSlice)
1842            Param.IndexRange.first_i=first_i+(iprocess-1)*BlockLength*incr_i;
1843            if Param.IndexRange.first_i>last_i
1844                NbProcess=iprocess-1; % leave the loop, we are at the end of the calculation
1845                break
1846            end
1847            Param.IndexRange.last_i=min(last_i,first_i+(iprocess)*BlockLength*incr_i-1);
1848        else %multislices (then incr_i is not empty)
1849            Param.IndexRange.first_i= first_i+iprocess-1;
1850            Param.IndexRange.incr_i=incr_i*Param.IndexRange.NbSlice;
1851        end
1852        for ilist=1:size(Param.InputTable,1)
1853            Param.InputTable{ilist,1}=regexprep(Param.InputTable{ilist,1},'\','/'); % correct path name for PCWIN system
1854        end
1855       
1856        if isfield(Param,'OutputSubDir')
1857            t=struct2xml(Param);
1858            t=set(t,1,'name','Series');
1859            extxml{iprocess}=fullfile_uvmat('','',Param.InputTable{1,3},'.xml',OutputNomType,...
1860                Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1861            filexml{iprocess}=fullfile(OutputDir,'0_XML',extxml{iprocess});
1862            try
1863                save(t, filexml{iprocess}); % save the xml file containing the processing parameters
1864            catch ME
1865                if ~strcmp (RunMode,'local')
1866                    errormsg=['error writting ' filexml{iprocess} ': ' ME.message];
1867                    return
1868                end
1869            end
1870        end
1871        if strcmp (RunMode,'local')
1872            switch ActionExt
1873                case '.m'
1874                    h_fun(Param); % direct launching
1875                   
1876                case '.sh'
1877                    switch computer
1878                        case {'PCWIN','PCWIN64'} %Windows system
1879                            filexml=regexprep(filexml,'\\','\\\\'); % add '\' so that '\' are left as characters
1880                            system([ActionFullName ' ' RunTime ' ' filexml{iprocess}]); % TODO: adapt to DOS system
1881                        case {'GLNX86','GLNXA64','MACI64'}%Linux  system
1882                            system([ActionFullName ' ' RunTime ' ' filexml{iprocess}]);
1883                    end
1884            end
1885        end
1886    end
1887   
1888    if ~strcmp (RunMode,'local') && ~strcmp(RunMode,'python')
1889        %% processing on a different session of the same computer (background) or cluster, create executable files
1890        batch_file_list=cell(NbProcess,1); % initiate the list of executable files
1891        DirExe=fullfile(OutputDir,'0_EXE'); % directory name for executable files
1892        switch computer
1893            case {'PCWIN','PCWIN64'} %Windows system
1894                ExeExt='.bat';
1895            case {'GLNX86','GLNXA64','MACI64'}%Linux  system
1896                ExeExt='.sh';
1897        end
1898        %create subdirectory for executable files
1899        if ~exist(DirExe,'dir')
1900            [tild,msg1]=mkdir(DirExe);
1901            if ~strcmp(msg1,'')
1902                errormsg=['cannot create ' DirExe ': ' msg1]; % error message for directory creation
1903                return
1904            end
1905            [success,msg] = fileattrib(DirExe,'+w','g','s'); % allow writing access for the group of users, recursively in the folder
1906            if success==0
1907                msgbox_uvmat('WARNING',{['unable to set group write access to ' DirExe ':']; msg}); % error message for directory creation
1908            end
1909        end
1910        %create subdirectory for log files
1911        DirLog=fullfile(OutputDir,'0_LOG');
1912        if ~exist(DirLog,'dir')
1913            [tild,msg1]=mkdir(DirLog);
1914            if ~strcmp(msg1,'')
1915                errormsg=['cannot create ' DirLog ': ' msg1]; % error message for directory creation
1916                return
1917            end
1918            [success,msg] = fileattrib(DirLog,'+w','g','s'); % allow writing access for the group of users, recursively in the folder
1919            if success==0
1920                msgbox_uvmat('WARNING',{['unable to set group write access to ' DirLog ':']; msg}); % error message for directory creation
1921            end
1922        end
1923       
1924        %create the executable file
1925        file_exe_global=fullfile_uvmat('','',Param.InputTable{1,3},ExeExt,OutputNomType,...
1926            first_i,last_i,first_j,last_j);
1927        file_exe_global=fullfile(OutputDir,'0_EXE',file_exe_global);
1928        filelog_global=fullfile_uvmat('','',Param.InputTable{1,3},'.log',OutputNomType,...
1929            first_i,last_i,first_j,last_j);
1930        filelog_global=fullfile(OutputDir,'0_LOG',filelog_global);
1931       
1932        for iprocess=1:NbProcess
1933            %create the executable file
1934            batch_file_list{iprocess}=fullfile(OutputDir,'0_EXE',regexprep(extxml{iprocess},'.xml$',ExeExt));
1935           
1936            % set the log file name
1937            filelog{iprocess}=fullfile(OutputDir,'0_LOG',regexprep(extxml{iprocess},'.xml$','.log'));
1938        end
1939    end
1940   
1941    %% launch the executable files for background or cluster processing
1942   
1943    switch RunMode
1944       
1945        case 'background'
1946            [fid,message]=fopen(file_exe_global,'w');
1947            if isequal(fid,-1)
1948                errormsg=['creation of ' file_exe_global ':' message];
1949                return
1950            end
1951            switch ActionExt
1952                case '.m'% Matlab function
1953                    switch computer
1954                        case {'GLNX86','GLNXA64','MACI64'}
1955                            matlab_ver = ver('MATLAB');
1956                            matlab_version = matlab_ver.Version;
1957                            cmd=[...
1958                                '#!/bin/bash\n'...
1959                                'source /etc/profile\n'...
1960                                'module load matlab/' matlab_version '\n'...% CHOICE OF MATLAB VERSION
1961                                'time_start=$(date +%%s)\n'...
1962                                'matlab -nodisplay -nosplash -nojvm -logfile ''' filelog_global ''' <<END_MATLAB\n'...
1963                                'addpath(''' path_series ''');\n'...
1964                                'addpath(''' Param.Action.ActionPath ''');\n'];
1965                            for iprocess=1:NbProcess
1966                                cmd=[cmd '' Param.Action.ActionName  '(''' filexml{iprocess} ''');\n'];
1967                            end
1968                            cmd=[cmd  'exit\n' 'END_MATLAB\n'...
1969                                'time_end=$(date +%%s)\n'...
1970                                'echo "global time = " $(($time_end - $time_start)) >> ''' filelog_global '''\n'];
1971                            fprintf(fid,cmd); % fill the executable file with the  char string cmd
1972                            fclose(fid); % close the executable filefilelog_global
1973                            system(['chmod +x ' file_exe_global]); % set the file to executable
1974                        case {'PCWIN','PCWIN64'}
1975                            cmd=['matlab -automation -logfile ' regexprep(filelog{iprocess},'\\','\\\\')...
1976                                ' -r "addpath(''' regexprep(path_series,'\\','\\\\') ''');'...
1977                                'addpath(''' regexprep(Param.Action.ActionPath,'\\','\\\\') ''');'];
1978                            for iprocess=1:NbProcess
1979                                cmd=[cmd '' Param.Action.ActionName  '( ''' regexprep(filexml{iprocess},'\\','\\\\') ''');']
1980                            end
1981                            cmd=[cmd ';exit"'];
1982                            fprintf(fid,cmd); % fill the executable file with the  char string cmd
1983                            fclose(fid); % close the executable file
1984                    end
1985                    system([file_exe_global ' &'])% directly execute the command file
1986                case '.sh' % compiled Matlab function
1987                    for iprocess=1:NbProcess
1988                        switch computer
1989                            case {'GLNX86','GLNXA64','MACI64'}
1990                                [fid,message]=fopen(batch_file_list{iprocess},'w'); % create the executable file
1991                                if isequal(fid,-1)
1992                                    errormsg=['creation of .bat file: ' message];
1993                                    return
1994                                end
1995                                cmd=['#!/bin/bash \n '...
1996                                    '#$ -cwd \n '...
1997                                    'hostname && date \n '...
1998                                    'umask 002 \n'...
1999                                    ActionFullName ' ' RunTime ' ' filexml{iprocess}]; % allow writting access to created files for user group
2000                                fprintf(fid,cmd); % fill the executable file with the  char string cmd
2001                                fclose(fid); % close the executable file
2002                                system(['chmod +x ' batch_file_list{iprocess}]); % set the file to executable
2003                                system([batch_file_list{iprocess} ' &'])% directly execute the command file
2004                            case {'PCWIN','PCWIN64'}
2005                                msgbox_uvmat('ERROR','option for compiled Matlab functions not implemented for Windows system')
2006                                return
2007                        end
2008                    end
2009                    msgbox_uvmat('CONFIRMATION',[ActionFullName ' launched in background for ' ExpName ': press STATUS to see results'])
2010            end
2011           
2012        case 'cluster' % option 'oar-parexec' used
2013            %create subdirectory for oar commands
2014            for iprocess=1:NbProcess
2015                [fid,message]=fopen(batch_file_list{iprocess},'w'); % create the executable file
2016                if isequal(fid,-1)
2017                    errormsg=['creation of .bat file: ' message];
2018                    return
2019                end
2020                if  strcmp(ActionExt,'.sh')
2021                    cmd=['#!/bin/bash \n '...
2022                        '#$ -cwd \n '...
2023                        'hostname && date \n '...
2024                        'umask 002 \n'...
2025                        ActionFullName ' ' RunTime ' ' filexml{iprocess}]; % allow writting access to created files for user group
2026                else
2027                    matlab_ver = ver('MATLAB');
2028                    matlab_version = matlab_ver.Version;
2029                    cmd=[...
2030                        '#!/bin/bash\n'...
2031                        'source /etc/profile\n'...
2032                        'module load matlab/' matlab_version '\n'...% CHOICE OF MATLAB VERSION
2033                        'matlab -nodisplay -nosplash -nojvm -singleCompThread -logfile ''' filelog{iprocess} ''' <<END_MATLAB\n'...
2034                        'addpath(''' path_series ''');\n'...
2035                        'addpath(''' Param.Action.ActionPath ''');\n'...
2036                        '' Param.Action.ActionName  '(''' filexml{iprocess} ''');\n'...
2037                        'exit\n'...
2038                        'END_MATLAB\n'];
2039                end
2040                fprintf(fid,cmd); % fill the executable file with the  char string cmd
2041                fclose(fid); % close the executable file
2042                system(['chmod +x ' batch_file_list{iprocess}]); % set the file to executable
2043            end
2044            DIR_CLUSTER=fullfile(OutputDir,'0_CLUSTER');
2045            if exist(DIR_CLUSTER,'dir')% delete the content of the dir 0_LOG to allow new input
2046                curdir=pwd;
2047                cd(DIR_CLUSTER)
2048                delete('*')
2049                cd(curdir)
2050            else
2051                [tild,msg1]=mkdir(DIR_CLUSTER);
2052                if ~strcmp(msg1,'')
2053                    errormsg=['cannot create ' DIR_CLUSTER ': ' msg1]; % error message for directory creation
2054                    return
2055                end
2056            end
2057            % create file containing the list of jobs
2058            ListProcess=fullfile(DIR_CLUSTER,'job_list.txt'); % name of the file containing the list of executables
2059            fid=fopen(ListProcess,'w'); % open it for writting
2060            for iprocess=1:length(batch_file_list)
2061                fprintf(fid,[batch_file_list{iprocess} '\n']); % write list of exe files
2062            end
2063            fclose(fid);
2064            system(['chmod +x ' ListProcess]); % set the file to executable
2065           
2066            CPUTimeProcess=CPUTime*BlockLength*nbfield_j; % estimated CPU time for one individual process (in minutes)
2067            LaunchCmdFcn=SeriesData.SeriesParam.ClusterParam.LaunchCmdFcn;
2068            oar_command=feval(LaunchCmdFcn,ListProcess,ActionFullName,DirLog,NbProcess, NbCore,CPUTimeProcess)
2069            [status,result]=system(oar_command)% execute system command and show the result (ID number of the launched job) on the Matlab command window
2070            filename_oarcommand=fullfile(DIR_CLUSTER,'0_cluster_command'); % keep track of the command in file '0-OAR/0_cluster_command'
2071            fid=fopen(filename_oarcommand,'w');
2072            fprintf(fid,oar_command); % store the command
2073            fprintf(fid,result); % store the result (job ID number)
2074            fclose(fid);
2075            if status==0
2076                msgbox_uvmat('CONFIRMATION',[ActionFullName ' launched for ' ExpName ' as ' num2str(NbProcess) ' processes in cluster: press STATUS to see results'])
2077            else
2078                msgbox_uvmat('ERROR',result)
2079            end
2080            %     case 'cluster_pbs' % for LMFA Kepler machine:  trqnsferred to fct
2081           
2082            %         %create subdirectory for pbs command and log files
2083            %         DirPBS=fullfile(OutputDir,'0_PBS'); % todo : common name OAR/PBS
2084            %         if exist(DirPBS,'dir')% delete the content of the dir 0_LOG to allow new input
2085            %             curdir=pwd;
2086            %             cd(DirPBS)
2087            %             delete('*')
2088            %             cd(curdir)
2089            %         else
2090            %             [tild,msg1]=mkdir(DirPBS);
2091            %             if ~strcmp(msg1,'')
2092            %                 errormsg=['cannot create ' DirPBS ': ' msg1]; % error message for directory creation
2093            %                 return
2094            %             end
2095            %         end
2096            %         max_walltime=3600*20; % 20h max total calculation (cannot exceed 24 h)
2097            %         walltime_onejob=1800; % seconds, max estimated time for asingle file index value
2098            %         ListProcess=fullfile(DirPBS,'job_list.txt'); % create name of the global executable file
2099            %         fid=fopen(ListProcess,'w');
2100            %         for iprocess=1:length(batch_file_list)
2101            %             fprintf(fid,[batch_file_list{iprocess} '\n']); % list of exe files
2102            %         end
2103            %         fclose(fid);
2104            %         system(['chmod +x ' ListProcess]); % set the file to executable
2105            %         pbs_command=['qsub -n CIVX '...
2106            %             '-t idempotent --checkpoint ' num2str(walltime_onejob+60) ' '...
2107            %             '-l /core=' num2str(NbCore) ','...
2108            %             'walltime=' datestr(min(1.05*walltime_onejob/86400*max(NbProcess*BlockLength*nbfield_j,NbCore)/NbCore,max_walltime/86400),13) ' '...
2109            %             '-E ' regexprep(ListProcess,'\.txt\>','.stderr') ' '...
2110            %             '-O ' regexprep(ListProcess,'\.txt\>','.log') ' '...
2111            %             extra_qstat ' '...
2112            %             '"oar-parexec -s -f ' ListProcess ' '...
2113            %             '-l ' ListProcess '.log"'];
2114            %         filename_oarcommand=fullfile(DirPBS,'pbs_command');
2115            %         fid=fopen(filename_oarcommand,'w');
2116            %         fprintf(fid,pbs_command);
2117            %         fclose(fid);
2118            %         fprintf(pbs_command); % display in command line
2119            %         %system(pbs_command);
2120            %         msgbox_uvmat('CONFIRMATION',[ActionFullName ' command ready to be launched in cluster'])
2121           
2122        case 'cluster_sge' % for PSMN % TODO: use the standard 'cluster' config with an external fct
2123            % Au PSMN, on ne cr??e pas 1 job avec plusieurs c??urs, mais N jobs de 1 c??urs
2124            % o?? N < 1000.
2125            %create subdirectory for pbs command and log files
2126           
2127            DirSGE=fullfile(OutputDir,'0_SGE');
2128            if exist(DirSGE,'dir')% delete the content of the dir 0_LOG to allow new input
2129                curdir=pwd;
2130                cd(DirSGE)
2131                delete('*')
2132                cd(curdir)
2133            else
2134                [tild,msg1]=mkdir(DirSGE);
2135                if ~strcmp(msg1,'')
2136                    errormsg=['cannot create ' DirSGE ': ' msg1]; % error message for directory creation
2137                    return
2138                end
2139            end
2140            maxImgsPerJob = ceil(length(batch_file_list)/NbCore);
2141            disp(['Max number of jobs: ' num2str(NbCore)])
2142            disp(['Images per job: ' num2str(maxImgsPerJob)])
2143           
2144            iprocess = 1;
2145            imgsInJob = [];
2146            currJobIndex = 1;
2147            done = 0;
2148            while(~done)
2149                if(iprocess <= length(batch_file_list))
2150                    imgsInJob = [imgsInJob, iprocess];
2151                end
2152                if((numel(imgsInJob) >= maxImgsPerJob) || (iprocess == length(batch_file_list)))
2153                    cmd=['#!/bin/sh \n'...
2154                        '#$ -cwd \n'...
2155                        'hostname && date\n']
2156                    for ii=1:numel(imgsInJob)
2157                        cmd=[cmd ActionFullName ' /softs/matlab ' filexml{imgsInJob(ii)} '\n'];
2158                    end
2159                    [fid, message] = fopen([DirSGE '/job' num2str(currJobIndex) '.sh'], 'w');
2160                    fprintf(fid, cmd);
2161                    fclose(fid);
2162                    system(['chmod +x ' DirSGE '/job' num2str(currJobIndex) '.sh'])
2163                    sge_command=['qsub -N civ_' num2str(currJobIndex) ' '...
2164                        '-q ' qstat_Queue ' '...
2165                        '-e ' fullfile([DirSGE '/job' num2str(currJobIndex) '.out']) ' '...
2166                        '-o ' fullfile([DirSGE '/job' num2str(currJobIndex) '.out']) ' '...
2167                        fullfile([DirSGE '/job' num2str(currJobIndex) '.sh'])];
2168                    fprintf(sge_command); % display in command line
2169                    [status, result] = system(sge_command);
2170                    fprintf(result);
2171                    currJobIndex = currJobIndex + 1;
2172                    imgsInJob = [];
2173                end
2174                if(iprocess == length(batch_file_list))
2175                    done = 1;
2176                end
2177                iprocess = iprocess + 1;
2178            end
2179            msgbox_uvmat('CONFIRMATION',[num2str(currJobIndex-1) ' jobs launched on queue ' qstat_Queue '.'])
2180        case 'python'
2181            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))") ' ...
2182                'python -m fluidimage.run_from_xml ' filexml{iprocess}];
2183            fprintf(['command:\n' command '\n\n'])
2184            system(command, '-echo');
2185    end
2186    if exist(OutputDir,'dir')
2187        [SUCCESS,MESSAGE,MESSAGEID] = fileattrib (OutputDir);
2188        if MESSAGE.GroupWrite~=1
2189            [success,msg] = fileattrib(OutputDir,'+w','g','s'); % allow writing access for the group of users, recursively in the folder
2190            if success==0
2191                msgbox_uvmat('WARNING',{['unable to set group write access to ' OutputDir ':']; msg}); % error message for directory creation
2192            end
2193        end
2194    end
2195end
2196set(handles.Replicate,'BackgroundColor',[0 1 0])
2197if NbExp>1
2198    set(handles.REFRESH,'BackgroundColor',[1 0 1])% set REFRESH button to magenta (input file features need to be updated)
2199end
2200%------------------------------------------------------------------------
2201function STOP_Callback(hObject, eventdata, handles)
2202%------------------------------------------------------------------------
2203set(handles.RUN, 'BusyAction','cancel')
2204set(handles.RUN,'BackgroundColor',[1 0 0])
2205set(handles.RUN,'enable','on')
2206set(handles.RUN, 'Value',0)
2207
2208%------------------------------------------------------------------------
2209% --- read parameters from the GUI series
2210%------------------------------------------------------------------------
2211function Param=read_GUI_series(handles)
2212
2213%% read raw parameters from the GUI series
2214Param=read_GUI(handles.series);
2215
2216%% clean the output structure by removing unused information
2217if isfield(Param,'Pairs')
2218    Param=rmfield(Param,'Pairs'); % info Pairs not needed for output
2219end
2220if isfield(Param,'InputLine')
2221    Param=rmfield(Param,'InputLine');
2222end
2223if isfield(Param,'EditObject')
2224    Param=rmfield(Param,'EditObject');
2225end
2226Param.IndexRange.TimeSource=Param.IndexRange.TimeTable{end,1};
2227Param.IndexRange=rmfield(Param.IndexRange,'TimeTable');
2228empty_line=false(size(Param.InputTable,1),1);
2229for iline=1:size(Param.InputTable,1)
2230    empty_line(iline)=isempty(cell2mat(Param.InputTable(iline,1:3)));
2231end
2232Param.InputTable(empty_line,:)=[];
2233
2234%------------------------------------------------------------------------
2235% --- Executes on selection change in ActionName.
2236function ActionName_Callback(hObject, ActionPath, handles)
2237%------------------------------------------------------------------------
2238
2239%% stop any ongoing series processing
2240if isequal(get(handles.RUN,'Value'),1)
2241    answer= msgbox_uvmat('INPUT_Y-N','stop current Action process?');
2242    if strcmp(answer,'Yes')
2243        STOP_Callback(hObject, [], handles)
2244    else
2245        return
2246    end
2247end
2248set(handles.ActionName,'BackgroundColor',[1 1 0])
2249huigetfile=findobj(allchild(0),'tag','status_display');
2250if ~isempty(huigetfile)
2251    delete(huigetfile)
2252end
2253drawnow
2254
2255%% get Action name and path
2256NbBuiltinAction=get(handles.Action,'UserData'); % nbre of functions initially proposed in the menu ActionName (as defined in the Opening fct of series)
2257ActionList=get(handles.ActionName,'String'); % list menu fields
2258ActionIndex=get(handles.ActionName,'Value');
2259if ~isequal(ActionIndex,1)% if we are not just opening series
2260    InputTable=get(handles.InputTable,'Data');
2261    if isempty(InputTable{1,4})
2262        msgbox_uvmat('ERROR','no input file available: use Open in the menu bar')
2263        return
2264    end
2265end
2266ActionName= ActionList{get(handles.ActionName,'Value')}; % selected function name
2267ActionPathList=get(handles.ActionName,'UserData'); % list of recorded paths to functions of the list ActionName
2268
2269%% add a new function to the menu if 'more...' has been selected in the menu ActionName
2270if isequal(ActionName,'more...')
2271    if ~ischar(ActionPath)
2272        ActionPath=get(handles.ActionPath,'String');
2273    end
2274    [FileName, PathName] = uigetfile( ...
2275        {'*.m', ' (*.m)';
2276        '*.m',  '.m files '; ...
2277        '*.*', 'All Files (*.*)'}, ...
2278        'Pick a series processing function ',ActionPath);
2279    if length(FileName)<2
2280        return
2281    end
2282    [tild,ActionName,ActionExt]=fileparts(FileName);
2283   
2284    % insert the choice in the menu ActionName
2285    ActionIndex=find(strcmp(ActionName,ActionList),1); % look for the selected function in the menu Action
2286    PathName=regexprep(PathName,'/$','');
2287    if ~isempty(ActionIndex) && ~strcmp(ActionPathList{ActionIndex},PathName)%compare the path to the existing fct
2288        ActionIndex=[]; % the selected path is different than the recorded one
2289    end
2290    if isempty(ActionIndex)%the qselected fct (with selected path) does not exist in the menu
2291        ActionIndex= length(ActionList);
2292        ActionList=[ActionList(1:end-1);{ActionName};ActionList(end)]; % the selected function is appended in the menu, before the last item 'more...'
2293         ActionPathList=[ActionPathList; PathName];
2294    end
2295   
2296    % record the file extension and extend the path list if it is a new extension
2297    ActionExtList=get(handles.ActionExt,'String');
2298    ActionExtIndex=find(strcmp(ActionExt,ActionExtList), 1);
2299    if isempty(ActionExtIndex)
2300        set(handles.ActionExt,'String',[ActionExtList;{ActionExt}])
2301    end
2302
2303    % remove old Action options in the menu (keeping a menu length <nb_builtin_ACTION+5)
2304    if length(ActionList)>NbBuiltinAction+5; % nb_builtin_ACTION=nbre of functions always remaining in the initial menu
2305        nbremove=length(ActionList)-NbBuiltinAction-5;
2306        ActionList(NbBuiltinAction+1:end-5)=[];
2307        ActionPathList(NbBuiltinAction+1:end-4,:)=[];
2308        ActionIndex=ActionIndex-nbremove;
2309    end
2310   
2311    % record action menu, choice and path
2312    set(handles.ActionName,'Value',ActionIndex)
2313    set(handles.ActionName,'String',ActionList)
2314       set(handles.ActionName,'UserData',ActionPathList);
2315    set(handles.ActionExt,'Value',ActionExtIndex)
2316       
2317    %record the user defined menu additions in personal file profil_perso
2318    dir_perso=prefdir;
2319    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
2320    if NbBuiltinAction+1<=numel(ActionList)-1
2321        ActionListUser=ActionList(NbBuiltinAction+1:numel(ActionList)-1);
2322        ActionPathListUser=ActionPathList(NbBuiltinAction+1:numel(ActionList)-1);
2323        ActionExtListUser={};
2324        if numel(ActionExtList)>2
2325            ActionExtListUser=ActionExtList(3:end);
2326        end
2327        if exist(profil_perso,'file')
2328            save(profil_perso,'ActionListUser','ActionPathListUser','ActionExtListUser','-append')
2329        else
2330            save(profil_perso,'ActionListUser','ActionPathListUser','ActionExtListUser','-V6')
2331        end
2332    end
2333end
2334
2335%% check the current ActionPath to the selected function
2336ActionPath=ActionPathList{ActionIndex}; % current recorded path
2337set(handles.ActionPath,'String',ActionPath); % show the path to the senlected function
2338
2339%% reinitialise the waitbar
2340update_waitbar(handles.Waitbar,0)
2341
2342%% Put the first line of the selected Action fct as tooltip help
2343try
2344    [fid,errormsg] =fopen([ActionName '.m']);
2345    InputText=textscan(fid,'%s',1,'delimiter','\n');
2346    fclose(fid);
2347    set(handles.ActionName,'ToolTipString',InputText{1}{1})% put the first line of the selected function as tooltip help
2348end
2349set(handles.ActionName,'BackgroundColor',[1 1 1])
2350set(handles.ActionInput,'BackgroundColor',[1 0 1])% set ActionInput button to magenta color to indicate that input refr
2351
2352
2353% --- Executes on button press in ActionInput.
2354function ActionInput_Callback(hObject, eventdata, handles)
2355
2356set(handles.ActionInput,'BackgroundColor',[1 1 0])
2357SeriesData=get(handles.series,'UserData'); % info on the input file series
2358
2359%% create the function handle for Action
2360ActionPath=get(handles.ActionPath,'String');
2361ActionList=get(handles.ActionName,'String');
2362ActionName= ActionList{get(handles.ActionName,'Value')}; % selected function name
2363if ~exist(ActionPath,'dir')
2364    ActionName_Callback(handles.ActionName, ActionPath, handles)% update the function
2365    return
2366end
2367current_dir=pwd; % current working dir
2368cd(ActionPath)
2369h_fun=str2func(ActionName);
2370cd(current_dir)
2371
2372%% Activate the Action fct to adapt the configuration of the GUI series and bring specific parameters in SeriesData
2373Param=read_GUI_series(handles); % read the parameters from the GUI series
2374Param.Action.RUN=0;
2375Param.SeriesData=SeriesData;
2376ParamOut=h_fun(Param); % run the selected Action function to get the relevant input
2377
2378
2379%% Visibility of VelType and VelType_1 menus asked by ActionName
2380VelTypeRequest=1; % VelType requested by default
2381VelTypeRequest_1=1; % VelType requested by default
2382if isfield(ParamOut,'VelType')
2383    VelTypeRequest=ismember(ParamOut.VelType,{'on','one','two'});
2384    VelTypeRequest_1=strcmp( ParamOut.VelType,'two');
2385end
2386FieldNameRequest=0;  %hidden by default
2387FieldNameRequest_1=0;  %hidden by default
2388if isfield(ParamOut,'FieldName')
2389    FieldNameRequest=ismember(ParamOut.FieldName,{'on','one','two'});
2390    FieldNameRequest_1=strcmp( ParamOut.FieldName,'two');
2391end
2392
2393%% Detect the types of input files and set menus and default options in 'VelType'
2394iview_civ=find(strcmp('civx',SeriesData.FileType)|strcmp('civdata',SeriesData.FileType));
2395iview_netcdf=find(strcmp('netcdf',SeriesData.FileType)|strcmp('civx',SeriesData.FileType)|strcmp('civdata',SeriesData.FileType)); % all nc files, icluding civ
2396FieldList=get(handles.FieldName,'String'); % previous list as default
2397if ~iscell(FieldList),FieldList={FieldList};end
2398FieldList_1=get(handles.FieldName_1,'String'); % previous list as default
2399if ~iscell(FieldList_1),FieldList_1={FieldList_1};end
2400CheckList_1=1; % indicate whether FieldName_1 has been updated
2401handles_coord=[handles.Coord_x handles.Coord_y handles.Coord_z handles.Coord_x_title handles.Coord_y_title handles.Coord_z_title];
2402if VelTypeRequest && numel(iview_civ)>=1
2403    menu=set_veltype_display(SeriesData.FileInfo{iview_civ(1)}.CivStage,SeriesData.FileType{iview_civ(1)});
2404    set(handles.VelType,'Value',1)% set first choice by default
2405    set(handles.VelType,'String',[{'*'};menu])
2406    set(handles.VelType,'Visible','on')
2407    set(handles.VelType_title,'Visible','on')
2408    FieldList=set_field_list('U','V'); % standard menu for civx data
2409    if max(get(handles.FieldName,'Value'))>numel(FieldList)
2410    set(handles.FieldName,'Value',1); % velocity vector choice by default
2411    end
2412    if  VelTypeRequest_1 && numel(iview_civ)>=2
2413        menu=set_veltype_display(SeriesData.FileInfo{iview_civ(2)}.CivStage,SeriesData.FileType{iview_civ(2)});
2414        set(handles.VelType_1,'Value',1)% set first choice by default
2415        set(handles.VelType_1,'String',[{'*'};menu])
2416        set(handles.VelType_1,'Visible','on')
2417        set(handles.VelType_title_1,'Visible','on')
2418        FieldList_1=[set_field_list('U','V');{'C'};{'get_field...'}]; % standard menu for civx data
2419        CheckList_1=1;
2420        set(handles.FieldName_1,'Value',1); % velocity vector choice by default
2421    else
2422        set(handles.VelType_1,'Visible','off')
2423        set(handles.VelType_title_1,'Visible','off')
2424    end
2425else
2426    set(handles.VelType,'Visible','off')
2427    set(handles.VelType_title,'Visible','off')
2428end
2429
2430%% Detect the types of input files and set menus and default options in 'FieldName'
2431if (FieldNameRequest || VelTypeRequest) && numel(iview_netcdf)>=1
2432    set(handles.InputFields,'Visible','on')% set the frame InputFields visible
2433    if FieldNameRequest && isfield(SeriesData.FileInfo{iview_netcdf(1)},'ListVarName')
2434        set(handles.FieldName,'Visible','on')
2435        ListVarName=SeriesData.FileInfo{iview_netcdf(1)}.ListVarName;
2436        ind_var=get(handles.FieldName,'Value'); % indices of previously selected variables
2437        for ilist=1:numel(ind_var)
2438            if isempty(find(strcmp(FieldList{ind_var(ilist)},ListVarName)))
2439                FieldList={}; % previous choice not consistent with new input field
2440                set(handles.FieldName,'Value',1)
2441                break
2442            end
2443        end
2444        if ~isempty(FieldList)
2445            if isempty(find(strcmp(get(handles.Coord_x,'String'),ListVarName)))||...
2446                    isempty(find(strcmp(get(handles.Coord_y,'String'),ListVarName)))
2447                FieldList={};
2448                set(handles.Coord_x,'String','')
2449                set(handles.Coord_y,'String','')
2450            end
2451            Coord_z=get(handles.Coord_z,'String');
2452            if ~isempty(Coord_z) && isempty(find(strcmp(Coord_z,ListVarName)))
2453                FieldList={};
2454                set(handles.Coord_z,'String','')
2455            end
2456        end
2457    else
2458        set(handles.FieldName,'Visible','off')
2459    end
2460   
2461    set(handles_coord,'Visible','on')
2462    if isempty(find(strcmp('get_field...',FieldList)))
2463    FieldList=[FieldList;{'get_field...'}];%add 'get_field...' to the menu FieldName if it is not already
2464    end
2465    if FieldNameRequest_1 && numel(iview_netcdf)>=2
2466        set(handles.FieldName_1,'Visible','on')
2467        if CheckList_1==0        % not civ input made
2468            ListVarName=SeriesData.FileInfo{iview_netcdf(2)}.ListVarName;
2469            ind_var=get(handles.FieldName,'Value'); % indices of previously selected variables
2470            for ilist=1:numel(ind_var)
2471                if isempty(find(strcmp(FieldList{ind_var(ilist)},ListVarName)))
2472                    FieldList_1={}; % previous choice not consistent with new input field
2473                    set(handles.FieldName_1,'Value',1)
2474                    break
2475                end
2476            end
2477            warn_coord=0;
2478            if isempty(find(strcmp(get(handles.Coord_x,'String'),ListVarName)))||...
2479                    isempty(find(strcmp(get(handles.Coord_y,'String'),ListVarName)))
2480                warn_coord=1;
2481            end
2482            if ~isempty(Coord_z) && isempty(find(strcmp(Coord_z,ListVarName)))
2483                FieldList_1={};
2484                warn_coord=1;
2485            end
2486            if warn_coord
2487                msgbox_uvmat('WARNING','coordinate names do not exist in the second netcdf input file')
2488            end
2489           
2490            set(handles.FieldName_1,'Visible','on')
2491            set(handles.FieldName_1,'Value',1)
2492            set(handles.FieldName_1,'String',FieldList_1)
2493        end
2494    else
2495        set(handles.FieldName_1,'Visible','off')
2496    end
2497    if isempty(FieldList)
2498        set(handles.FieldName,'Visible','off')
2499    else
2500        set(handles.FieldName,'Visible','on')
2501        set(handles.FieldName,'String',FieldList)
2502    end
2503else
2504    set(handles.InputFields,'Visible','off')
2505end
2506
2507%% Introduce visibility of file overwrite option
2508if isfield(ParamOut,'CheckOverwriteVisible')&& strcmp(ParamOut.CheckOverwriteVisible,'on')
2509    set(handles.CheckOverwrite,'Visible','on')
2510else
2511    set(handles.CheckOverwrite,'Visible','off')
2512end
2513
2514%% Check whether alphabetical sorting of input Subdir is allowed by the Action fct  (for multiples series entries)
2515if isfield(ParamOut,'AllowInputSort')&&isequal(ParamOut.AllowInputSort,'on')&& size(Param.InputTable,1)>1
2516    [tild,iview]=sort(Param.InputTable(:,2)); % subdirectories sorted in alphabetical order
2517    set(handles.InputTable,'Data',Param.InputTable(iview,:));
2518    MinIndex_i=get(handles.MinIndex_i,'Data');
2519    MinIndex_j=get(handles.MinIndex_j,'Data');
2520    MaxIndex_i=get(handles.MaxIndex_i,'Data');
2521    MaxIndex_j=get(handles.MaxIndex_j,'Data');
2522    set(handles.MinIndex_i,'Data',MinIndex_i(iview,:));
2523    set(handles.MinIndex_j,'Data',MinIndex_j(iview,:));
2524    set(handles.MaxIndex_i,'Data',MaxIndex_i(iview,:));
2525    set(handles.MaxIndex_j,'Data',MaxIndex_j(iview,:));;
2526    TimeTable=get(handles.TimeTable,'Data');
2527    if size(TimeTable,1)<size(Param.InputTable,1)%if the time table is not complete, copy the missing lines from the previous ones
2528        for iline=size(TimeTable,1)+1:size(Param.InputTable,1)
2529            TimeTable(iline,:)=TimeTable(iline-1,:);
2530        end
2531    end
2532    set(handles.TimeTable,'Data',TimeTable(iview,:));% sort the time tables
2533    PairString=get(handles.PairString,'Data');
2534    set(handles.PairString,'Data',PairString(iview,:));
2535end
2536
2537%% Impose the whole input file index range if requested
2538if isfield(ParamOut,'WholeIndexRange')&&isequal(ParamOut.WholeIndexRange,'on')
2539    MinIndex_i=get(handles.MinIndex_i,'Data');
2540    MinIndex_j=get(handles.MinIndex_j,'Data');
2541    MaxIndex_i=get(handles.MaxIndex_i,'Data');
2542    MaxIndex_j=get(handles.MaxIndex_j,'Data');
2543    set(handles.num_first_i,'String',num2str(MinIndex_i(1)))% set first as the min index (for the first line)
2544    set(handles.num_last_i,'String',num2str(MaxIndex_i(1)))% set last as the max index (for the first line)
2545    set(handles.num_incr_i,'String','1')
2546    set(handles.num_first_j,'String',num2str(MinIndex_j(1)))% set first as the min index (for the first line)
2547    set(handles.num_last_j,'String',num2str(MaxIndex_j(1)))% set last as the max index (for the first line)
2548    set(handles.num_incr_j,'String','1')
2549else  % check index ranges
2550    first_i=1;last_i=1;first_j=1;last_j=1;
2551    if isfield(Param.IndexRange,'first_i')
2552        first_i=Param.IndexRange.first_i;
2553        last_i=Param.IndexRange.last_i;
2554    end
2555    if isfield(Param.IndexRange,'first_j')
2556        first_j=Param.IndexRange.first_j;
2557        last_j=Param.IndexRange.last_j;
2558    end
2559    if last_i < first_i || last_j < first_j , msgbox_uvmat('ERROR','last field number must be larger than the first one'),...
2560            set(handles.RUN, 'Enable','On'), set(handles.RUN,'BackgroundColor',[1 0 0]),return,end;
2561end
2562
2563%% enable or desable j index visibility
2564status_j='on'; % default
2565if isempty(find(~cellfun(@isempty,SeriesData.j1_series), 1)); % case of empty j indices
2566    status_j='off'; % no j index needed
2567elseif strcmp(get(handles.PairString,'Visible'),'on')
2568    check_burst=cellfun(@isempty,regexp(get(handles.PairString,'Data'),'^j')); % =0 for burst case, 1 otherwise
2569    if isempty(find(check_burst, 1))% if all pair string begins by j (burst)
2570        status_j='off'; % no j index needed for bust case
2571    end
2572end
2573enable_j(handles,status_j) % no j index needed
2574if isfield(ParamOut,'j_index_1')&& isfield(ParamOut,'j_index_2')%strcmp(ParamOut.Desable_j_index,'on')
2575    %status_j='off';
2576    set(handles.num_first_j,'String',num2str(ParamOut.j_index_1))
2577    set(handles.num_last_j,'String',num2str(ParamOut.j_index_2))
2578    set(handles.num_first_j,'enable','off')
2579    set(handles.num_last_j,'enable','off')
2580    set(handles.num_incr_j,'visible','off')
2581else
2582    set(handles.num_first_j,'enable','on')
2583    set(handles.num_last_j,'enable','on')
2584    set(handles.num_incr_j,'visible',status_j)
2585end
2586
2587%% NbSlice visibility
2588if isfield(ParamOut,'NbSlice') && (strcmp(ParamOut.NbSlice,'on')||isnumeric(ParamOut.NbSlice))
2589    set(handles.num_NbSlice,'Visible','on')
2590    set(handles.NbSlice_title,'Visible','on')
2591else
2592    set(handles.num_NbSlice,'Visible','off')
2593    set(handles.NbSlice_title,'Visible','off')
2594end
2595if isfield(ParamOut,'NbSlice') && isnumeric(ParamOut.NbSlice)
2596    set(handles.num_NbSlice,'String',num2str(ParamOut.NbSlice))
2597    set(handles.num_NbSlice,'Enable','off'); % NbSlice set by the activation of the Action function
2598else
2599    set(handles.num_NbSlice,'Enable','on'); % NbSlice can be modified on the GUI series
2600end
2601
2602%% Visibility of FieldTransform menu
2603FieldTransformVisible='off';  %hidden by default
2604if isfield(ParamOut,'FieldTransform')
2605    if ~strcmp(ParamOut.FieldTransform,'off')
2606    FieldTransformVisible='on'; 
2607    end
2608    if iscell(ParamOut.FieldTransform)
2609        SeriesData.TransformList=ParamOut.FieldTransform;
2610    end
2611    TransformName_Callback([],[], handles)
2612end
2613set(handles.FieldTransform,'Visible',FieldTransformVisible)
2614if isfield(ParamOut,'TransformPath');% record the path of transform function requested for compilation
2615    set(handles.TransformPath,'UserData',ParamOut.TransformPath)
2616else
2617    set(handles.TransformPath,'UserData',[])
2618end
2619
2620%% Visibility of projection object
2621ProjObjectVisible='off';  %hidden by default
2622if isfield(ParamOut,'ProjObject')
2623    ProjObjectVisible=ParamOut.ProjObject;
2624end
2625set(handles.CheckObject,'Visible',ProjObjectVisible)
2626if ~get(handles.CheckObject,'Value')
2627    ProjObjectVisible='off';
2628end
2629set(handles.ProjObject,'Visible',ProjObjectVisible)
2630set(handles.DeleteObject,'Visible',ProjObjectVisible)
2631set(handles.ViewObject,'Visible',ProjObjectVisible)
2632set(handles.EditObject,'Visible',ProjObjectVisible)
2633
2634%% Visibility of mask input
2635MaskVisible='off';  %hidden by default
2636if isfield(ParamOut,'Mask')
2637    MaskVisible=ParamOut.Mask;
2638end
2639set(handles.CheckMask,'Visible',MaskVisible);
2640%% Setting of expected iteration time
2641if isfield(ParamOut,'CPUTime')
2642    set(handles.num_CPUTime,'String',num2str(ParamOut.CPUTime));
2643end
2644
2645%% definition of the directory containing the output files
2646if  ~(isfield(SeriesData,'ActionName') && strcmp(ActionName,SeriesData.ActionName))
2647    OutputDirExt='.series'; % default
2648    if isfield(ParamOut,'OutputDirExt')&&~isempty(ParamOut.OutputDirExt)
2649        OutputDirExt=ParamOut.OutputDirExt;
2650    end
2651    set(handles.OutputDirExt,'String',OutputDirExt)
2652end
2653OutputDirVisible='off';
2654OutputSubDirMode='auto'; % default
2655SubDirOut='';
2656if isfield(ParamOut,'OutputSubDirMode')
2657    OutputSubDirMode=ParamOut.OutputSubDirMode;
2658end
2659InputTable=get(handles.InputTable,'Data');
2660switch OutputSubDirMode
2661    case 'auto'; % default
2662        OutputDirVisible='on';
2663        SubDir=InputTable(1:end,2); % set of subdirectories
2664        SubDirOut=SubDir{1};
2665        if numel(SubDir)>1
2666            for ilist=2:numel(SubDir)
2667                SubDirOut=[SubDirOut '-' regexprep(SubDir{ilist},'^/','')];
2668            end
2669        end
2670    case 'one'
2671        OutputDirVisible='on';
2672        SubDirOut=InputTable{1,2}; % use the first subdir name (+OutputDirExt) as output  subdirectory
2673    case 'two'
2674        OutputDirVisible='on';   
2675        SubDir=InputTable(1:2,2); % set of subdirectories
2676        SubDirOut=SubDir{1};
2677        if numel(SubDir)>1
2678                SubDirOut=[SubDirOut '-' regexprep(SubDir{2},'^/','')];
2679        end
2680    case 'last'
2681        OutputDirVisible='on';
2682        SubDirOut=InputTable{end,2}; % use the last subdir name (+OutputDirExt) as output  subdirectory
2683end
2684set(handles.OutputSubDir,'String',SubDirOut)
2685set(handles.OutputSubDir,'BackgroundColor',[1 1 1])% set edit box to white color to indicate refreshment
2686set(handles.OutputDirExt,'Visible',OutputDirVisible)
2687set(handles.OutputSubDir,'Visible',OutputDirVisible)
2688%set(handles.CheckOverwrite,'Visible',OutputDirVisible)
2689set(handles.OutputDir_title,'Visible',OutputDirVisible)
2690SeriesData.ActionName=ActionName; % record ActionName for next use
2691
2692
2693%% visibility of the run mode (local or background or cluster)
2694if strcmp(OutputSubDirMode,'none')
2695    RunModeVisible='off'; % only local mode available if no output file is produced
2696else
2697    RunModeVisible='on';
2698end
2699set(handles.RunMode,'Visible',RunModeVisible)
2700set(handles.ActionExt,'Visible',RunModeVisible)
2701set(handles.RunMode_title,'Visible',RunModeVisible)
2702set(handles.ActionExt_title,'Visible',RunModeVisible)
2703
2704
2705%% Expected nbre of output files
2706if isfield(ParamOut,'OutputFileMode')
2707    StatusData.OutputFileMode=ParamOut.OutputFileMode;
2708    set(handles.status,'UserData',StatusData)
2709end
2710
2711%% definition of an additional parameter set, determined by an ancillary GUI
2712if isfield(ParamOut,'ActionInput')
2713%     set(handles.ActionInput,'Visible','on')
2714    ParamOut.ActionInput.Program=ActionName; % record the program in ActionInput
2715    SeriesData.ActionInput=ParamOut.ActionInput;
2716else
2717%     set(handles.ActionInput,'Visible','off')
2718    if isfield(SeriesData,'ActionInput')
2719        SeriesData=rmfield(SeriesData,'ActionInput');
2720    end
2721end
2722set(handles.series,'UserData',SeriesData)
2723set(handles.ActionInput,'BackgroundColor',[1 0 0])
2724
2725%------------------------------------------------------------------------
2726% --- Executes on selection change in FieldName.
2727function FieldName_Callback(hObject, eventdata, handles)
2728%------------------------------------------------------------------------
2729field_str=get(handles.FieldName,'String');
2730field_index=get(handles.FieldName,'Value');
2731field=field_str{field_index(1)};
2732if isequal(field,'get_field...')
2733    SeriesData=get(handles.series,'UserData');
2734    % input line for which the field choice is relevant
2735    iview=find(ismember(SeriesData.FileType,{'netcdf','civx','civdata'})); % all nc files, icluding civ
2736    hget_field=findobj(allchild(0),'name','get_field');
2737    if ~isempty(hget_field)
2738        delete(hget_field)%delete opened versions of get_field
2739    end
2740    Param=read_GUI(handles.series);
2741    InputTable=Param.InputTable(iview,:);
2742    % check the existence of the first file in the series
2743    first_j=[];last_j=[];MinIndex_j=1;MaxIndex_j=1; % default setting for index j
2744    if isfield(Param.IndexRange,'first_j'); % if index j is used     
2745        first_j=Param.IndexRange.first_j;
2746        last_j=Param.IndexRange.last_j;
2747        MinIndex_j=Param.IndexRange.MinIndex_j(iview);
2748        MaxIndex_j=Param.IndexRange.MaxIndex_j(iview);
2749    end
2750    PairString='';
2751    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString{iview}; end
2752    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
2753    LineIndex=iview(1);
2754    if numel(iview)>1     
2755        answer=msgbox_uvmat('INPUT_TXT',['select the line of the input table:' num2str(iview)] ,num2str(iview(1)));
2756        LineIndex=str2num(answer);
2757%         InputLine=str2num(get(handles.InputLine,'String'));
2758%         if ismember(InputLine,iview)
2759%             LineIndex=InputLine;
2760%         end
2761    end
2762    FirstFileName=fullfile_uvmat(InputTable{LineIndex,1},InputTable{LineIndex,2},InputTable{LineIndex,3},...
2763        InputTable{LineIndex,5},InputTable{LineIndex,4},i1,i2,j1,j2);
2764    if exist(FirstFileName,'file')
2765        ParamIn.Title='get_field: pick input variables and coordinates for series processing';
2766        ParamIn.SeriesInput=1;
2767        GetFieldData=get_field(FirstFileName,ParamIn);
2768        FieldList={};
2769        if isfield(GetFieldData,'FieldOption')% if a field has been selected
2770        switch GetFieldData.FieldOption
2771            case 'vectors'
2772                UName=GetFieldData.PanelVectors.vector_x;
2773                VName=GetFieldData.PanelVectors.vector_y;
2774                YName={GetFieldData.Coordinates.Coord_y};
2775                FieldList={['vec(' UName ',' VName ')'];...
2776                    ['norm(' UName ',' VName ')'];...
2777                    UName;VName};
2778                set(handles.VelType,'Visible','off')
2779            case {'scalar'}
2780                FieldList=GetFieldData.PanelScalar.scalar;
2781                YName={GetFieldData.Coordinates.Coord_y};
2782                if ischar(FieldList)
2783                    FieldList={FieldList};
2784                end
2785                set(handles.VelType,'Visible','off')
2786            case 'civdata...'
2787                FieldList=[set_field_list('U','V') ;{'C'}];
2788                set(handles.FieldName,'Value',1) % set menu to 'velocity
2789                XName='X';
2790                YName='y';
2791                set(handles.VelType,'Visible','on')
2792        end
2793        set(handles.FieldName,'Value',1)
2794        set(handles.FieldName,'String',[FieldList; {'get_field...'}]);
2795        if ~strcmp(GetFieldData.FieldOption,'civdata...')
2796           if ~isempty(regexp(FieldList{1},'^vec'))
2797                set(handles.FieldName,'Value',1)
2798           else
2799                set(handles.FieldName,'Value',1:numel(FieldList))%select all input fields by default
2800           end
2801            XName=GetFieldData.Coordinates.Coord_x;
2802            YName=GetFieldData.Coordinates.Coord_y;
2803            TimeNameStr=GetFieldData.Time.SwitchVarIndexTime;
2804            % get the time info                     
2805            TimeTable=get(handles.TimeTable,'Data');
2806            switch TimeNameStr
2807                case 'file index'
2808                    TimeName='';
2809                case 'attribute'
2810                    TimeName=['att:' GetFieldData.Time.TimeName];
2811                    % update the time table
2812                    TimeTable{LineIndex,2}=get_time(Param.IndexRange.MinIndex_i(LineIndex),MinIndex_j,PairString,InputTable,SeriesData.FileInfo{LineIndex},GetFieldData.Time.TimeName);  % Min time     
2813                    TimeTable{LineIndex,3}=get_time(Param.IndexRange.first_i,first_j,PairString,InputTable,SeriesData.FileInfo{LineIndex},GetFieldData.Time.TimeName);  % first time             
2814                    TimeTable{LineIndex,4}=get_time(Param.IndexRange.last_i,last_j,PairString,InputTable,SeriesData.FileInfo{LineIndex},GetFieldData.Time.TimeName);  % last time                     
2815                    TimeTable{LineIndex,5}=get_time(Param.IndexRange.MaxIndex_i(LineIndex),MaxIndex_j,PairString,InputTable,SeriesData.FileInfo{LineIndex},GetFieldData.Time.TimeName);  % Max time
2816                case 'variable'
2817                    set(handles.TimeName,'String',['var:' GetFieldData.Time.TimeName])
2818                    set(handles.NomType,'String','*')
2819                    set(handles.RootFile,'String',[get(handles.RootFile,'String') get(handles.FileIndex,'String')])% A VERIFIER !!!!!!
2820                    set(handles.FileIndex,'String','')
2821                    ParamIn.TimeVarName=GetFieldData.Time.TimeName;
2822                case 'matrix_index'
2823                    TimeName=['dim:' GetFieldData.Time.TimeName];
2824                    set(handles.NomType,'String','*')
2825                    set(handles.RootFile,'String',[get(handles.RootFile,'String') get(handles.FileIndex,'String')])
2826                    set(handles.FileIndex,'String','')
2827                    ParamIn.TimeDimName=GetFieldData.Time.TimeName;
2828            end
2829            TimeTable{LineIndex,1}=TimeName;
2830            set(handles.TimeTable,'Data',TimeTable);
2831        end
2832        set(handles.Coord_x,'String',XName)
2833        set(handles.Coord_y,'String',YName)
2834        set(handles.Coord_x,'Visible','on')
2835        set(handles.Coord_y,'Visible','on')
2836        end
2837    else
2838        msgbox_uvmat('ERROR',[FirstFileName ' does not exist'])
2839    end
2840end
2841
2842
2843function [TimeValue,DtValue]=get_time(ref_i,ref_j,PairString,InputTable,FileInfo,TimeName,DtName)
2844[i1,i2,j1,j2] = get_file_index(ref_i,ref_j,PairString);
2845FileName=fullfile_uvmat(InputTable{1},InputTable{2},InputTable{3},InputTable{5},InputTable{4},i1,i2,j1,j2);
2846Data=nc2struct(FileName,[]);
2847TimeValue=[];
2848DtValue=[];
2849if isequal(FileInfo.FileType,'civdata')
2850    if ismember(TimeName,{'civ1','filter1'})
2851        if isfield(Data,'Civ1_Time')
2852        TimeValue=Data.Civ1_Time;
2853        end
2854        if isfield(Data,'Civ1_Dt')
2855        DtValue=Data.Civ1_Dt;
2856        end
2857    else
2858        if isfield(Data,'Civ2_Time')
2859        TimeValue=Data.Civ2_Time;
2860        end
2861        if isfield(Data,'Civ2_Dt')
2862        DtValue=Data.Civ2_Dt;
2863        end
2864    end
2865else
2866    if ~isempty(TimeName)&& isfield(Data,TimeName)
2867        TimeValue=Data.(TimeName);
2868    end
2869    if exist('DtName','var') && isfield(Data,DtName)
2870        DtValue=Data.(DtName);
2871    end
2872end
2873
2874%------------------------------------------------------------------------
2875% --- Executes on selection change in FieldName_1.
2876function FieldName_1_Callback(hObject, eventdata, handles)
2877%------------------------------------------------------------------------
2878field_str=get(handles.FieldName_1,'String');
2879field_index=get(handles.FieldName_1,'Value');
2880field=field_str{field_index(1)};
2881if isequal(field,'get_field...')
2882    hget_field=findobj(allchild(0),'name','get_field');
2883    if ~isempty(hget_field)
2884        delete(hget_field)%delete opened versions of get_field
2885    end
2886    Param=read_GUI(handles.series);
2887    Param.InputTable=Param.InputTable(1,:);
2888    % check the existence of the first file in the series
2889    first_j=[];
2890    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
2891    if isfield(Param.IndexRange,'last_j'); last_j=Param.IndexRange.last_j; end
2892    PairString='';
2893    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
2894    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
2895    FirstFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
2896        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
2897    if exist(FirstFileName,'file')
2898        ParamIn.SeriesInput=1;
2899        GetFieldData=get_field(FirstFileName,ParamIn);
2900        FieldList={};
2901        switch GetFieldData.FieldOption
2902            case 'vectors'
2903                UName=GetFieldData.PanelVectors.vector_x;
2904                VName=GetFieldData.PanelVectors.vector_y;
2905                FieldList={['vec(' UName ',' VName ')'];...
2906                    ['norm(' UName ',' VName ')'];...
2907                    UName;VName};
2908            case {'scalar','pick variables'}
2909                FieldList=GetFieldData.PanelScalar.scalar;
2910                if ischar(FieldList)
2911                    FieldList={FieldList};
2912                end
2913            case '1D plot'
2914
2915            case 'civdata...'
2916                FieldList=set_field_list('U','V','C');
2917                set(handles.FieldName,'Value',2) % set menu to 'velocity
2918        end
2919        if ~strcmp(GetFieldData.FieldOption,'civdata...')
2920            TimeNameStr=GetFieldData.Time.SwitchVarIndexTime;
2921            switch TimeNameStr
2922                case 'file index'
2923                    set(handles.TimeName,'String','');
2924                case 'attribute'
2925                    set(handles.TimeName,'String',['att:' GetFieldData.Time.TimeName]);
2926                case 'variable'
2927                    set(handles.TimeName,'String',['var:' GetFieldData.Time.TimeName])
2928                    set(handles.NomType,'String','*')
2929                    set(handles.RootFile,'String',[get(handles.RootFile,'String') get(handles.FileIndex,'String')])% A VERIFIER !!!!!!
2930                    set(handles.FileIndex,'String','')
2931                    ParamIn.TimeVarName=GetFieldData.Time.TimeName;
2932                case 'matrix_index'
2933                    set(handles.TimeName,'String',['dim:' GetFieldData.Time.TimeName]);
2934                    set(handles.NomType,'String','*')
2935                    set(handles.RootFile,'String',[get(handles.RootFile,'String') get(handles.FileIndex,'String')])
2936                    set(handles.FileIndex,'String','')
2937                    ParamIn.TimeDimName=GetFieldData.Time.TimeName;
2938            end
2939        end
2940        set(handles.FieldName_1,'Value',1)
2941        set(handles.FieldName_1,'String',[FieldList; {'get_field...'}]);
2942    end
2943end   
2944
2945
2946%%%%%%%%%%%%%
2947function [ind_remove]=find_pairs(dirpair,ind_i,last_i)
2948indsel=ind_i;
2949indiff=diff(ind_i); % test index increment to detect multiplets (several pairs with the same index ind_i) and holes in the series
2950indiff=[1 indiff last_i-ind_i(end)+1]; % for testing gaps with the imposed bounds
2951if ~isempty(indiff)
2952    indiff2=diff(indiff);
2953    indiffp=[indiff2 1];
2954    indiffm=[1 indiff2];
2955    ind_multi_m=find((indiff==0)&(indiffm<0))-1; % indices of first members of multiplets
2956    ind_multi_p=find((indiff==0)&(indiffp>0)); % indices of last members of multiplets
2957    %for each multiplet, select the most recent file
2958    ind_remove=[];
2959    for i=1:length(ind_multi_m)
2960        ind_pairs=ind_multi_m(i):ind_multi_p(i);
2961        for imulti=1:length(ind_pairs)
2962            datepair(imulti)=datenum(dirpair(ind_pairs(imulti)).date); % dates of creation
2963        end
2964        [datenew,indsort2]=sort(datepair); % sort the multiplet by creation date
2965        ind_s=indsort2(1:end-1); %
2966        ind_remove=[ind_remove ind_pairs(ind_s)]; % remove these indices, leave the last one
2967    end
2968end
2969
2970%------------------------------------------------------------------------
2971% --- determine the list of index pairstring of processing file
2972function [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)
2973%------------------------------------------------------------------------
2974num_i1=num_i; % set of first image numbers by default
2975num_i2=num_i;
2976num_j1=num_j;
2977num_j2=num_j;
2978num_i_out=num_i;
2979num_j_out=num_j;
2980% if isequal (NomType,'_1-2_1') || isequal (NomType,'_1-2')
2981if isequal(mode,'series(Di)')
2982    num_i1_line=num_i+ind_shift(3); % set of first image numbers
2983    num_i2_line=num_i+ind_shift(4);
2984    % adjust the first and last field number
2985        indsel=find(num_i1_line >= 1);
2986    num_i_out=num_i(indsel);
2987    num_i1_line=num_i1_line(indsel);
2988    num_i2_line=num_i2_line(indsel);
2989    num_j1=meshgrid(num_j,ones(size(num_i1_line)));
2990    num_j2=meshgrid(num_j,ones(size(num_i1_line)));
2991    [xx,num_i1]=meshgrid(num_j,num_i1_line);
2992    [xx,num_i2]=meshgrid(num_j,num_i2_line);
2993elseif isequal (mode,'series(Dj)')||isequal (mode,'bursts')
2994    if isequal(mode,'bursts') %case of bursts (png_old or png_2D)
2995        num_j1=ind_shift(1)*ones(size(num_i));
2996        num_j2=ind_shift(2)*ones(size(num_i));
2997    else
2998        num_j1_col=num_j+ind_shift(1); % set of first image numbers
2999        num_j2_col=num_j+ind_shift(2);
3000        % adjust the first field number
3001        indsel=find((num_j1_col >= 1));   
3002        num_j_out=num_j(indsel);
3003        num_j1_col=num_j1_col(indsel);
3004        num_j2_col=num_j2_col(indsel);
3005        [num_i1,num_j1]=meshgrid(num_i,num_j1_col);
3006        [num_i2,num_j2]=meshgrid(num_i,num_j2_col);
3007    end   
3008end
3009
3010%------------------------------------------------------------------------
3011% --- Executes on button press in CheckObject.
3012function CheckObject_Callback(hObject, eventdata, handles)
3013%------------------------------------------------------------------------
3014hset_object=findobj(allchild(0),'tag','set_object'); % find the set_object interface handle
3015if get(handles.CheckObject,'Value')
3016    SeriesData=get(handles.series,'UserData');
3017    if isfield(SeriesData,'ProjObject') && ~isempty(SeriesData.ProjObject)
3018        set(handles.ViewObject,'Value',1)
3019        ViewObject_Callback(hObject, eventdata, handles)
3020    else
3021        if ishandle(hset_object)
3022            uistack(hset_object,'top')% show the GUI set_object if opened
3023        else
3024            %get the object file
3025            InputTable=get(handles.InputTable,'Data');
3026            defaultname=InputTable{1,1};
3027            if isempty(defaultname)
3028                defaultname={''};
3029            end
3030            fileinput=uigetfile_uvmat('pick a xml object file (or use uvmat to create it)',defaultname,'.xml');
3031            if isempty(fileinput)% exit if no object file is selected
3032                set(handles.CheckObject,'Value',0)
3033                return
3034            end
3035            %read the file
3036            data=xml2struct(fileinput);
3037            if ~isfield(data,'Type')
3038                msgbox_uvmat('ERROR',[fileinput ' is not an object xml file'])
3039                set(handles.CheckObject,'Value',0)
3040                return
3041            end
3042            if ~isfield(data,'ProjMode')
3043                data.ProjMode='none';
3044            end
3045            hset_object=set_object(data); % call the set_object interface
3046            set(hset_object,'Name','set_object_series')% name to distinguish from set_object used with uvmat
3047        end
3048        ProjObject=read_GUI(hset_object);
3049        set(handles.ProjObject,'String',ProjObject.Name); % display the object name
3050        SeriesData=get(handles.series,'UserData');
3051        SeriesData.ProjObject=ProjObject;
3052        set(handles.series,'UserData',SeriesData);
3053    end
3054    set(handles.EditObject,'Visible','on');
3055    set(handles.DeleteObject,'Visible','on');
3056    set(handles.ViewObject,'Visible','on');
3057    set(handles.ProjObject,'Visible','on');
3058else
3059    set(handles.EditObject,'Visible','off');
3060    set(handles.DeleteObject,'Visible','off');
3061    set(handles.ViewObject,'Visible','off');
3062    if ~ishandle(hset_object)
3063        set(handles.ViewObject,'Value',0);
3064    end
3065    set(handles.ProjObject,'Visible','off');
3066end
3067
3068%------------------------------------------------------------------------
3069% --- Executes on button press in ViewObject.
3070%------------------------------------------------------------------------
3071function ViewObject_Callback(hObject, eventdata, handles)
3072
3073UserData=get(handles.series,'UserData');
3074hset_object=findobj(allchild(0),'Tag','set_object');
3075if ~isempty(hset_object)
3076    delete(hset_object)% refresh set_object if already opened
3077end
3078hset_object=set_object(UserData.ProjObject);
3079set(hset_object,'Name','view_object_series')
3080
3081
3082%------------------------------------------------------------------------
3083% --- Executes on button press in EditObject.
3084function EditObject_Callback(hObject, eventdata, handles)
3085%------------------------------------------------------------------------
3086if get(handles.EditObject,'Value')
3087    set(handles.ViewObject,'Value',0)
3088    UserData=get(handles.series,'UserData');
3089    hset_object=set_object(UserData.ProjObject);
3090    set(hset_object,'Name','edit_object_series')
3091    set(get(hset_object,'Children'),'Enable','on')
3092else
3093    hset_object=findobj(allchild(0),'Tag','set_object');
3094    if ~isempty(hset_object)
3095        set(get(hset_object,'Children'),'Enable','off')
3096    end
3097end
3098
3099%------------------------------------------------------------------------
3100% --- Executes on button press in DeleteObject.
3101function DeleteObject_Callback(hObject, eventdata, handles)
3102%------------------------------------------------------------------------
3103SeriesData=get(handles.series,'UserData');
3104SeriesData.ProjObject=[];
3105set(handles.series,'UserData',SeriesData)
3106set(handles.ProjObject,'String','')
3107set(handles.ProjObject,'Visible','off')
3108set(handles.CheckObject,'Value',0)
3109set(handles.ViewObject,'Visible','off')
3110set(handles.EditObject,'Visible','off')
3111hset_object=findobj(allchild(0),'name','set_object_series');
3112if ~isempty(hset_object)
3113    delete(hset_object)
3114end
3115set(handles.DeleteObject,'Visible','off')
3116
3117%------------------------------------------------------------------------
3118% --- Executed when CheckMask is activated
3119%------------------------------------------------------------------------
3120function CheckMask_Callback(hObject, eventdata, handles)
3121
3122if get(handles.CheckMask,'Value')
3123    InputTable=get(handles.InputTable,'Data');
3124    nbview=size(InputTable,1);
3125    MaskTable=cell(nbview,1); % default
3126    ListMask=cell(nbview,1); % default
3127    MaskData=get(handles.MaskTable,'Data');
3128    MaskData(size(MaskData,1):nbview,1)=cell(size(MaskData,1):nbview,1); % complement if undefined lines
3129    for iview=1:nbview
3130        ListMask{iview,1}=num2str(iview);
3131        RootPath=InputTable{iview,1};
3132        if ~isempty(RootPath)
3133            if isempty(MaskData{iview})
3134                SubDir=InputTable{iview,2};
3135                MaskPath=fullfile(RootPath,[regexprep(SubDir,'\..*','') '.mask']); % take the root part of SubDir, before the first dot '.'
3136                if exist(MaskPath,'dir')
3137                    ListStruct=dir(MaskPath); % look for a mask file
3138                    ListCells=struct2cell(ListStruct); % transform dir struct to a cell arrray
3139                    check_dir=cell2mat(ListCells(4,:)); % =1 for directories, =0 for files
3140                    ListFiles=ListCells(1,:); % list of file and dri names
3141                    ListFiles=ListFiles(~check_dir); % list of file names (excluding dir)
3142                    mdetect=0;
3143                    if ~isempty(ListFiles)
3144                        for ifile=1:numel(ListFiles)
3145                            [tild,tild,MaskFile{ifile},i1_series,i2_series,j1_series,j2_series,MaskNomType,MaskFileType]=find_file_series(MaskPath,ListFiles{ifile},0);
3146                            if strcmp(MaskFileType,'image') && isempty(i2_series) && isempty(j2_series)
3147                                mdetect=1;
3148                                MaskName=ListFiles{ifile};
3149                            end
3150                            if ~strcmp(MaskFile{ifile},MaskFile{1})
3151                                mdetect=0; % cancel detection test in case of multiple masks, use the brower for selection
3152                                break
3153                            end
3154                        end
3155                    end
3156                    if mdetect==1
3157                        MaskName=fullfile(MaskPath,'mask_1.png');
3158                    else
3159                        MaskName=uigetfile_uvmat('select a mask file:',MaskPath,'image');
3160                    end
3161                else
3162                    MaskName=uigetfile_uvmat('select a mask file:',RootPath,'image');
3163                end
3164                MaskTable{iview,1}=MaskName ;
3165                ListMask{iview,1}=num2str(iview);
3166            end
3167        end
3168    end
3169    set(handles.MaskTable,'Data',MaskTable)
3170    set(handles.MaskTable,'Visible','on')
3171    set(handles.MaskBrowse,'Visible','on')
3172    set(handles.ListMask,'Visible','on')
3173    set(handles.ListMask,'String',ListMask)
3174    set(handles.ListMask,'Value',1)
3175else
3176    set(handles.MaskTable,'Visible','off')
3177    set(handles.MaskBrowse,'Visible','off')
3178    set(handles.ListMask,'Visible','off')
3179end
3180
3181%------------------------------------------------------------------------
3182% --- Executes on button press in MaskBrowse.
3183%------------------------------------------------------------------------
3184function MaskBrowse_Callback(hObject, eventdata, handles)
3185
3186InputTable=get(handles.InputTable,'Data');
3187iview=get(handles.ListMask,'Value');
3188RootPath=InputTable{iview,1};
3189MaskName=uigetfile_uvmat('select a mask file:',RootPath,'image');
3190if ~isempty(MaskName)
3191    MaskTable=get(handles.MaskTable,'Data');
3192    MaskTable{iview,1}=MaskName ;
3193    set(handles.MaskTable,'Data',MaskTable)
3194end
3195
3196%------------------------------------------------------------------------
3197% --- Executes when selected cell(s) is changed in MaskTable.
3198%------------------------------------------------------------------------
3199function MaskTable_CellSelectionCallback(hObject, eventdata, handles)
3200
3201if numel(eventdata.Indices)>=1
3202set(handles.ListMask,'Value',eventdata.Indices(1))
3203end
3204
3205%-------------------------------------------------------------------
3206function MenuHelp_Callback(hObject, eventdata, handles)
3207%-------------------------------------------------------------------
3208
3209
3210% path_to_uvmat=which ('uvmat'); % check the path of uvmat
3211% pathelp=fileparts(path_to_uvmat);
3212% helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
3213% 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')
3214% else
3215%     addpath (fullfile(pathelp,'uvmat_doc'))
3216%     web([helpfile '#series'])
3217% end
3218
3219%-------------------------------------------------------------------
3220% --- Executes on selection change in TransformName.
3221function TransformName_Callback(hObject, eventdata, handles)
3222%----------------------------------------------------------------------
3223TransformList=get(handles.TransformName,'String');
3224TransformIndex=get(handles.TransformName,'Value');
3225TransformName=TransformList{TransformIndex};
3226TransformPathList=get(handles.TransformName,'UserData');
3227nb_builtin_transform=4;
3228if isequal(TransformName,'more...');     
3229    FileName=uigetfile_uvmat('Pick a transform function',get(handles.TransformPath,'String'),'.m');
3230    if isempty(FileName)
3231        return     %browser closed without choice
3232    end
3233    [TransformPath,TransformName,TransformExt]=fileparts(FileName); % removes extension .m
3234    if ~strcmp(TransformExt,'.m')
3235        msgbox_uvmat('ERROR','a Matlab function .m must be introduced');
3236        return
3237    end
3238     % insert the choice in the menu
3239    TransformIndex=find(strcmp(TransformName,TransformList),1); % look for the selected function in the menu Action
3240    if isempty(TransformIndex)%the input string does not exist in the menu
3241        TransformIndex= length(TransformList);
3242        TransformList=[TransformList(1:end-1);{TransformName};TransformList(end)]; % the selected function is appended in the menu, before the last item 'more...'
3243        set(handles.TransformName,'String',TransformList)
3244        TransformPathList=[TransformPathList;{TransformPath}];
3245    else% the input function already exist, we update its path (possibly new)
3246        TransformPathList{TransformIndex}=TransformPath; %
3247        set(handles.TransformName,'Value',TransformIndex)
3248    end
3249   % save the new menu in the personal file 'uvmat_perso.mat'
3250   dir_perso=prefdir; % personal Matalb directory
3251   profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
3252   if exist(profil_perso,'file')
3253       for ilist=nb_builtin_transform+1:numel(TransformPathList)
3254           TransformListUser{ilist-nb_builtin_transform}=TransformList{ilist};
3255           TransformPathListUser{ilist-nb_builtin_transform}=TransformPathList{ilist};
3256       end
3257       TransformPathListUser=TransformPathListUser';
3258       TransformListUser=TransformListUser';
3259       save (profil_perso,'TransformPathListUser','TransformListUser','-append'); % store the root name for future opening of uvmat
3260   end
3261end
3262
3263%display the current function path
3264set(handles.TransformPath,'String',TransformPathList{TransformIndex}); % show the path to the senlected function
3265set(handles.TransformName,'UserData',TransformPathList);
3266
3267%% create the function handle of the selected fct
3268if ~isempty(TransformName)
3269    if ~exist(TransformPathList{TransformIndex},'dir')
3270        msgbox_uvmat('ERROR',['The prescribed transform function path ' TransformPathList{TransformIndex} ' does not exist']);
3271        return
3272    end
3273    current_dir=pwd; % current working dir
3274    cd(TransformPathList{TransformIndex})
3275    transform_handle=str2func(TransformName);
3276    cd(current_dir)
3277    Field.Action.RUN=0;% indicate that the transform fct is called only to get input param
3278    SeriesData=get(handles.series,'UserData');
3279    ParamIn=[];
3280    if isfield(SeriesData,'TransformInput')
3281        ParamIn.TransformInput=SeriesData.TransformInput;
3282    end
3283    DataOut=feval(transform_handle,Field,ParamIn);% execute the transform fct to get the required conditions
3284    Field.Action.RUN=0; % indicate that the transform fct is called only to get input param
3285    DataOut=feval(transform_handle,Field,[]); % execute the transform fct to get the required conditions
3286    if isfield(DataOut,'TransformInput')%  used to add transform parameters at selection of the transform fct
3287        SeriesData.TransformInput=DataOut.TransformInput;
3288        set(handles.series,'UserData',SeriesData)
3289    end
3290end
3291
3292%------------------------------------------------------------------------
3293% --- fct activated by the upper bar menu ExportConfig
3294%------------------------------------------------------------------------
3295function MenuDisplayConfig_Callback(hObject, eventdata, handles)
3296
3297global Param
3298Param=read_GUI_series(handles);
3299evalin('base','global Param')%make CurData global in the workspace
3300display('current series config :')
3301evalin('base','Param') %display CurData in the workspace
3302commandwindow; % brings the Matlab command window to the front
3303
3304%------------------------------------------------------------------------
3305% --- fct activated by the upper bar menu InportConfig: import
3306%     menu settings from an xml file (stored in /0_XML for each run)
3307%------------------------------------------------------------------------
3308function MenuImportConfig_Callback(hObject, eventdata, handles)
3309
3310%% use a browser to choose the xml file containing the processing config
3311InputTable=get(handles.InputTable,'Data');
3312oldfile=InputTable{1,1}; % current path in InputTable
3313if isempty(oldfile)
3314    % use a file name stored in prefdir
3315    dir_perso=prefdir;
3316    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
3317    if exist(profil_perso,'file')
3318        h=load (profil_perso);
3319        if isfield(h,'RootPath') && ischar(h.RootPath)
3320            oldfile=h.RootPath;
3321        end
3322    end
3323end
3324filexml=uigetfile_uvmat('pick a xml parameter file',oldfile,'.xml'); % get the xml file containing processing parameters
3325if isempty(filexml), return, end % quit function if an xml file has not been opened
3326
3327%% fill the GUI series with the content of the xml file
3328Param=xml2struct(filexml); % read the input xml file as a Matlab structure
3329
3330% ask to stop current Action if button RUN is in action (another process is already running)
3331if isequal(get(handles.RUN,'Value'),1)
3332    answer= msgbox_uvmat('INPUT_Y-N','stop current Action process?');
3333    if strcmp(answer,'Yes')
3334        STOP_Callback(hObject, eventdata, handles)
3335    else
3336        return
3337    end
3338end
3339Param.Action.RUN=0; % desactivate the input RUN=1
3340
3341fill_GUI(Param,handles.series)% fill the elements of the GUI series with the input parameters
3342SeriesData=get(handles.series,'UserData');
3343if isfield(Param,'InputFields')
3344    ListField=Param.InputFields.FieldName;
3345    if ischar(ListField),ListField={ListField}; end
3346    set(handles.FieldName,'String',[ListField;{'get-field...'}])
3347     set(handles.FieldName,'Value',1:numel(ListField))
3348     set(handles.FieldName,'Visible','on')
3349end       
3350if isfield(Param,'ActionInput')%  introduce  parameters specific to an Action fct, for instance PIV parameters
3351%     set(handles.ActionInput,'Visible','on')
3352%     set(handles.ActionInput,'Value',0)
3353    Param.ActionInput.ConfigSource=filexml; % record the source of config for future info
3354    SeriesData.ActionInput=Param.ActionInput;
3355end
3356if isfield(Param,'TransformInput')%  introduce  parameters specific to a transform fct
3357    SeriesData.TransformInput=Param.TransformInput;
3358end
3359if isfield(Param,'ProjObject') %introduce projection object if relevant
3360    SeriesData.ProjObject=Param.ProjObject;
3361end
3362set(handles.series,'UserData',SeriesData)
3363if isfield(Param,'CheckObject') && isequal(Param.CheckObject,1)
3364    set(handles.ProjObject,'String',Param.ProjObject.Name)
3365    set(handles.ViewObject,'Visible','on')
3366    set(handles.EditObject,'Visible','on')
3367    set(handles.DeleteObject,'Visible','on')
3368else     
3369    set(handles.ProjObject,'String','')
3370    set(handles.ProjObject,'Visible','off')
3371    set(handles.ViewObject,'Visible','off')
3372    set(handles.EditObject,'Visible','off')
3373    set(handles.DeleteObject,'Visible','off')     
3374end     
3375set(handles.REFRESH,'BackgroundColor',[1 0 1]); % paint REFRESH button in magenta to indicate that it should be activated
3376
3377
3378%------------------------------------------------------------------------
3379% --- Executes when the GUI series is resized.
3380%------------------------------------------------------------------------
3381function series_ResizeFcn(hObject, eventdata, handles)
3382
3383%% input table
3384set(handles.InputTable,'Unit','pixel')
3385Pos=get(handles.InputTable,'Position');
3386set(handles.InputTable,'Unit','normalized')
3387ColumnWidth=round([0.5 0.14 0.14 0.14 0.08]*(Pos(3)-52));
3388ColumnWidth=num2cell(ColumnWidth);
3389set(handles.InputTable,'ColumnWidth',ColumnWidth)
3390
3391%% MinIndex_j and MaxIndex_i
3392unit=get(handles.MinIndex_i,'Unit');
3393set(handles.MinIndex_i,'Unit','pixel')
3394Pos=get(handles.MinIndex_i,'Position');
3395set(handles.MinIndex_i,'Unit',unit)
3396set(handles.MinIndex_i,'ColumnWidth',{Pos(3)-18})
3397set(handles.MaxIndex_i,'ColumnWidth',{Pos(3)-18})
3398set(handles.MinIndex_j,'ColumnWidth',{Pos(3)-18})
3399set(handles.MaxIndex_j,'ColumnWidth',{Pos(3)-18})
3400
3401%% TimeTable
3402set(handles.TimeTable,'Unit','pixel')
3403Pos=get(handles.TimeTable,'Position');
3404set(handles.TimeTable,'Unit','normalized')
3405% ColumnWidth=get(handles.TimeTable,'ColumnWidth');
3406ColumnWidth=num2cell(floor([0.2 0.2 0.2 0.2 0.2]*(Pos(3)-20)));
3407set(handles.TimeTable,'ColumnWidth',ColumnWidth)
3408
3409
3410%% PairString
3411set(handles.PairString,'Unit','pixel')
3412Pos=get(handles.PairString,'Position');
3413set(handles.PairString,'Unit','normalized')
3414set(handles.PairString,'ColumnWidth',{Pos(3)-5})
3415
3416%% MaskTable
3417set(handles.MaskTable,'Unit','pixel')
3418Pos=get(handles.MaskTable,'Position');
3419set(handles.MaskTable,'Unit','normalized')
3420set(handles.MaskTable,'ColumnWidth',{Pos(3)-5})
3421
3422%------------------------------------------------------------------------
3423% --- Executes on button press in status.
3424%------------------------------------------------------------------------
3425function status_Callback(hObject, eventdata, handles)
3426
3427if get(handles.status,'Value')
3428    set(handles.status,'BackgroundColor',[1 1 0])
3429    drawnow
3430    Param=read_GUI(handles.series);
3431    RootPath=Param.InputTable{1,1};
3432    if ~isfield(Param,'OutputSubDir')   
3433        msgbox_uvmat('ERROR','no standard sub-directory definition for output files, use a browser to check the output')
3434        set(handles.status,'BackgroundColor',[0 1 0])
3435        return
3436    end
3437    OutputSubDir=[Param.OutputSubDir Param.OutputDirExt]; % subdirectory for output files
3438    OutputDir=fullfile(RootPath,OutputSubDir);
3439    if exist(OutputDir,'dir')
3440        uigetfile_uvmat('status_display',OutputDir)
3441    else
3442        msgbox_uvmat('ERROR','output folder not created yet: calculation did not start')
3443        set(handles.status,'BackgroundColor',[0 1 0])
3444    end
3445else
3446    %% delete current display fig if selection is off
3447    set(handles.status,'BackgroundColor',[0 1 0])
3448    hfig=findobj(allchild(0),'name','status_display');
3449    if ~isempty(hfig)
3450        delete(hfig)
3451    end
3452    return
3453end
3454
3455
3456%------------------------------------------------------------------------   
3457% launched by selecting a file on the list
3458%------------------------------------------------------------------------
3459function view_file(hObject, eventdata)
3460
3461list=get(hObject,'String');
3462index=get(hObject,'Value');
3463rootroot=get(hObject,'UserData');
3464selectname=list{index};
3465ind_dot=regexp(selectname,'\.\.\.');
3466if ~isempty(ind_dot)
3467    selectname=selectname(1:ind_dot-1);
3468end
3469FullSelectName=fullfile(rootroot,selectname);
3470if exist(FullSelectName,'dir')% a directory has been selected
3471    ListFiles=dir(FullSelectName);
3472    ListDisplay=cell(numel(ListFiles),1);
3473    for ilist=2:numel(ListDisplay)% suppress the first line '.'
3474        ListDisplay{ilist-1}=ListFiles(ilist).name;
3475    end
3476    set(hObject,'Value',1)
3477    set(hObject,'String',ListDisplay)
3478    if strcmp(selectname,'..')
3479        FullSelectName=fileparts(fileparts(FullSelectName));
3480    end
3481    set(hObject,'UserData',FullSelectName)
3482    hfig=get(hObject,'parent');
3483    htitlebox=findobj(hfig,'tag','titlebox');   
3484    set(htitlebox,'String',FullSelectName)
3485elseif exist(FullSelectName,'file')%visualise the vel field if it exists
3486    FileInfo=get_file_info(FullSelectName);   
3487    if strcmp(FileInfo.FileType,'txt')
3488        edit(FullSelectName)
3489    elseif strcmp(FileInfo.FileType,'xml')
3490        editxml(FullSelectName)
3491    else
3492        uvmat(FullSelectName)
3493    end
3494    set(gcbo,'Value',1)
3495end
3496
3497
3498%------------------------------------------------------------------------   
3499% launched by refreshing the status figure
3500%------------------------------------------------------------------------
3501function refresh_GUI(hfig)
3502
3503htitlebox=findobj(hfig,'tag','titlebox');
3504hlist=findobj(hfig,'tag','list');
3505hseries=findobj(allchild(0),'tag','series');
3506hstatus=findobj(hseries,'tag','status');
3507StatusData=get(hstatus,'UserData');
3508OutputDir=get(htitlebox,'String');
3509if ischar(OutputDir),OutputDir={OutputDir};end
3510ListFiles=dir(OutputDir{1});
3511if numel(ListFiles)<1
3512    return
3513end
3514ListFiles(1)=[]; % removes the first line ='.'
3515ListDisplay=cell(numel(ListFiles),1);
3516testrecent=0;
3517datnum=zeros(numel(ListDisplay),1);
3518for ilist=1:numel(ListDisplay)
3519    ListDisplay{ilist}=ListFiles(ilist).name;
3520      if ~ListFiles(ilist).isdir && isfield(ListFiles(ilist),'datenum')
3521            datnum(ilist)=ListFiles(ilist).datenum; % only available in recent matlab versions
3522            testrecent=1;
3523       end
3524end
3525set(hlist,'String',ListDisplay)
3526
3527%% Look at date of creation
3528ListDisplay=ListDisplay(datnum~=0);
3529datnum=datnum(datnum~=0); % keep the non zero values corresponding to existing files
3530NbOutputFile=[];
3531if isempty(datnum)
3532    if testrecent
3533        message='no civ result created yet';
3534    else
3535        message='';
3536    end
3537else
3538    [first,indfirst]=min(datnum);
3539    [last,indlast]=max(datnum);
3540    NbOutputFile_str='?';
3541    NbOutputFile=[];
3542    if isfield(StatusData,'NbOutputFile')
3543        NbOutputFile=StatusData.NbOutputFile;
3544        NbOutputFile_str=num2str(NbOutputFile);
3545    end
3546    message={[num2str(numel(datnum)) ' file(s) done over ' NbOutputFile_str] ;['oldest modification:  ' ListDisplay{indfirst} ' : ' datestr(first)];...
3547        ['latest modification:  ' ListDisplay{indlast} ' : ' datestr(last)]};
3548end
3549set(htitlebox,'String', [OutputDir{1};message])
3550
3551%% update the waitbar
3552hwaitbar=findobj(hfig,'tag','waitbar');
3553if ~isempty(NbOutputFile)
3554    BarPosition=get(hwaitbar,'Position');
3555    BarPosition(3)=0.9*numel(datnum)/NbOutputFile;
3556    set(hwaitbar,'Position',BarPosition)
3557end
3558
3559%------------------------------------------------------------------------
3560% --- Executes on selection change in ActionExt.
3561%------------------------------------------------------------------------
3562function ActionExt_Callback(hObject, eventdata, handles)
3563
3564ActionExtList=get(handles.ActionExt,'String');
3565ActionExt=ActionExtList{get(handles.ActionExt,'Value')};
3566if strcmp(ActionExt,'.py (in dev.)')
3567    set(handles.RunMode,'Value',2)
3568end
3569
3570
3571function num_NbSlice_Callback(hObject, eventdata, handles)
3572NbSlice=str2num(get(handles.num_NbSlice,'String'));
3573
3574%------------------------------------------------------------------------
3575% --- set the visibility of relevant velocity type menus:
3576function menu=set_veltype_display(Civ,FileType)
3577%------------------------------------------------------------------------
3578if ~exist('FileType','var')
3579    FileType='civx';
3580end
3581switch FileType
3582    case 'civx'
3583        menu={'civ1';'interp1';'filter1';'civ2';'interp2';'filter2'};
3584        if isequal(Civ,0)
3585            imax=0;
3586        elseif isequal(Civ,1) || isequal(Civ,2)
3587            imax=1;
3588        elseif isequal(Civ,3)
3589            imax=3;
3590        elseif isequal(Civ,4) || isequal(Civ,5)
3591            imax=4;
3592        elseif isequal(Civ,6) %patch2
3593            imax=6;
3594        end
3595    case 'civdata'
3596        menu={'civ1';'filter1';'civ2';'filter2'};
3597        if isequal(Civ,0)
3598            imax=0;
3599        elseif isequal(Civ,1) || isequal(Civ,2)
3600            imax=1;
3601        elseif isequal(Civ,3)
3602            imax=2;
3603        elseif isequal(Civ,4) || isequal(Civ,5)
3604            imax=3;
3605        else%if isequal(Civ,6) %patch2
3606            imax=4;
3607        end
3608end
3609menu=menu(1:imax);
3610
3611
3612% --- Executes on mouse motion over figure - except title and menu.
3613% function series_WindowButtonMotionFcn(hObject, eventdata, handles)
3614% set(hObject,'Pointer','arrow');
3615
3616
3617% --- Executes on button press in SetPairs.
3618function SetPairs_Callback(hObject, eventdata, handles)
3619
3620%% delete previous occurrence of 'set_pairs'
3621hfig=findobj(allchild(0),'Tag','set_pairs');
3622if ~isempty(hfig)
3623delete(hfig)
3624end
3625
3626%% create the GUI set_pairs
3627set(0,'Unit','points')
3628ScreenSize=get(0,'ScreenSize'); % get the size of the screen, to put the fig on the upper right
3629Width=220; % fig width in points (1/72 inch)
3630Height=min(0.8*ScreenSize(4),300);
3631Left=ScreenSize(3)- Width-40; % right edge close to the right, with margin=40
3632Bottom=ScreenSize(4)-Height-40; % put fig at top right
3633hfig=findobj(allchild(0),'Tag','set_slice');
3634if ~isempty(hfig),delete(hfig), end; % delete existing version of the GUI
3635hfig=figure('name','set_pairs','tag','set_pairs','MenuBar','none','NumberTitle','off','Unit','points','Position',[Left,Bottom,Width,Height]);
3636BackgroundColor=get(hfig,'Color');
3637SeriesData=get(handles.series,'UserData');
3638TimeUnit=get(handles.TimeUnit,'String');
3639PairString=get(handles.PairString,'Data');
3640ListViewLines=find(cellfun('isempty',PairString)==0); % find list of non empty pairs
3641ListViewMenu=cell(numel(ListViewLines),1);
3642%iview=get(handles.PairString,'Value');
3643iview=[];
3644for ilist=1:numel(ListViewLines)
3645    ListViewMenu{ilist}=num2str(ListViewLines(ilist));
3646end
3647if isempty(iview)
3648    ListViewValue=numel(ListViewLines); % we work by default on the pair option for the last line which requires pairs
3649    iview=ListViewLines(end);
3650else
3651    ListViewValue=find(ListViewLines==iview);
3652end
3653ref_i=str2num(get(handles.num_first_i,'String'));
3654ref_j=1; % default
3655if strcmp(get(handles.num_first_j,'String'),'Visible')
3656    ref_j=str2num(get(handles.num_first_j,'String'));
3657end
3658[ModeMenu,ModeValue]=update_mode(SeriesData.i1_series{1},SeriesData.i2_series{1},SeriesData.j2_series{1});
3659InputTable=get(handles.InputTable,'Data');
3660displ_pair=update_listpair(SeriesData.i1_series{1},SeriesData.i2_series{1},SeriesData.j1_series{1},SeriesData.j2_series{1},ModeMenu{ModeValue},...
3661                                                 SeriesData.Time{1},TimeUnit,ref_i,ref_j,SeriesData.TimeName,InputTable,SeriesData.FileInfo{1});
3662for iline=1:size(InputTable,1)
3663    viewcell{iline}=num2str(iline);
3664end
3665viewcell=viewcell';
3666ModeMenu={'bursts';'series(Dj)'};
3667ModeValue=1;                                               
3668                   %i1_series,i2_series,j1_series,j2_series,mode,time,TimeUnit,ref_i,ref_j,TimeName,InputTable,FileInfo                             
3669% first raw of the GUI
3670uicontrol('Style','text','Units','normalized', 'Position', [0.05 0.88 0.5 0.1],'BackgroundColor',BackgroundColor,...
3671    'String','row to edit #','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','right'); % title
3672uicontrol('Style','popupmenu','Units','normalized', 'Position', [0.54 0.8 0.3 0.2],'BackgroundColor',[1 1 1],...
3673    'Callback',@(hObject,eventdata)ListView_Callback(hObject,eventdata),'String',viewcell,'Value',1,'FontUnits','points','FontSize',12,'FontWeight','bold',...
3674    'Tag','ListView','TooltipString','''ListView'':choice of the file series w for pair display');
3675% second raw of the GUI
3676uicontrol('Style','text','Units','normalized', 'Position', [0.05 0.79 0.7 0.1],'BackgroundColor',BackgroundColor,...
3677    'String','mode of index pairing:','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','left'); % title
3678uicontrol('Style','popupmenu','Units','normalized', 'Position', [0.05 0.62 0.9 0.2],'BackgroundColor',[1 1 1],...
3679    'Callback',@(hObject,eventdata)Mode_Callback(hObject,eventdata),'String',ModeMenu,'Value',ModeValue,'FontUnits','points','FontSize',12,'FontWeight','bold',...
3680    'Tag','Mode','TooltipString','''Mode'': choice of the image pair mode');
3681% third raw
3682uicontrol('Style','text','Units','normalized', 'Position', [0.05 0.6 0.7 0.1],'BackgroundColor',BackgroundColor,...
3683    'String','pair choice:','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','left'); % title
3684uicontrol('Style','listbox','Units','normalized', 'Position', [0.05 0.42 0.9 0.2],'BackgroundColor',[1 1 1],...
3685    'Callback',@(hObject,eventdata)ListPair_Callback(hObject,eventdata),'String',displ_pair,'Value',1,'FontUnits','points','FontSize',12,'FontWeight','bold',...
3686    'Tag','ListPair','TooltipString','''ListPair'': menu for selecting the image pair');
3687uicontrol('Style','text','Units','normalized', 'Position', [0.1 0.22 0.8 0.1],'BackgroundColor',BackgroundColor,...
3688    'String','ref_i           ref_j','FontUnits','points','FontSize',12,'FontWeight','bold','ForegroundColor','blue','HorizontalAlignment','center'); % title
3689uicontrol('Style','edit','Units','normalized', 'Position', [0.15 0.17 0.3 0.08],'BackgroundColor',[1 1 1],...
3690    'Callback',@(hObject,eventdata)num_ref_i_Callback(hObject,eventdata),'String',num2str(ref_i),'FontUnits','points','FontSize',12,'FontWeight','bold',...
3691    'Tag','num_ref_i','TooltipString','''num_ref_i'': reference field index i used to display dt in ''list_pair_civ''');
3692uicontrol('Style','edit','Units','normalized', 'Position', [0.55 0.17 0.3 0.08],'BackgroundColor',[1 1 1],...
3693    'Callback',@(hObject,eventdata)num_ref_j_Callback(hObject,eventdata),'String',num2str(ref_j),'FontUnits','points','FontSize',12,'FontWeight','bold',...
3694    'Tag','num_ref_j','TooltipString','''num_ref_j'': reference field index i used to display dt in ''list_pair_civ''');
3695uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.01 0.01 0.3 0.12],'BackgroundColor',[0 1 0],...
3696    'Callback',@(hObject,eventdata)OK_Callback(hObject,eventdata),'String','OK','FontUnits','points','FontSize',12,'FontWeight','bold',...
3697    'Tag','OK','TooltipString','''OK'': validate the choice');
3698%  last raw  of the GUI: pushbuttons
3699% 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),...
3700%     'FontWeight','bold','FontUnits','points','FontSize',12,'TooltipString','''OK'': apply the output to the current field series in uvmat');
3701drawnow
3702
3703%------------------------------------------------------------------------
3704function ListView_Callback(hObject,eventdata)
3705Mode_Callback(hObject,eventdata)
3706
3707%------------------------------------------------------------------------   
3708function Mode_Callback(hObject,eventdata)
3709%% get input info
3710hseries=findobj(allchild(0),'tag','series'); % handles of the GUI series
3711hhseries=guidata(hseries); % handles of the elements in the GUI series
3712TimeUnit=get(hhseries.TimeUnit,'String');
3713SeriesData=get(hseries,'UserData');
3714mode_list=get(hObject,'String');
3715mode=mode_list{get(hObject,'Value')};
3716hListView=findobj(get(hObject,'parent'),'Tag','ListView');
3717iview=get(hListView,'Value');
3718i1_series=SeriesData.i1_series{iview};
3719i2_series=SeriesData.i2_series{iview};
3720j1_series=SeriesData.j1_series{iview};
3721j2_series=SeriesData.j2_series{iview};
3722
3723%% enable j index visibility after the new choice
3724
3725if strcmp(mode,'series(Dj)')
3726   status_j='on'; % default
3727else
3728       status_j='off'; % no j index needed for bust case
3729end
3730enable_j(hhseries,status_j) % no j index needed
3731
3732%% get the reference indices for the time interval Dt
3733href_i=findobj(get(hObject,'parent'),'Tag','ref_i');
3734ref_i=[];ref_j=[];
3735if strcmp(get(href_i,'Visible'),'on')
3736    ref_i=str2num(get(href_i,'String'));
3737end
3738if isempty(ref_i)
3739    ref_i=1;
3740end
3741if isempty(ref_j)
3742    ref_j=1;
3743end
3744
3745%% update the menu ListPair
3746Menu=update_listpair(i1_series,i2_series,j1_series,j2_series,mode,SeriesData.Time{iview},TimeUnit,ref_i,ref_j,SeriesData.FileInfo);
3747hlist_pairs=findobj(get(hObject,'parent'),'Tag','ListPair');
3748set(hlist_pairs,'Value',1)% set the first choice by default in ListPair
3749set(hlist_pairs,'String',Menu)% set the menu in ListPair
3750ListPair_Callback(hlist_pairs,[])% apply the default choice in ListPair
3751
3752%-------------------------------------------------------------
3753% --- Executes on selection in ListPair.
3754function ListPair_Callback(hObject,eventdata)
3755%------------------------------------------------------------
3756list_pair=get(hObject,'String'); % get the menu of image pairs
3757if isempty(list_pair)
3758    string='';
3759else
3760    string=list_pair{get(hObject,'Value')};
3761   % string=regexprep(string,',.*',''); % removes time indication (after ',')
3762end
3763hseries=findobj(allchild(0),'tag','series');
3764hPairString=findobj(hseries,'tag','PairString');
3765PairString=get(hPairString,'Data');
3766hListView=findobj(get(hObject,'parent'),'Tag','ListView');
3767iview=get(hListView,'Value');
3768PairString{iview,1}=string;
3769% report the selected pair string to the table PairString
3770set(hPairString,'Data',PairString)
3771
3772
3773%------------------------------------------------------------------------
3774function num_ref_i_Callback(hObject, eventdata)
3775%------------------------------------------------------------------------
3776Mode_Callback([],[])
3777
3778%------------------------------------------------------------------------
3779function num_ref_j_Callback(hObject, eventdata)
3780%------------------------------------------------------------------------
3781Mode_Callback([],[])
3782
3783%------------------------------------------------------------------------
3784function OK_Callback(hObject, eventdata)
3785%------------------------------------------------------------------------
3786delete(get(hObject,'parent'))
3787
3788
3789%------------------------------------------------------------------------
3790% --- Executes on button press in ClearLine.
3791%------------------------------------------------------------------------
3792function ClearLine_Callback(hObject, eventdata, handles)
3793InputTable=get(handles.InputTable,'Data');
3794iline=str2double(get(handles.InputLine,'String'));
3795if size(InputTable,1)>1
3796    InputTable(iline,:)=[]; % suppress the current line if not the first
3797    set(handles.InputTable,'Data',InputTable);
3798end
3799set(handles.REFRESH,'BackgroundColor',[1 0 1])% set REFRESH button to magenta color to indicate that input refr
3800
3801
3802% --- Executes on button press in MonitorCluster.
3803function MonitorCluster_Callback(hObject, eventdata, handles)
3804disp('format: R/W=run/wait, time lapsed, R=nbre of cores,W=walltime')
3805system('oarstat |grep N=UVmat')% check the list of jobs launched with uvmat
3806
3807
3808function OutputSubDir_Callback(hObject, eventdata, handles)
3809set(handles.OutputSubDir,'BackgroundColor',[1 1 1])
3810
3811
3812% --- Executes on button press in CheckOverwrite.
3813function CheckOverwrite_Callback(hObject, eventdata, handles)
3814
3815% --- Executes on button press in TestCPUTime.
3816function TestCPUTime_Callback(hObject, eventdata, handles)
3817% hObject    handle to TestCPUTime (see GCBO)
3818% eventdata  reserved - to be defined in a future version of MATLAB
3819% handles    structure with handles and user data (see GUIDATA)
3820
3821
3822% --- Executes on button press in DiskQuota.
3823function DiskQuota_Callback(hObject, eventdata, handles)
3824SeriesData=get(handles.series,'UserData');
3825system(SeriesData.SeriesParam.DiskQuotaCmd)
3826
3827
3828
3829% --- Executes on button press in Replicate.
3830function Replicate_Callback(hObject, eventdata, handles)
3831if get(handles.Replicate,'Value')
3832InputTable=get(handles.InputTable,'Data');
3833browse_data(fullfile(InputTable{1,1},InputTable{1,2}))
3834else
3835    hh=findobj(allchild(0),'Tag','browse_data');
3836    if ~isempty(hh)
3837        delete(hh)
3838    end
3839end
Note: See TracBrowser for help on using the repository browser.