source: trunk/src/series.m @ 1053

Last change on this file since 1053 was 1051, checked in by sommeria, 6 years ago

psmsn cluster command updated, pb with multimask solved...

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