source: trunk/src/series.m @ 1171

Last change on this file since 1171 was 1171, checked in by sommeria, 10 hours ago

bug corrected in test civ1

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