source: trunk/src/series.m @ 1033

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

miscellaneous updates

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