source: trunk/src/series.m @ 842

Last change on this file since 842 was 842, checked in by sommeria, 6 years ago

button added in series to clear an input line

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