source: trunk/src/series.m @ 1188

Last change on this file since 1188 was 1188, checked in by sommeria, 2 months ago

file relabeling implemented for civ_series

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