source: trunk/src/series.m @ 1187

Last change on this file since 1187 was 1187, checked in by sommeria, 12 days ago

mask accessory updated

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