source: trunk/src/series.m @ 1133

Last change on this file since 1133 was 1133, checked in by sommeria, 3 months ago

bug corrected in plot_field

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