source: trunk/src/series.m @ 1179

Last change on this file since 1179 was 1179, checked in by sommeria, 4 weeks ago

a few bug repairs and cleaning

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