source: trunk/src/series.m @ 773

Last change on this file since 773 was 773, checked in by sommeria, 10 years ago

help web link corrected

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