source: trunk/src/series.m @ 1069

Last change on this file since 1069 was 1069, checked in by sommeria, 5 years ago

browse_data updated

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