source: trunk/src/series.m @ 1036

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