source: trunk/src/series.m @ 667

Last change on this file since 667 was 667, checked in by sommeria, 11 years ago

a few bugs corrected.
multimask introduced in series
displ_uvmat transformed into disp_uvmat

File size: 119.4 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)
124
125% check default input data
126if ~exist('Param','var')
127    Param=[]; %default
128end
129
130%% list of builtin functions in the mebu ActionName
131ActionList={'check_data_files';'aver_stat';'time_series';'civ_series';'merge_proj'};% WARNING: fits with nb_builtin_ACTION=4 in ActionName_callback
132NbBuiltinAction=numel(ActionList);
133[path_series,name,ext]=fileparts(which('series'));% path to the GUI series
134path_series_fct=fullfile(path_series,'series');%path of the functions in subdirectroy 'series'
135ActionExtList={'.m';'.sh'};% default choice of extensions (Matlab fct .m or compiled version .sh
136ActionPathList=cell(NbBuiltinAction,numel(ActionExtList));%initiate the cell matrix of Action fct paths
137ActionPathList(:)={path_series_fct}; %set the default path to series fcts to all list members
138RunModeList={'local';'background'};% default choice of extensions (Matlab fct .m or compiled version .sh)
139[s,w]=system('oarstat');% look for cluster system 'oar'
140if isequal(s,0)
141    RunModeList=[RunModeList;{'cluster_oar'}];
142end
143[s,w]=system('qstat');% look for cluster system 'sge'
144if isequal(s,0)
145    RunModeList=[RunModeList;{'cluster_sge'}];
146end
147set(handles.RunMode,'String',RunModeList)
148
149%% list of builtin transform functions in the mebu TransformName
150TransformList={'';'sub_field';'phys';'phys_polar'};% WARNING: must fit with the corresponding menu in uvmat and nb_builtin_transform=4 in  TransformName_callback
151NbBuiltinTransform=numel(TransformList);
152path_transform_fct=fullfile(path_series,'transform_field');
153TransformPathList=cell(NbBuiltinTransform,1);%initiate the cell matrix of Action fct paths
154TransformPathList(:)={path_transform_fct}; %set the default path to series fcts to all list members
155
156%% get the user defined functions stored in the personal file uvmat_perso.mat
157dir_perso=prefdir;
158profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
159if exist(profil_perso,'file')
160    h=load (profil_perso);
161    %get the list of previous input files in the upper bar menu Open
162    if isfield(h,'MenuFile')
163        for ifile=1:min(length(h.MenuFile),5)
164            set(handles.(['MenuFile_' num2str(ifile)]),'Label',h.MenuFile{ifile});
165            set(handles.(['MenuFile_' num2str(ifile+5)]),'Label',h.MenuFile{ifile});
166        end
167    end
168    %get the list of previous camapigns in the upper bar menu Open campaign
169    if isfield(h,'MenuCampaign')
170        for ifile=1:min(length(h.MenuCampaign),5)
171            set(handles.(['MenuCampaign_' num2str(ifile)]),'Label',h.MenuCampaign{ifile});
172        end
173    end
174    %get the menu of actions
175    if isfield(h,'ActionExtListUser') && iscell(h.ActionExtListUser)
176        ActionExtList=[ActionExtList; h.ActionExtListUser];
177    end
178    if isfield(h,'ActionListUser') && iscell(h.ActionListUser) && isfield(h,'ActionPathListUser') && iscell(h.ActionPathListUser)
179        ActionList=[ActionList;h.ActionListUser];
180        ActionPathList=[ActionPathList;h.ActionPathListUser];
181    end
182    %get the menu of transform fct
183    if isfield(h,'TransformListUser') && iscell(h.TransformListUser) && isfield(h,'TransformPathListUser') && iscell(h.TransformPathListUser)
184        TransformList=[TransformList;h.TransformListUser];
185        TransformPathList=[TransformPathList;h.TransformPathListUser];
186    end
187end
188
189%% selection of the input Action fct
190ActionCheckExist=true(size(ActionList));%initiate the check of the path to the listed action fct
191for ilist=NbBuiltinAction+1:numel(ActionList)%check  the validity of the path of the user defined Action fct
192    ActionCheckExist(ilist)=exist(fullfile(ActionPathList{ilist},[ActionList{ilist} '.m']),'file');
193end
194ActionPathList=ActionPathList(ActionCheckExist,:);% suppress the menu options which are not valid anymore
195ActionList=ActionList(ActionCheckExist);
196set(handles.ActionName,'String',[ActionList;{'more...'}])
197set(handles.ActionName,'UserData',ActionPathList)
198ActionIndex=[];
199if isfield(Param,'ActionName')% copy the selected menu index transferred in Param from uvmat
200    ActionIndex=find(strcmp(Param.ActionName,ActionList),1);
201end
202if isempty(ActionIndex)
203    ActionIndex=1;
204end
205set(handles.ActionName,'Value',ActionIndex)
206set(handles.ActionPath,'String',ActionPathList{ActionIndex})
207set(handles.ActionExt,'Value',1)
208set(handles.ActionExt,'String',ActionExtList)
209
210%% selection of the input transform fct
211TransformCheckExist=true(size(TransformList));
212for ilist=NbBuiltinTransform+1:numel(TransformList)
213    TransformCheckExist(ilist)=exist(fullfile(TransformPathList{ilist},[TransformList{ilist} '.m']),'file');
214end
215TransformPathList=TransformPathList(TransformCheckExist);
216TransformList=TransformList(TransformCheckExist);
217set(handles.TransformName,'String',[TransformList;{'more...'}])
218set(handles.TransformName,'UserData',TransformPathList)
219TransformIndex=[];
220if isfield(Param,'TransformName')% copy the selected menu index transferred in Param from uvmat
221    TransformIndex=find(strcmp(Param.TransformName,TransformList),1);
222end
223if isempty(TransformIndex)
224    TransformIndex=1;
225end
226set(handles.TransformName,'Value',TransformIndex)
227set(handles.TransformPath,'String',TransformPathList{TransformIndex})
228   
229%% fields input initialisation
230if isfield(Param,'list_fields')&& isfield(Param,'index_fields') &&~isempty(Param.list_fields) &&~isempty(Param.index_fields)
231    set(handles.FieldName,'String',Param.list_fields);% list menu fields
232    set(handles.FieldName,'Value',Param.index_fields);% selected string index
233end
234if isfield(Param,'Coord_x_str')&& isfield(Param,'Coord_x_val')
235        set(handles.Coord_x,'String',Param.Coord_x_str);% list menu fields
236    set(handles.Coord_x,'Value',Param.Coord_x_val);% selected string index
237end
238if isfield(Param,'Coord_y_str')&& isfield(Param,'Coord_y_val')
239        set(handles.Coord_y,'String',Param.Coord_y_str);% list menu fields
240    set(handles.Coord_y,'Value',Param.Coord_y_val);% selected string index
241end
242
243%% introduce the input file name(s) if defined from input Param
244if isfield(Param,'FileName')
245    InputTable={'','','','',''}; % refresh the file input table
246    set(handles.InputTable,'Data',InputTable)
247    if isfield(Param,'FileName_1')
248        display_file_name(handles,Param.FileName,'one')%refresh the input table
249        display_file_name(handles,Param.FileName_1,1)
250    else
251        display_file_name(handles,Param.FileName,'one')%refresh the input table
252    end
253end 
254if isfield(Param,'incr_i')
255    set(handles.num_incr_i,'String',num2str(Param.incr_i))
256end
257if isfield(Param,'incr_j')
258    set(handles.num_incr_j,'String',num2str(Param.incr_j))
259end
260
261
262%------------------------------------------------------------------------
263% --- Outputs from this function are returned to the command line.
264function varargout = series_OutputFcn(hObject, eventdata, handles)
265%------------------------------------------------------------------------
266% varargout  cell array for returning output args (see VARARGOUT);
267% hObject    handle to figure
268% eventdata  reserved - to be defined in a future version of MATLAB
269% handles    structure with handles and user data (see GUIDATA)
270% Get default command line output from handles structure
271varargout{1} = handles.output;
272
273%------------------------------------------------------------------------
274%------------------------------------------------------------------------
275%  II - FUNCTIONS FOR INTRODUCING THE INPUT FILES
276% automatically sets the global properties when the rootfile name is introduced
277% then activate the view-field actionname if selected
278% it is activated either by clicking on the RootPath window or by the
279% browser
280%------------------------------------------------------------------------
281%------------------------------------------------------------------------
282% --- fct activated by the browser under 'Open'
283%------------------------------------------------------------------------ 
284function MenuBrowse_Callback(hObject, eventdata, handles)
285
286%% look for the previously opened file 'oldfile'
287oldfile=''; %default
288if get(handles.CheckAppend,'Value')
289    % case 'checkappend': new series appended to the input table
290    InputTable=get(handles.InputTable,'Data');
291    RootPathCell=InputTable(:,1);
292    SubDirCell=InputTable(:,3);
293    oldfile=''; %default
294    if ~(isempty(RootPathCell) || isequal(RootPathCell,{''}))%loads the previously stored file name and set it as default in the file_input box
295        oldfile=fullfile(RootPathCell{1},SubDirCell{1});
296    end
297else
298    % case refresh the input table by a new series
299    SeriesData=get(handles.series,'UserData');
300    if isfield(SeriesData,'RefFile')
301        oldfile=SeriesData.RefFile{1};
302    end
303end
304
305%% use a file name stored in prefdir
306dir_perso=prefdir;
307profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
308if exist(profil_perso,'file')
309    h=load (profil_perso);
310    if isfield(h,'RootPath') && ischar(h.RootPath)
311        oldfile=h.RootPath;
312    end
313end
314
315%% launch the browser
316fileinput=uigetfile_uvmat('pick a file to append in the input table',oldfile);
317if ~isempty(fileinput)
318%     if get(handles.CheckAppend,'Value')
319%         display_file_name(handles,fileinput,'append')
320%     else
321        display_file_name(handles,fileinput,'one')
322%     end
323end
324
325% --------------------------------------------------------------------
326function MenuBrowseAppend_Callback(hObject, eventdata, handles)
327
328%% look for the previously opened file 'oldfile'
329InputTable=get(handles.InputTable,'Data');
330RootPathCell=InputTable(:,1);
331if isempty(RootPathCell{1})% no input file in the table
332     MenuBrowse_Callback(hObject, eventdata, handles)%refresh the input table, not append
333     return
334end
335SubDirCell=InputTable(:,2);
336% oldfile=''; %default
337% if ~(isempty(RootPathCell) || isequal(RootPathCell,{''}))%loads the previously stored file name and set it as default in the file_input box
338    oldfile=fullfile(RootPathCell{1},SubDirCell{1});
339% end
340
341%% use a file name stored in prefdir
342dir_perso=prefdir;
343profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
344if exist(profil_perso,'file')
345    h=load (profil_perso);
346    if isfield(h,'RootPath') && ischar(h.RootPath)
347        oldfile=h.RootPath;
348    end
349end
350
351%% launch the browser
352fileinput=uigetfile_uvmat('pick a file to append in the input table',oldfile);
353if ~isempty(fileinput)
354        display_file_name(handles,fileinput,'append')
355end
356
357%------------------------------------------------------------------------
358% --- fct activated by selecting a previous file under the menu Open
359%------------------------------------------------------------------------
360function MenuFile_Callback(hObject, eventdata, handles)
361
362display_file_name(handles,get(hObject,'Label'),'one')
363
364%------------------------------------------------------------------------
365% --- fct activated by selecting a previous file under the menu Open/append
366%------------------------------------------------------------------------
367function MenuFile_append_Callback(hObject, eventdata, handles)
368
369InputTable=get(handles.InputTable,'Data');
370if isempty(InputTable{1,1})% no input file in the table
371    display_file_name(handles,get(hObject,'Label'),'one') %refresh the input table, not append
372else
373    display_file_name(handles,get(hObject,'Label'),'append')% append the selected file to the current list of InputTable
374end
375
376%------------------------------------------------------------------------
377% --- fct activated by the browser under 'Open campaign'
378%------------------------------------------------------------------------
379function MenuBrowseCampaign_Callback(hObject, eventdata, handles)
380
381set(handles.MenuOpenCampaign,'ForegroundColor',[1 1 0])
382drawnow
383InputTable=get(handles.InputTable,'Data');
384RootPath=InputTable{1,1};
385CampaignPath=fileparts(fileparts(RootPath));
386DirFull=uigetfile_uvmat('define this path as the Campaign folder:',CampaignPath,'uigetdir');
387if ~ischar(DirFull)|| ~exist(DirFull,'dir')
388    return
389end
390OutPut=browse_data(DirFull);% open the GUI browse_data to get select a campaign dir, experiment and device
391if ~isfield(OutPut,'Campaign')
392    return
393end
394DirName=fullfile(OutPut.Campaign,OutPut.Experiment{1},OutPut.DataSeries{1});
395ListStruct=dir(DirName); %list files and the dir DataSeries
396% select the first appropriate file in the dir
397FileName='';
398for ilist=1:numel(ListStruct)
399    if ~isequal(ListStruct(ilist).isdir,1)%look for files, not dir
400        FileName=ListStruct(ilist).name;
401        FileType=get_file_type(fullfile(DirName,FileName));
402        switch FileType
403            case {'image','multimage','civx','civdata','netcdf'}
404                break
405        end
406    end
407end
408if isempty(FileName)
409    msgbox_uvmat('ERROR',['no appropriate input file in the DataSeries folder ' fullfile(DirName)])
410    return
411end
412
413%% update the list of campaigns in the menubar
414MenuCampaign=[{get(handles.MenuCampaign_1,'Label')};{get(handles.MenuCampaign_2,'Label')};...
415    {get(handles.MenuCampaign_3,'Label')};{get(handles.MenuCampaign_4,'Label')};{get(handles.MenuCampaign_5,'Label')}];
416check_dir=isempty(find(strcmp(DirFull,MenuCampaign)));
417if check_dir %insert the new campaign in the list if it is not found
418    MenuCampaign(end)=[]; %suppress the last item
419    MenuCampaign=[{DirFull};MenuCampaign];%insert the new campaign
420    for ilist=1:numel(MenuCampaign)
421        set(handles.(['MenuCampaign_' num2str(ilist)]),'Label',MenuCampaign{ilist})
422    end
423    % save the list for future opening:
424    dir_perso=prefdir;
425    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
426    if exist(profil_perso,'file')
427        save (profil_perso,'MenuCampaign','RootPath','-append'); %store the file names for future opening of uvmat
428    else
429        save (profil_perso,'MenuCampaign','RootPath','-V6'); %store the file names for future opening of uvmat
430    end
431end
432
433%% display the selected field and related information
434if get(handles.CheckAppend,'Value')
435    display_file_name(handles,fullfile(DirName,FileName),'append')
436else
437    display_file_name(handles,fullfile(DirName,FileName),'one')
438end
439set(handles.MenuOpenCampaign,'ForegroundColor',[0 0 0])
440
441% --------------------------------------------------------------------
442function MenuCampaign_Callback(hObject, eventdata, handles)
443% --------------------------------------------------------------------
444set(handles.MenuOpenCampaign,'ForegroundColor',[1 1 0])
445OutPut=browse_data(get(hObject,'Label'));% open the GUI browse_data to get select a campaign dir, experiment and device
446if ~isfield(OutPut,'Campaign')
447    return
448end
449DirName=fullfile(OutPut.Campaign,OutPut.Experiment{1},OutPut.DataSeries{1});
450hdir=dir(DirName); %list files and dirs
451for ilist=1:numel(hdir)
452    if ~isequal(hdir(ilist).isdir,1)%look for files, not dir
453        FileName=hdir(ilist).name;
454        FileType=get_file_type(fullfile(DirName,FileName));
455        switch FileType
456            case {'image','multimage','civx','civdata','netcdf'}
457            break
458        end
459    end
460end
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
469
470%------------------------------------------------------------------------
471% --- Executes when entered data in editable cell(s) in InputTable.
472function InputTable_CellEditCallback(hObject, eventdata, handles)
473%------------------------------------------------------------------------
474set(handles.REFRESH,'Visible','on')
475% set(handles.REFRESH_title,'Visible','on')
476iview=eventdata.Indices(1);
477view_set=get(handles.REFRESH,'UserData');
478if isempty(find(view_set==iview))
479    set(handles.REFRESH,'UserData',[view_set iview])
480end
481%% enable other menus and uicontrols
482set(handles.MenuOpenCampaign,'Enable','on')
483set(handles.MenuCampaign_1,'Enable','on')
484set(handles.MenuCampaign_2,'Enable','on')
485set(handles.MenuCampaign_3,'Enable','on')
486set(handles.MenuCampaign_4,'Enable','on')
487set(handles.MenuCampaign_5,'Enable','on')
488set(handles.RUN, 'Enable','On')
489set(handles.RUN,'BackgroundColor',[1 0 0])% set RUN button to red
490
491%------------------------------------------------------------------------
492% --- Executes on button press in REFRESH.
493function REFRESH_Callback(hObject, eventdata, handles)
494%------------------------------------------------------------------------
495InputTable=get(handles.InputTable,'Data');
496% view_set=get(handles.REFRESH,'UserData');% list of lines to refresh
497set(handles.REFRESH,'BackgroundColor',[1 1 0])% set REFRESH  button to yellow color (indicate activation)
498drawnow
499empty_line=false(size(InputTable,1),1);
500for iline=1:size(InputTable,1)
501    empty_line(iline)= isempty(cell2mat(InputTable(iline,1:3)));
502end
503InputTable(empty_line,:)=[];%remove empty lines
504set(handles.InputTable,'Data',InputTable)
505for iview=1:size(InputTable,1)
506    RootPath=fullfile(InputTable{iview,1},InputTable{iview,2});
507    if ~exist(RootPath,'dir')
508        i1_series=[];
509        RootPath=fileparts(RootPath); %will try the upped forlder
510    else
511        [RootPath,SubDir,RootFile,i1_series,i2_series,j1_series,j2_series,tild,FileType,FileInfo,MovieObject]=...
512            find_file_series(fullfile(InputTable{iview,1},InputTable{iview,2}),[InputTable{iview,3} InputTable{iview,4} InputTable{iview,5}]);
513    end
514    if isempty(i1_series)
515        fileinput=uigetfile_uvmat(['wrong input at line ' num2str(iview) ':pick a new input file'],RootPath);
516        if isempty(fileinput)
517            set(handles.REFRESH,'BackgroundColor',[1 0 0])% set REFRESH  back to red color
518            return
519        else
520            display_file_name(handles,fileinput,iview)
521        end
522    else
523       update_rootinfo(handles,i1_series,i2_series,j1_series,j2_series,FileType,FileInfo,MovieObject,iview)
524    end
525end
526set(handles.REFRESH,'Visible','off')
527set(handles.REFRESH_title,'Visible','off')
528% set(handles.REFRESH,'UserData',[])
529
530%------------------------------------------------------------------------
531% --- Function called when a new file is opened, either by series_OpeningFcn or by the browser
532function display_file_name(handles,fileinput,iview)
533%------------------------------------------------------------------------ 
534%
535% INPUT:
536% handles: handles of elements in the GUI
537% fileinput: input file name, including path
538% iview: line index in the input table
539%       or 'one': refresh the list
540%         'append': add a new line to the input table
541
542%% get the input root name, indices, file extension and nomenclature NomType
543if ~exist(fileinput,'file')
544    msgbox_uvmat('ERROR',['input file ' fileinput  ' does not exist'])
545    return
546end
547
548%% detect root name, nomenclature and indices in the input file name:
549[FilePath,FileName,FileExt]=fileparts(fileinput);
550% detect the file type, get the movie object if relevant, and look for the corresponding file series:
551% the root name and indices may be corrected by including the first index i1 if a corresponding xml file exists
552[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]);
553if isempty(RootFile)&&isempty(i1_series)
554    errormsg='no input file in the series';
555    return
556end
557if strcmp(FileType,'txt')
558    edit(fileinput)
559    return
560elseif strcmp(FileType,'xml')
561    editxml(fileinput)
562     return
563elseif strcmp(FileType,'figure')
564    open(fileinput)
565     return
566end
567
568%% enable other menus and uicontrols
569set(handles.MenuOpenCampaign,'Enable','on')
570set(handles.MenuCampaign_1,'Enable','on')
571set(handles.MenuCampaign_2,'Enable','on')
572set(handles.MenuCampaign_3,'Enable','on')
573set(handles.MenuCampaign_4,'Enable','on')
574set(handles.MenuCampaign_5,'Enable','on')
575set(handles.RUN, 'Enable','On')
576set(handles.RUN,'BackgroundColor',[1 0 0])% set RUN button to red
577set(handles.InputTable,'BackgroundColor',[1 1 0]) % set RootPath edit box  to yellow
578drawnow
579
580
581
582%% fill the list of file series
583InputTable=get(handles.InputTable,'Data');
584SeriesData=get(handles.series,'UserData');
585if strcmp(iview,'append') % display the input data as a new line in the table
586    iview=size(InputTable,1);% the next line in InputTable becomes the current line
587    InputTable(iview+1,:)={'','','','',''};
588    InputTable(iview,:)=[{RootPath},{SubDir},{RootFile},{NomType},{FileExt}];
589elseif strcmp(iview,'one') % refresh the list of  input  file series
590    iview=1; %the first line in InputTable becomes the current line
591    InputTable=[{'','','','',''};{'','','','',''}];
592    InputTable(iview,:)=[{RootPath},{SubDir},{RootFile},{NomType},{FileExt}];
593    set(handles.TimeTable,'Data',[{[]},{[]},{[]},{[]}])
594    set(handles.MinIndex_i,'Data',[])
595    set(handles.MaxIndex_i,'Data',[])
596    set(handles.MinIndex_j,'Data',[])
597    set(handles.MaxIndex_j,'Data',[])
598    set(handles.ListView,'Value',1)
599    set(handles.ListView,'String',{'1'})
600    set(handles.PairString,'Data',{''})
601    SeriesData.i1_series={};
602    SeriesData.i2_series={};
603    SeriesData.j1_series={};
604    SeriesData.j2_series={};
605    SeriesData.FileType={};
606    SeriesData.FileInfo={};
607    SeriesData.Time={};
608end
609nbview=size(InputTable,1)-1;% rmq: the last line is set blank to allow manual addition of a line
610set(handles.ListView,'String',mat2cell((1:nbview)',ones(nbview,1)))
611set(handles.ListView,'Value',iview)
612set(handles.InputTable,'Data',InputTable)
613
614%% determine the selected reference field indices for pair display
615if isempty(i1)
616    i1=1;
617end
618if isempty(i2)
619    i2=i1;
620end
621ref_i=floor((i1+i2)/2);% reference image number corresponding to the file
622set(handles.num_ref_i,'String',num2str(ref_i));
623% set(handles.num_ref_i,'UserData',[i1 i2])%store the indices for future opening
624if isempty(j1)
625    j1=1;
626end
627if isempty(j2)
628    j2=j1;
629end
630ref_j=floor((j1+j2)/2);% reference image number corresponding to the file
631set(handles.num_ref_j,'String',num2str(ref_j));
632
633%% update the list of recent files in the menubar and save it for future opening
634MenuFile=[{get(handles.MenuFile_1,'Label')};{get(handles.MenuFile_2,'Label')};...
635    {get(handles.MenuFile_3,'Label')};{get(handles.MenuFile_4,'Label')};{get(handles.MenuFile_5,'Label')}];
636str_find=strcmp(fileinput,MenuFile);
637if isempty(find(str_find,1))
638    MenuFile=[{fileinput};MenuFile];%insert the current file if not already in the list
639end
640for ifile=1:min(length(MenuFile),5)
641    eval(['set(handles.MenuFile_' num2str(ifile) ',''Label'',MenuFile{ifile});'])
642end
643dir_perso=prefdir;
644profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
645if exist(profil_perso,'file')
646    save (profil_perso,'MenuFile','-append'); %store the file names for future opening of uvmat
647else
648    save (profil_perso,'MenuFile','-V6'); %store the file names for future opening of uvmat
649end
650% save the opened file to initiate future opening
651SeriesData.RefFile{iview}=fileinput;% reference opening file for line iview
652SeriesData.Ref_i1=i1;
653SeriesData.Ref_i2=i2;
654SeriesData.Ref_j1=j1;
655SeriesData.Ref_j2=j2;
656set(handles.series,'UserData',SeriesData)
657
658set(handles.InputTable,'BackgroundColor',[1 1 1])
659
660%% initiate input file series and refresh the current field view:     
661update_rootinfo(handles,i1_series,i2_series,j1_series,j2_series,FileType,FileInfo,MovieObject,iview);
662
663%------------------------------------------------------------------------
664% --- Update information about a new field series (indices to scan, timing,
665%     calibration from an xml file
666function update_rootinfo(handles,i1_series,i2_series,j1_series,j2_series,FileType,FileInfo,VideoObject,iview)
667%------------------------------------------------------------------------
668InputTable=get(handles.InputTable,'Data');
669
670%% display the min and max indices for the whole file series
671if size(i1_series,2)==2 && min(min(i1_series(:,1,:)))==0
672    MinIndex_j=1;% index j set to 1 by default
673    MaxIndex_j=1;
674    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)
675    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)
676else
677    ref_i=squeeze(max(i1_series(1,:,:),[],2));% select ref_j index for each ref_i
678    ref_j=squeeze(max(j1_series(1,:,:),[],3));% select ref_i index for each ref_j
679     MinIndex_i=min(find(ref_i))-1;
680     MaxIndex_i=max(find(ref_i))-1;
681     MaxIndex_j=max(find(ref_j))-1;
682     MinIndex_j=min(find(ref_j))-1;
683    diff_j_max=diff(ref_j);
684    diff_i_max=diff(ref_i);
685   
686%     pair_max=squeeze(max(i1_series,[],1)); %max on pair index
687%     j_max=max(pair_max,[],1);
688%     MinIndex_i=find(j_max, 1 )-1;% min ref index i detected in the series (corresponding to the first non-zero value of i1_series, except for zero index)
689%     MaxIndex_i=find(j_max, 1, 'last' )-1;% max ref index i detected in the series (corresponding to the first non-zero value of i1_series, except for zero index)
690%     diff_i_max=diff(j_max);
691    if ~isempty(diff_i_max) && isequal (diff_i_max,diff_i_max(1)*ones(size(diff_i_max)))
692        set(handles.num_incr_i,'String',num2str(diff_i_max(1)))% detect an increment to dispaly by default
693    end
694%     i_max=max(pair_max,[],2);
695%     MinIndex_j=min(find(i_max))-1;% min ref index j
696%     MaxIndex_j=max(find(i_max))-1;% max ref index j
697%     diff_j_max=diff(i_max);
698    if isequal (diff_j_max,diff_j_max(1)*ones(size(diff_j_max)))
699        set(handles.num_incr_j,'String',num2str(diff_j_max(1)))
700    end
701end
702if isequal(MinIndex_i,-1)
703    MinIndex_i=0;
704end
705if isequal(MinIndex_j,-1)
706    MinIndex_j=0;
707end
708MinIndex_i_table=get(handles.MinIndex_i,'Data');%retrieve the min indices in the table MinIndex
709MinIndex_j_table=get(handles.MinIndex_j,'Data');%retrieve the min indices in the table MinIndex
710MaxIndex_i_table=get(handles.MaxIndex_i,'Data');%retrieve the min indices in the table MinIndex
711MaxIndex_j_table=get(handles.MaxIndex_j,'Data');%retrieve the min indices in the table MinIndex
712MinIndex_i_table(iview,1)=MinIndex_i;
713MinIndex_j_table(iview,1)=MinIndex_j;
714MaxIndex_i_table(iview,1)=MaxIndex_i;
715MaxIndex_j_table(iview,1)=MaxIndex_j;
716set(handles.MinIndex_i,'Data',MinIndex_i_table)%display the min indices in the table MinIndex
717set(handles.MinIndex_j,'Data',MinIndex_j_table)%display the max indices in the table MaxIndex
718set(handles.MaxIndex_i,'Data',MaxIndex_i_table)%display the min indices in the table MinIndex
719set(handles.MaxIndex_j,'Data',MaxIndex_j_table)%display the max indices in the table MaxIndex
720
721%% adjust the first and last indices for the selected series, only if requested by the bounds
722% i index, compare input to min index i
723first_i=str2num(get(handles.num_first_i,'String'));%retrieve previous first i
724ref_i=str2num(get(handles.num_ref_i,'String'));%index i given by the input field
725if isempty(first_i)
726    first_i=ref_i;% first_i updated by the input value
727elseif first_i < MinIndex_i
728    first_i=MinIndex_i; % first_i set to the min i index (restricted by oter input lines)
729elseif first_i >MaxIndex_i
730    first_i=MaxIndex_i;% first_i set to the max i index (restricted by oter input lines)
731end
732% j index,  compare input to min index j
733first_j=str2num(get(handles.num_first_j,'String'));
734ref_j=str2num(get(handles.num_ref_j,'String'));%index j given by the input field
735if isempty(first_j)
736    first_j=ref_j;% first_j updated by the input value
737elseif first_j<MinIndex_j
738    first_j=MinIndex_j; % first_j set to the min j index (restricted by oter input lines)
739elseif first_j >MaxIndex_j
740    first_j=MaxIndex_j; % first_j set to the max j index (restricted by oter input lines)
741end
742% i index, compare input to max index i
743last_i=str2num(get(handles.num_last_i,'String'));
744if isempty(last_i)
745    last_i=ref_i;
746elseif last_i > MaxIndex_i
747    last_i=MaxIndex_i;
748elseif last_i<first_i
749    last_i=first_i;
750end
751% j index, compare input to max index j
752last_j=str2num(get(handles.num_last_j,'String'));
753if isempty(last_j)
754    last_j=ref_j;
755elseif last_j>MaxIndex_j
756    last_j=MaxIndex_j;
757elseif last_j<first_j
758    last_j=first_j;
759end
760set(handles.num_first_i,'String',num2str(first_i));
761set(handles.num_first_j,'String',num2str(first_j));
762set(handles.num_last_i,'String',num2str(last_i));
763set(handles.num_last_j,'String',num2str(last_j));
764
765%% number of slices set by default
766NbSlice=1;%default
767% read  value set by the first series for the checkappend mode (iwiew >1)
768if iview>1 && strcmp(get(handles.num_NbSlice,'Visible'),'on')
769    NbSlice=str2num(get(handles.num_NbSlice,'String'));
770end
771
772%% default time unit
773TimeUnit='';
774% read  value set by the first series for the checkappend mode (iwiew >1)
775if iview>1
776    TimeUnit=get(handles.TimeUnit,'String');
777end
778TimeSource='';
779Time=[];%default
780
781%%  read image documentation file if found
782XmlData=[];
783check_calib=0;
784XmlFileName=find_imadoc(InputTable{iview,1},InputTable{iview,2},InputTable{iview,3},InputTable{iview,5});
785if ~isempty(XmlFileName)
786    [XmlData,errormsg]=imadoc2struct(XmlFileName);
787    if ~isempty(errormsg)
788         msgbox_uvmat('WARNING',['error in reading ' XmlFileName ': ' errormsg]);
789    end
790    % read time if available
791    if isfield(XmlData,'Time')
792        Time=XmlData.Time;
793        TimeSource='xml';
794    end
795    if isfield(XmlData,'Camera')
796        if isfield(XmlData.Camera,'NbSlice')&& ~isempty(XmlData.Camera.NbSlice)
797            if iview>1 && ~isempty(NbSlice) && ~strcmp(NbSlice,XmlData.Camera.NbSlice)
798                msgbox_uvmat('WARNING','inconsistent number of slices with the first field series');
799            end
800            NbSlice=XmlData.Camera.NbSlice;% Nbre of slices from camera
801        end
802        if isfield(XmlData.Camera,'TimeUnit')&& ~isempty(XmlData.Camera.TimeUnit)
803            if iview>1 && ~isempty(TimeUnit) && ~strcmp(TimeUnit,XmlData.Camera.TimeUnit)
804                msgbox_uvmat('WARNING','inconsistent time unit with the first field series');
805            end
806            TimeUnit=XmlData.Camera.TimeUnit;
807        end
808    end
809    % number of slices
810    if isfield(XmlData,'GeometryCalib')
811        check_calib=1;
812        if isfield(XmlData.GeometryCalib,'SliceCoord')
813            siz=size(XmlData.GeometryCalib.SliceCoord);
814            if siz(1)>1
815                if iview>1 && ~isempty(NbSlice) && ~strcmp(NbSlice,siz(1))
816                    msgbox_uvmat('WARNING','inconsistent number of Z indices with the first field series');
817                end
818                NbSlice=siz(1);
819            end
820        end
821    end
822    set(handles.num_NbSlice,'String',num2str(NbSlice))
823end
824
825%% read timing and total frame number from the current file (movie files) if not already set by the xml file (prioritary)
826InputTable=get(handles.InputTable,'Data');
827
828% case of movies
829if isempty(Time)
830    if ~isempty(VideoObject)
831        imainfo=get(VideoObject);
832        if isempty(j1_series); %frame index along i
833            Time=zeros(imainfo.NumberOfFrames+1,2);
834            Time(:,2)=(0:1/imainfo.FrameRate:(imainfo.NumberOfFrames)/imainfo.FrameRate)';
835        else
836            Time=[0;ones(size(i1_series,3)-1,1)]*(0:1/imainfo.FrameRate:(imainfo.NumberOfFrames)/imainfo.FrameRate);
837        end
838        TimeSource='video';
839    end
840end
841
842%% update time table
843if ~isempty(Time)
844    TimeTable=get(handles.TimeTable,'Data');
845    TimeTable{iview,1}=Time(MinIndex_i+1,MinIndex_j+1);
846    if size(Time)>=[first_i+1 first_j+1]
847        TimeTable{iview,2}=Time(first_i+1,first_j+1);
848    end
849    if size(Time)>=[last_i+1 last_j+1]
850        TimeTable{iview,3}=Time(last_i+1,last_j+1);
851    end
852    if size(Time)>=[MaxIndex_i+1 MaxIndex_j+1];
853        TimeTable{iview,4}=Time(MaxIndex_i+1,MaxIndex_j+1);
854    end
855    set(handles.TimeTable,'Data',TimeTable)
856end
857
858%% update the series info in 'UserData'
859SeriesData=get(handles.series,'UserData');
860SeriesData.i1_series{iview}=i1_series;
861SeriesData.i2_series{iview}=i2_series;
862SeriesData.j1_series{iview}=j1_series;
863SeriesData.j2_series{iview}=j2_series;
864SeriesData.FileType{iview}=FileType;
865SeriesData.FileInfo{iview}=FileInfo;
866SeriesData.Time{iview}=Time;
867if ~isempty(TimeSource)
868    SeriesData.TimeSource=TimeSource;
869end
870% if ~isempty(TimeUnit)
871%     SeriesData.TimeUnit=TimeUnit;
872% end
873if check_calib
874    SeriesData.GeometryCalib{iview}=XmlData.GeometryCalib;
875end
876set(handles.series,'UserData',SeriesData)
877
878%% update pair menus
879ListView=get(handles.ListView,'String');
880ListView{iview}=num2str(iview);
881set(handles.ListView,'String',ListView);
882set(handles.ListView,'Value',iview)
883update_mode(handles,i1_series,i2_series,j1_series,j2_series,Time)
884
885%% enable j index visibility
886%check_jindex=~isempty(find(~cellfun(@isempty,SeriesData.j1_series))); %look for non empty j indices
887status_j='on';%default
888if isempty(find(~cellfun(@isempty,SeriesData.j1_series), 1)); % case of empty j indices
889    status_j='off'; % no j index needed
890elseif strcmp(get(handles.PairString,'Visible'),'on')
891        PairString=get(handles.PairString,'Data');       
892        check_burst=cellfun(@isempty,regexp(PairString,'^j'));%=0 for burst case, 1 otherwise
893 %   check_nopair=cellfun(@isempty,PairString);
894    if isempty(find(check_burst, 1))% if all pair string begins by j (burst)
895        status_j='off'; % no j index needed for bust case
896    end
897end
898enable_j(handles,status_j) % no j index needed
899
900%% display the set of existing files as an image
901set(handles.FileStatus,'Units','pixels')
902Position=get(handles.FileStatus,'Position');
903set(handles.FileStatus,'Units','normalized')
904xI=0.5:Position(3)-0.5;
905nbview=numel(SeriesData.i1_series);
906j_max=cell(1,nbview);
907MaxIndex_i=ones(1,nbview);%default
908MinIndex_i=ones(1,nbview);%default
909for iview=1:nbview
910    pair_max=squeeze(max(SeriesData.i1_series{iview},[],1)); %max on pair index
911    j_max{iview}=max(pair_max,[],1);%max on j index
912    MaxIndex_i(iview)=max(find(j_max{iview}))-1;% max ref index i
913    MinIndex_i(iview)=min(find(j_max{iview}))-1;% min ref index i
914%     pair_max{iview}=squeezSeriesData.i1_series{iview},[],1)); %max on pair index
915%     if (strcmp(get(handles.num_first_j,'Visible'),'off')&& size(pair_max{iview},2)~=1)
916%         pair_max{iview}=squeeze(max(pair_max{iview},[],1)); % consider only the i index
917%     end
918end
919MinIndex_i=min(MinIndex_i);
920MaxIndex_i=max(MaxIndex_i);
921range_index=MaxIndex_i-MinIndex_i+1;
922% scale_y=Position(4)/nbview;
923% scale_x=Position(3)/range_index;
924%x=(0.5:range_index-0.5)*Position(3)/range_index;% set of abscissa representing the whole i index range
925% y=(0.5:nbview-0.5)*Position(4)/nbview;
926range_y=max(1,floor(Position(4)/nbview));
927npx=floor(Position(3));
928file_indices=MinIndex_i+floor(((0.5:npx-0.5)/npx)*range_index)+1;
929CData=zeros(nbview*range_y,npx);% initiate the image representing the existing files
930for iview=1:nbview
931    ind_y=1+(iview-1)*range_y:iview*range_y;
932    LineData=zeros(size(file_indices));
933    file_select=file_indices(file_indices<=numel(j_max{iview}));
934    ind_select=find(file_indices<=numel(j_max{iview}));
935    LineData(ind_select)=j_max{iview}(file_select)~=0;
936%     LineData=zeros(1,range_index);
937%     x_index=find(j_max{iview}>0)-MinIndex_i;
938%     LineData(x_index)=1;
939%     if numel(x)>1
940%         LineData
941    %LineData=interp1(x,LineData,xI,'nearest');
942    CData(ind_y,:)=ones(size(ind_y'))*LineData;
943%     end
944end
945CData=cat(3,zeros(size(CData)),CData,zeros(size(CData)));%make color images r=0,g,b=0
946set(handles.FileStatus,'CData',CData);
947
948%% check for pair display
949check_pairs=0;
950for iview=1:numel(SeriesData.i2_series)
951    if ~isempty(SeriesData.i2_series{iview})||~isempty(SeriesData.j2_series{iview})
952        check_pairs=1;
953    end
954end
955if check_pairs
956    set(handles.Pairs,'Visible','on')
957    set(handles.PairString,'Visible','on')
958else
959    set(handles.Pairs,'Visible','off')
960    set(handles.PairString,'Visible','off')
961end
962
963
964%% enable field and veltype menus, in accordance with the current action
965ActionName_Callback([],[], handles)
966
967%% set length of waitbar
968displ_time(handles)
969
970%% set default options in menu 'Fields'
971switch FileType
972    case {'civx','civdata'}
973        [FieldList,ColorList]=set_field_list('U','V','C');
974        set(handles.FieldName,'String',[{'image'};FieldList;{'get_field...'}]);%standard menu for civx data
975        set(handles.FieldName,'Value',2) % set menu to 'velocity
976        set(handles.Coord_x,'Value',1);
977        set(handles.Coord_x,'String',{'X'});
978        set(handles.Coord_y,'Value',1);
979        set(handles.Coord_y,'String',{'Y'});
980    case 'netcdf'
981        set(handles.FieldName,'Value',1)
982        set(handles.FieldName,'String',{'get_field...'})
983        if isempty(i2_series)
984            i2=[];
985        else
986            i2=i2_series(1,ref_j+1,ref_i+1);
987        end
988        if isempty(j1_series)
989            j1=[];j2=[];
990        else
991            j1=j1_series(1,ref_j+1,ref_i+1);
992            if isempty(j2_series)
993                j2=[];
994            else
995                j2=j2_series(1,ref_j+1,ref_i+1);
996            end
997        end
998        FileName=fullfile_uvmat(InputTable{iview,1},InputTable{iview,2},InputTable{iview,3},InputTable{iview,5},InputTable{iview,4},i1_series(1,ref_j+1,ref_i+1),i2,j1,j2);
999%         hget_field=get_field(FileName);
1000%         hhget_field=guidata(hget_field);
1001%         get_field('RUN_Callback',hhget_field.RUN,[],hhget_field);
1002    otherwise
1003        set(handles.FieldName,'Value',1) % set menu to 'image'
1004        set(handles.FieldName,'String',{'image'})
1005        set(handles.Coord_x,'Value',1);
1006        set(handles.Coord_x,'String',{'AX'});
1007        set(handles.Coord_y,'Value',1);
1008        set(handles.Coord_y,'String',{'AY'});
1009end
1010
1011%------------------------------------------------------------------------
1012function num_first_i_Callback(hObject, eventdata, handles)
1013%------------------------------------------------------------------------
1014num_last_i_Callback(hObject, eventdata, handles)
1015
1016%------------------------------------------------------------------------
1017function num_last_i_Callback(hObject, eventdata, handles)
1018%------------------------------------------------------------------------
1019SeriesData=get(handles.series,'UserData');
1020if ~isfield(SeriesData,'Time')
1021    SeriesData.Time{1}=[];
1022end
1023displ_time(handles);
1024
1025%------------------------------------------------------------------------
1026function num_first_j_Callback(hObject, eventdata, handles)
1027%------------------------------------------------------------------------
1028 num_last_j_Callback(hObject, eventdata, handles)
1029
1030%------------------------------------------------------------------------
1031function num_last_j_Callback(hObject, eventdata, handles)
1032%------------------------------------------------------------------------
1033first_j=str2num(get(handles.num_first_j,'String'));
1034last_j=str2num(get(handles.num_last_j,'String'));
1035ref_j=ceil((first_j+last_j)/2);
1036set(handles.num_ref_j,'String', num2str(ref_j))
1037num_ref_j_Callback(hObject, eventdata, handles)
1038SeriesData=get(handles.series,'UserData');
1039if ~isfield(SeriesData,'Time')
1040    SeriesData.Time{1}=[];
1041end
1042displ_time(handles);
1043
1044
1045%------------------------------------------------------------------------
1046% ---- find the times corresponding to the first and last indices of a series
1047function displ_time(handles)
1048%------------------------------------------------------------------------
1049SeriesData=get(handles.series,'UserData');%
1050ref_i=[str2num(get(handles.num_first_i,'String')) str2num(get(handles.num_last_i,'String'))];
1051ref_j=[str2num(get(handles.num_first_j,'String')) str2num(get(handles.num_last_j,'String'))];
1052TimeTable=get(handles.TimeTable,'Data');
1053Pairs=get(handles.PairString,'Data');
1054for iview=1:size(TimeTable,1)
1055    if size(SeriesData.Time,1)<iview
1056        break
1057    end
1058    i1=ref_i;
1059    j1=ref_j;
1060    i2=ref_i;
1061    j2=ref_j;
1062    % case of pairs
1063    if ~isempty(Pairs{iview,1})
1064        r=regexp(Pairs{iview,1},'(?<mode>(Di=)|(Dj=)) -*(?<num1>\d+)\|(?<num2>\d+)','names');
1065        if isempty(r)
1066            r=regexp(Pairs{iview,1},'(?<num1>\d+)(?<mode>-)(?<num2>\d+)','names');
1067        end
1068        switch r.mode
1069            case 'Di='  %  case 'series(Di)')
1070                i1=ref_i-str2num(r.num1);
1071                i2=ref_i+str2num(r.num2);
1072            case 'Dj='  %  case 'series(Dj)'
1073                j1=ref_j-str2num(r.num1);
1074                j2=ref_j+str2num(r.num2);
1075            case '-'  % case 'bursts'
1076                j1=str2num(r.num1)*ones(size(ref_i));
1077                j2=str2num(r.num2)*ones(size(ref_i));
1078        end
1079    end
1080    TimeTable{iview,2}=[];
1081    TimeTable{iview,3}=[];
1082    if size(SeriesData.Time{iview},1)>=i2(2)+1&&size(SeriesData.Time{iview},2)>=j2(2)+1
1083        if isempty(ref_j)
1084            time_first=(SeriesData.Time{iview}(i1(1)+1)+SeriesData.Time{iview}(i2(1)+1))/2;
1085            time_last=(SeriesData.Time{iview}(i1(2)+1)+SeriesData.Time{iview}(i2(2))+1)/2;
1086        else
1087            time_first=(SeriesData.Time{iview}(i1(1)+1,j1(1)+1)+SeriesData.Time{iview}(i2(1)+1,j2(1)+1))/2;
1088            time_last=(SeriesData.Time{iview}(i1(2)+1,j1(2)+1)+SeriesData.Time{iview}(i2(2)+1,j2(2)+1))/2;
1089        end
1090        TimeTable{iview,2}=time_first; %TODO: take into account pairs
1091        TimeTable{iview,3}=time_last; %TODO: take into account pairs
1092    end
1093end
1094set(handles.TimeTable,'Data',TimeTable)
1095
1096%% set the waitbar position with respect to the min and max in the series
1097MinIndex_i=min(get(handles.MinIndex_i,'Data'));
1098MaxIndex_i=max(get(handles.MaxIndex_i,'Data'));
1099pos_first=(ref_i(1)-MinIndex_i)/(MaxIndex_i-MinIndex_i+1);
1100pos_last=(ref_i(2)-MinIndex_i+1)/(MaxIndex_i-MinIndex_i+1);
1101Position=get(handles.Waitbar,'Position');% position of the waitbar:= [ x,y, width, height]
1102Position_status=get(handles.FileStatus,'Position');
1103Position(1)=Position_status(1)+Position_status(3)*pos_first;
1104Position(3)=Position_status(3)*(pos_last-pos_first);
1105set(handles.Waitbar,'Position',Position)
1106update_waitbar(handles.Waitbar,0)
1107
1108% for iview=1:numel(SeriesData.i1_series)
1109%     pair_max{iview}=squeeze(max(SeriesData.i1_series{iview},[],1)); %max on pair index
1110%     if (strcmp(get(handles.num_first_j,'Visible'),'off')&& size(pair_max{iview},2)~=1)
1111%         pair_max{iview}=squeeze(max(pair_max{iview},[],1)); % consider only the i index
1112%     end
1113%     pair_max{iview}=reshape(pair_max{iview},1,[]);
1114%     index_min(iview)=find(pair_max{iview}>0, 1 );
1115%     index_max(iview)=find(pair_max{iview}>0, 1, 'last' );
1116% end
1117% [index_min,iview_min]=min(index_min);
1118% [index_max,iview_max]=min(index_max);
1119% if size(SeriesData.i1_series{iview_min},2)==1% movie
1120%     index_first=ref_i(1);
1121%     index_last=ref_i(2);
1122% else
1123%     index_first=(ref_i(1)-1)*(size(SeriesData.i1_series{iview_min},1))+ref_j(1)+1;
1124%     index_last=(ref_i(2)-1)*(size(SeriesData.i1_series{iview_max},1))+ref_j(2)+1;
1125% end
1126% range=index_max-index_min+1;
1127% coeff_min=(index_first-index_min)/range;
1128% coeff_max=(index_last-index_min+1)/range;
1129% Position=get(handles.Waitbar,'Position');% position of the waitbar:= [ x,y, width, height]
1130% Position_status=get(handles.FileStatus,'Position');
1131% Position(1)=coeff_min*Position_status(3)+Position_status(1);
1132% Position(3)=Position_status(3)*(coeff_max-coeff_min);
1133% set(handles.Waitbar,'Position',Position)
1134% update_waitbar(handles.Waitbar,0)
1135
1136%------------------------------------------------------------------------
1137% --- Executes when selected cell(s) is changed in PairString.
1138function PairString_CellSelectionCallback(hObject, eventdata, handles)
1139%------------------------------------------------------------------------   
1140set(handles.ListView,'Value',eventdata.Indices(1))% detect the selected raw index
1141ListView_Callback ([],[],handles) % update the list of available pairs
1142
1143%------------------------------------------------------------------------
1144%------------------------------------------------------------------------
1145%  III - FUNCTIONS ASSOCIATED TO THE FRAME SET PAIRS
1146%------------------------------------------------------------------------
1147%------------------------------------------------------------------------
1148% --- Executes on selection change in ListView.
1149function ListView_Callback(hObject, eventdata, handles)
1150%------------------------------------------------------------------------   
1151SeriesData=get(handles.series,'UserData');
1152i2_series=[];
1153j2_series=[];
1154iview=get(handles.ListView,'Value');
1155if ~isempty(SeriesData.i2_series{iview})
1156    i2_series=SeriesData.i2_series{iview};
1157end
1158if ~isempty(SeriesData.j2_series{iview})
1159    j2_series=SeriesData.j2_series{iview};
1160end
1161update_mode(handles,SeriesData.i1_series{iview},SeriesData.i2_series{iview},...
1162    SeriesData.j1_series{iview},SeriesData.j2_series{iview},SeriesData.Time{iview})
1163
1164%------------------------------------------------------------------------
1165% --- Executes on button press in mode.
1166function mode_Callback(hObject, eventdata, handles)
1167%------------------------------------------------------------------------       
1168SeriesData=get(handles.series,'UserData');
1169iview=get(handles.ListView,'Value');
1170mode_list=get(handles.mode,'String');
1171mode=mode_list{get(handles.mode,'Value')};
1172if isequal(mode,'bursts')
1173    enable_i(handles,'On')
1174    enable_j(handles,'Off') %do not display j index scanning in burst mode (j is fixed by the burst choice)
1175else
1176    enable_i(handles,'On')
1177    enable_j(handles,'Off')
1178end
1179fill_ListPair(handles,SeriesData.i1_series{iview},SeriesData.i2_series{iview},...
1180    SeriesData.j1_series{iview},SeriesData.j2_series{iview},SeriesData.Time{iview})
1181ListPairs_Callback([],[],handles)
1182
1183%-------------------------------------------------------------
1184% --- Executes on selection in ListPairs.
1185function ListPairs_Callback(hObject,eventdata,handles)
1186%------------------------------------------------------------
1187list_pair=get(handles.ListPairs,'String');%get the menu of image pairs
1188if isempty(list_pair)
1189    string='';
1190else
1191    string=list_pair{get(handles.ListPairs,'Value')};
1192    string=regexprep(string,',.*','');%removes time indication (after ',')
1193end
1194PairString=get(handles.PairString,'Data');
1195iview=get(handles.ListView,'Value');
1196PairString{iview,1}=string;
1197% report the selected pair string to the table PairString
1198set(handles.PairString,'Data',PairString)
1199
1200%------------------------------------------------------------------------
1201function num_ref_i_Callback(hObject, eventdata, handles)
1202%------------------------------------------------------------------------
1203mode_list=get(handles.mode,'String');
1204mode=mode_list{get(handles.mode,'Value')};
1205SeriesData=get(handles.series,'UserData');
1206iview=get(handles.ListView,'Value');
1207fill_ListPair(handles,SeriesData.i1_series{iview},SeriesData.i2_series{iview},...
1208    SeriesData.j1_series{iview},SeriesData.j2_series{iview},SeriesData.Time{iview});% update the menu of pairs depending on the available netcdf files
1209ListPairs_Callback([],[],handles)
1210
1211%------------------------------------------------------------------------
1212function num_ref_j_Callback(hObject, eventdata, handles)
1213%------------------------------------------------------------------------
1214num_ref_i_Callback(hObject, eventdata, handles)
1215
1216%------------------------------------------------------------------------
1217function update_mode(handles,i1_series,i2_series,j1_series,j2_series,time)
1218%------------------------------------------------------------------------   
1219% check_burst=0;
1220if isempty(j2_series)% no j pair
1221    if isempty(i2_series)
1222        set(handles.mode,'Value',1)
1223        set(handles.mode,'String',{''})% no pair menu to display
1224    else   
1225        set(handles.mode,'Value',1)
1226        set(handles.mode,'String',{'series(Di)'}) % pair menu with only option Di
1227    end
1228else %existence of j pairs
1229    pair_max=squeeze(max(i1_series,[],1)); %max on pair index
1230    j_max=max(pair_max,[],1);
1231    MaxIndex_i=max(find(j_max))-1;% max ref index i
1232    MinIndex_i=min(find(j_max))-1;% min ref index i
1233    i_max=max(pair_max,[],2);
1234    MaxIndex_j=max(find(i_max))-1;% max ref index i
1235    MinIndex_j=min(find(i_max))-1;% min ref index i
1236    if MaxIndex_j==MinIndex_j
1237        set(handles.mode,'Value',1);
1238        set(handles.mode,'String',{'bursts'})
1239%         check_burst=1;
1240    elseif MaxIndex_i==MinIndex_i
1241        set(handles.mode,'Value',1);
1242        set(handles.mode,'String',{'series(Dj)'})
1243    else
1244        set(handles.mode,'String',{'bursts';'series(Dj)'})
1245        if (MaxIndex_j-MinIndex_j)>10
1246            set(handles.mode,'Value',2);%set mode to series(Dj) if more than 10 j values
1247        else
1248            set(handles.mode,'Value',1);
1249%             check_burst=1;
1250        end
1251    end
1252end
1253fill_ListPair(handles,i1_series,i2_series,j1_series,j2_series,time)
1254ListPairs_Callback([],[],handles)
1255
1256%--------------------------------------------------------------
1257% determine the menu for pairstring depending on existing netcdf files
1258% with the reference indices num_ref_i and num_ref_j
1259%----------------------------------------------------------------
1260function fill_ListPair(handles,i1_series,i2_series,j1_series,j2_series,time)
1261
1262mode_list=get(handles.mode,'String');
1263mode=mode_list{get(handles.mode,'Value')};
1264ref_i=str2num(get(handles.num_ref_i,'String'));
1265if isempty(ref_i)
1266    ref_i=1;
1267end
1268if strcmp(get(handles.num_ref_j,'Visible'),'on')
1269    ref_j=str2num(get(handles.num_ref_j,'String'));
1270    if isempty(ref_j)
1271        ref_j=1;
1272    end
1273else
1274    ref_j=1;
1275end
1276TimeUnit=get(handles.TimeUnit,'String');
1277if length(TimeUnit)>=1
1278    dtunit=['m' TimeUnit];
1279else
1280    dtunit='e-03';
1281end
1282
1283displ_pair={};
1284if strcmp(mode,'series(Di)')
1285    if isempty(i2_series)
1286        msgbox_uvmat('ERROR','no i1-i2 pair available')
1287        return
1288    end
1289    diff_i=i2_series-i1_series;
1290    min_diff=min(diff_i(diff_i>0));
1291    max_diff=max(diff_i(diff_i>0));
1292    for ipair=min_diff:max_diff
1293        if numel(diff_i(diff_i==ipair))>0
1294            pair_string=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
1295            if ~isempty(time)
1296                if ref_i<=floor(ipair/2)
1297                    ref_i=floor(ipair/2)+1;% shift ref_i to get the first pair
1298                end
1299                Dt=time(ref_i+ceil(ipair/2),ref_j)-time(ref_i-floor(ipair/2),ref_j);
1300                pair_string=[pair_string ', Dt=' num2str(Dt) ' ' dtunit];
1301            end
1302            displ_pair=[displ_pair;{pair_string}];
1303        end
1304    end
1305    if ~isempty(displ_pair)
1306        displ_pair=[displ_pair;{'Di=*|*'}];
1307    end
1308elseif strcmp(mode,'series(Dj)')
1309    if isempty(j2_series)
1310        msgbox_uvmat('ERROR','no j1-j2 pair available')
1311        return
1312    end
1313    diff_j=j2_series-j1_series;
1314    min_diff=min(diff_j(diff_j>0));
1315    max_diff=max(diff_j(diff_j>0));
1316    for ipair=min_diff:max_diff
1317        if numel(diff_j(diff_j==ipair))>0
1318            pair_string=['Dj= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
1319            if ~isempty(time)
1320                if ref_j<=floor(ipair/2)
1321                    ref_j=floor(ipair/2)+1;% shift ref_i to get the first pair
1322                end
1323                Dt=time(ref_i,ref_j+ceil(ipair/2))-time(ref_i,ref_j-floor(ipair/2));
1324                pair_string=[pair_string ', Dt=' num2str(Dt) ' ' dtunit];
1325            end
1326            displ_pair=[displ_pair;{pair_string}];
1327        end
1328    end
1329    if ~isempty(displ_pair)
1330        displ_pair=[displ_pair;{'Dj=*|*'}];
1331    end
1332elseif strcmp(mode,'bursts')
1333    if isempty(j2_series)
1334        msgbox_uvmat('ERROR','no j1-j2 pair available')
1335        return
1336    end
1337    diff_j=j2_series-j1_series;
1338    min_j1=min(j1_series(j1_series>0));
1339    max_j1=max(j1_series(j1_series>0));
1340    min_j2=min(j2_series(j2_series>0));
1341    max_j2=max(j2_series(j2_series>0));
1342    for pair1=min_j1:min(max_j1,min_j1+20)
1343        for pair2=min_j2:min(max_j2,min_j2+20)
1344        if numel(j1_series(j1_series==pair1))>0 && numel(j2_series(j2_series==pair2))>0
1345            displ_pair=[displ_pair;{['j= ' num2str(pair1) '-' num2str(pair2)]}];
1346        end
1347        end
1348    end
1349    if ~isempty(displ_pair)
1350        displ_pair=[displ_pair;{'j=*-*'}];
1351    end
1352end
1353set(handles.num_ref_i,'String',num2str(ref_i)) % update ref_i and ref_j
1354set(handles.num_ref_j,'String',num2str(ref_j))
1355
1356%% display list of pairstring
1357displ_pair_list=get(handles.ListPairs,'String');
1358NewVal=[];
1359if ~isempty(displ_pair_list)
1360Val=get(handles.ListPairs,'Value');
1361NewVal=find(strcmp(displ_pair_list{Val},displ_pair),1);% look at the previous display in the new menu displ_pï¿œir
1362end
1363if ~isempty(NewVal)
1364    set(handles.ListPairs,'Value',NewVal)
1365else
1366    set(handles.ListPairs,'Value',1)
1367end
1368set(handles.ListPairs,'String',displ_pair)
1369
1370%-------------------------------------
1371function enable_i(handles,state)
1372set(handles.i_txt,'Visible',state)
1373set(handles.num_first_i,'Visible',state)
1374set(handles.num_last_i,'Visible',state)
1375set(handles.num_incr_i,'Visible',state)
1376set(handles.num_ref_i,'Visible',state)
1377set(handles.ref_i_text,'Visible',state)
1378
1379%-----------------------------------
1380function enable_j(handles,state)
1381set(handles.j_txt,'Visible',state)
1382set(handles.num_first_j,'Visible',state)
1383set(handles.num_last_j,'Visible',state)
1384set(handles.num_incr_j,'Visible',state)
1385set(handles.num_ref_j,'Visible',state)
1386set(handles.ref_j_text,'Visible',state)
1387set(handles.MinIndex_j,'Visible',state)
1388set(handles.MaxIndex_j,'Visible',state)
1389
1390
1391%%%%%%%%%%%%%%%%%%%%
1392%%  MAIN ActionName FUNCTIONS
1393%%%%%%%%%%%%%%%%%%%%
1394%------------------------------------------------------------------------
1395% --- Executes on button press in RUN.
1396%------------------------------------------------------------------------
1397function RUN_Callback(hObject, eventdata, handles)
1398
1399%% settings of the button RUN
1400set(handles.RUN,'BusyAction','queue');% activation of STOP button will set BusyAction to 'cancel'
1401%set(0,'CurrentFigure',handles.series); % display the GUI series
1402set(handles.RUN, 'Enable','Off')% avoid further RUN action until the current one is finished
1403set(handles.RUN,'BackgroundColor',[1 1 0])%show activation of RUN by yellow color
1404drawnow
1405set(handles.status,'Value',0)% desable status display if relevant
1406status_Callback(hObject, eventdata, handles)
1407
1408%% read the data on the GUI series
1409Param=read_GUI_series(handles);%displayed parameters
1410SeriesData=get(handles.series,'UserData');%hidden parameters
1411
1412%% create the output data directory if needed
1413if isfield(Param,'OutputSubDir')
1414    SubDirOut=[get(handles.OutputSubDir,'String') Param.OutputDirExt];
1415    SubDirOutNew=SubDirOut;
1416    detect=exist(fullfile(Param.InputTable{1,1},SubDirOutNew),'dir');% test if  the dir  already exist
1417    check_create=1; %need to create the result directory by default
1418    while detect
1419        answer=msgbox_uvmat('INPUT_Y-N',['use existing ouput directory: ' fullfile(Param.InputTable{1,1},SubDirOutNew) ', possibly delete previous data']);
1420        if strcmp(answer,'Cancel')
1421            errormsg='Cancel';
1422            return
1423        elseif strcmp(answer,'Yes')
1424            detect=0;
1425            check_create=0;
1426        else
1427            r=regexp(SubDirOutNew,'(?<root>.*\D)(?<num1>\d+)$','names');%detect whether name ends by a number
1428            if isempty(r)
1429                r(1).root=[SubDirOutNew '_'];
1430                r(1).num1='0';
1431            end
1432            SubDirOutNew=[r(1).root num2str(str2num(r(1).num1)+1)];%increment the index by 1 or put 1
1433            detect=exist(fullfile(Param.InputTable{1,1},SubDirOutNew),'dir');% test if  the dir  already exists
1434            check_create=1;
1435        end
1436    end
1437    Param.OutputDirExt=regexprep(SubDirOutNew,Param.OutputSubDir,'');
1438    Param.OutputRootFile=Param.InputTable{1,3};% the first sorted RootFile taken for output
1439    set(handles.OutputDirExt,'String',Param.OutputDirExt)
1440    OutputDir=fullfile(Param.InputTable{1,1},[Param.OutputSubDir Param.OutputDirExt]);% full name (with path) of output directory
1441    if check_create    % create output directory if it does not exist
1442        [tild,msg1]=mkdir(OutputDir);
1443        if ~strcmp(msg1,'')
1444            errormsg=['cannot create ' OutputDir ': ' msg1];%error message for directory creation
1445            return
1446        end
1447    end
1448    OutputNomType=nomtype2pair(Param.InputTable{1,4});% nomenclature for output files
1449    DirXml=fullfile(OutputDir,'0_XML');
1450    if ~exist(DirXml,'dir')
1451        [tild,msg1]=mkdir(DirXml);
1452        if ~strcmp(msg1,'')
1453            msgbox_uvmat('ERROR',['cannot create ' DirXml ': ' msg1]);%error message for directory creation
1454            return
1455        end
1456    end
1457end
1458
1459%% select the Action mode, 'local', 'background' or 'cluster' (if available)
1460RunMode='local';%default (needed for first opening of the GUI series)
1461if isfield(Param.Action,'RunMode')
1462    RunMode=Param.Action.RunMode;
1463end
1464ActionExt='.m';%default
1465if isfield(Param.Action,'ActionExt')
1466    ActionExt=Param.Action.ActionExt;% '.m' or '.sh' (compiled)
1467end
1468ActionName=Param.Action.ActionName;
1469ActionPath=Param.Action.ActionPath;
1470path_series=fileparts(which('series'));
1471
1472%% create the Action fct handle if RunMode option = 'local'
1473if strcmp(RunMode,'local')
1474    if ~isequal(ActionPath,path_series)
1475        eval(['spath=which(''' ActionName ''');']) %spath = current path of the selected function ACTION
1476        if ~exist(ActionPath,'dir')
1477            msgbox_uvmat('ERROR',['The prescribed function path ' ActionPath ' does not exist']);
1478            return
1479        end
1480        if ~isequal(spath,ActionPath)
1481            addpath(ActionPath)% add the prescribed path if not the current one
1482        end
1483    end
1484    eval(['h_fun=@' ActionName ';'])%create a function handle for ACTION
1485    if ~isequal(ActionPath,path_series)
1486        rmpath(ActionPath)% add the prescribed path if not the current one
1487    end
1488end
1489
1490%% Get RunTime code from the file PARAM.xml (needed to run compiled functions)
1491errormsg='';%default error message
1492xmlfile=fullfile(path_series,'PARAM.xml');
1493test_batch=0;%default: ,no batch mode available
1494if ~exist(xmlfile,'file')
1495    [success,message]=copyfile(fullfile(path_series,'PARAM.xml.default'),xmlfile);
1496end
1497RunTime='';
1498if strcmp(ActionExt,'.sh')
1499    if exist(xmlfile,'file')
1500        s=xml2struct(xmlfile);
1501        if strcmp(RunMode,'cluster_oar') && isfield(s,'BatchParam')
1502            if isfield(s.BatchParam,'RunTime')
1503                RunTime=s.BatchParam.RunTime;
1504            end
1505            if isfield(s.BatchParam,'NbCore')
1506                NbCore=s.BatchParam.NbCore;
1507            end
1508        elseif (strcmp(RunMode,'background')||strcmp(RunMode,'local')) && isfield(s,'RunParam')
1509            if isfield(s.RunParam,'RunTime')
1510                RunTime=s.RunParam.RunTime;
1511            end
1512            if isfield(s.RunParam,'NbCore')
1513                NbCore=s.RunParam.NbCore;
1514            end
1515        end
1516    end
1517    if isempty(RunTime) && strcmp(RunMode,'cluster_oar')
1518        msgbox_uvmat('ERROR','RunTime name not found in PARAM.xml, compiled version .sh cannot run on cluster')
1519        return
1520    end
1521end
1522
1523%% set nbre of cluster cores and processes
1524switch RunMode
1525    case {'local','background'}
1526        NbCore=1;% no need to split the calculation
1527    case 'cluster_oar'
1528        if strcmp(Param.Action.ActionExt,'.m')% case of Matlab function (uncompiled)
1529            NbCore=1;% one core used only (limitation of Matlab licences)
1530            msgbox_uvmat('WARNING','Number of cores =1: select the compiled version civ_matlab.sh for multi-core processing');
1531            extra_oar='';
1532        else
1533            answer=inputdlg({'Number of cores (max 36)','extra oar options'},'oarsub parameter',1,{'12',''});
1534            NbCore=str2double(answer{1});
1535            extra_oar=answer{2};
1536        end
1537end
1538if ~isfield(Param.IndexRange,'NbSlice')
1539    Param.IndexRange.NbSlice=[];
1540end
1541if isempty(Param.IndexRange.NbSlice)
1542    NbProcess=NbCore;% choose one process per core
1543else
1544    NbProcess=Param.IndexRange.NbSlice;% the nbre of run processes is equal to the number of slices
1545    NbCore=min(NbCore,NbProcess);% at least one process per core
1546end
1547       
1548%% get the set of reference field indices
1549first_i=1;
1550last_i=1;
1551incr_i=1;
1552first_j=1;
1553last_j=1;
1554incr_j=1;
1555if isfield(Param.IndexRange,'first_i')
1556    first_i=Param.IndexRange.first_i;
1557    incr_i=Param.IndexRange.incr_i;
1558    last_i=Param.IndexRange.last_i;
1559end
1560if isfield(Param.IndexRange,'first_j')
1561    first_j=Param.IndexRange.first_j;
1562    last_j=Param.IndexRange.last_j;
1563    incr_j=Param.IndexRange.incr_j;
1564end
1565if last_i < first_i || last_j < first_j
1566    msgbox_uvmat('ERROR', 'series/Run_Callback:last field index must be larger or equal to the first one')
1567    set(handles.RUN, 'Enable','On'),
1568    set(handles.RUN,'BackgroundColor',[1 0 0])
1569    return
1570end
1571%incr_i must be defined, =1 by default, if NbSlice is active
1572if isempty(incr_i)&& ~isempty(Param.IndexRange.NbSlice)
1573    incr_i=1;
1574    set(handles.num_incr_i,'String','1')
1575end
1576if isempty(incr_i)
1577    if isempty(incr_j)
1578        [ref_j,ref_i]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1579        ref_j=ref_j(ref_j>=first_j & ref_j<=last_j);
1580        ref_i=ref_i(ref_i>=first_i & ref_i<=last_i);
1581        ref_j=ref_j-1;
1582        ref_i=ref_i-1;
1583    else
1584        ref_j=first_j:incr_j:last_j;
1585        [tild,ref_i]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1586        ref_i=ref_i-1;
1587        ref_i=ref_i(ref_i>=first_i & ref_i<=last_i);
1588    end
1589else
1590    ref_i=first_i:incr_i:last_i;
1591    if isempty(incr_j)
1592    [ref_j,tild]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1593    ref_j=ref_j-1;
1594    ref_j=ref_j(ref_j>=first_j & ref_j<=last_j);
1595    else
1596        ref_j=first_j:incr_j:last_j;
1597    end
1598end
1599BlockLength=ceil(numel(ref_i)/NbProcess);
1600nbfield_j=numel(ref_j);
1601
1602%% record nbre of output files and starting time for computation for status
1603StatusData=get(handles.status,'UserData');
1604if isfield(StatusData,'OutputFileMode')
1605    switch StatusData.OutputFileMode
1606        case 'NbInput'
1607            StatusData.NbOutputFile=numel(ref_i)*nbfield_j;
1608        case 'NbInput_i'
1609            StatusData.NbOutputFile=numel(ref_i);
1610        case 'NbSlice'   
1611            StatusData.NbOutputFile=str2num(get(handles.num_NbSlice,'String'));
1612    end
1613end
1614StatusData.TimeStart=now;
1615set(handles.status,'UserData',StatusData)
1616
1617%% direct processing on the current Matlab session
1618if strcmp (RunMode,'local')
1619    for iprocess=1:NbProcess
1620        if isempty(Param.IndexRange.NbSlice)
1621            %Param.IndexRange.first_i=first_i+(iprocess-1)*BlockLength*incr_i;
1622            Param.IndexRange.first_i=ref_i(1+(iprocess-1)*BlockLength);
1623            if Param.IndexRange.first_i>last_i
1624                break
1625            end
1626            Param.IndexRange.last_i=min(ref_i(iprocess*BlockLength),last_i);
1627            %Param.IndexRange.last_i=min(first_i+(iprocess)*BlockLength*incr_i-1,last_i);
1628        else %multislices (then incr_i is not empty)
1629             Param.IndexRange.first_i= first_i+incr_i*(iprocess-1);
1630             Param.IndexRange.incr_i=incr_i*Param.IndexRange.NbSlice;
1631        end
1632        if isfield(Param,'OutputSubDir')
1633        t=struct2xml(Param);
1634        t=set(t,1,'name','Series');
1635        filexml=fullfile_uvmat(DirXml,'',Param.InputTable{1,3},'.xml',OutputNomType,...
1636            Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1637        save(t,filexml);
1638        end
1639        switch ActionExt
1640            case '.m'
1641                h_fun(Param);
1642            case '.sh'
1643                switch computer
1644                    case {'PCWIN','PCWIN64'} %Windows system
1645                        filexml=regexprep(filexml,'\\','\\\\');% add '\' so that '\' are left as characters
1646                        system([fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml]);% TODO: adapt to DOS system
1647                    case {'GLNX86','GLNXA64','MACI64'}%Linux  system
1648                        system([fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml]);
1649                end
1650        end
1651    end
1652elseif strcmp(get(handles.OutputDirExt,'Visible'),'off')
1653    msgbox_uvmat('ERROR',['no output file for Action ' ActionName ', use run mode = local']);% a output dir is needed for background option
1654    return
1655else
1656    %% processing on a different session of the same computer (background) or cluster, create executable files
1657    batch_file_list=cell(NbProcess,1);% initiate the list of executable files
1658    DirBat=fullfile(OutputDir,'0_EXE');
1659    switch computer
1660        case {'PCWIN','PCWIN64'} %Windows system
1661            ExeExt='.bat';
1662        case {'GLNX86','GLNXA64','MACI64'}%Linux  system
1663           ExeExt='.sh';
1664    end
1665    %create subdirectory for executable files
1666    if ~exist(DirBat,'dir')
1667        [tild,msg1]=mkdir(DirBat);
1668        if ~strcmp(msg1,'')
1669            msgbox_uvmat('ERROR',['cannot create ' DirBat ': ' msg1]);%error message for directory creation
1670            return
1671        end
1672    end
1673    %create subdirectory for log files
1674    DirLog=fullfile(OutputDir,'0_LOG');
1675    if ~exist(DirLog,'dir')
1676        [tild,msg1]=mkdir(DirLog);
1677        if ~strcmp(msg1,'')
1678            msgbox_uvmat('ERROR',['cannot create ' DirLog ': ' msg1]);%error message for directory creation
1679            return
1680        end
1681    end
1682    for iprocess=1:NbProcess
1683        if isempty(Param.IndexRange.NbSlice)% process by blocks of i index
1684            Param.IndexRange.first_i=first_i+(iprocess-1)*BlockLength*incr_i;
1685            if Param.IndexRange.first_i>last_i
1686                NbProcess=iprocess-1;
1687                break% leave the loop, we are at the end of the calculation
1688            end
1689            Param.IndexRange.last_i=min(last_i,first_i+(iprocess)*BlockLength*incr_i-1);
1690        else% process by slices of i index if NbSlice is defined, computation in a single process if NbSlice =1
1691            Param.IndexRange.first_i= first_i+iprocess-1;
1692            Param.IndexRange.incr_i=incr_i*Param.IndexRange.NbSlice;
1693        end
1694       
1695        % create, fill and save the xml parameter file
1696        t=struct2xml(Param);
1697        t=set(t,1,'name','Series');
1698        filexml=fullfile_uvmat(DirXml,'',Param.InputTable{1,3},'.xml',OutputNomType,...
1699            Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1700        save(t,filexml);% save the parameter file
1701       
1702        %create the executable file
1703         filebat=fullfile_uvmat(DirBat,'',Param.InputTable{1,3},ExeExt,OutputNomType,...
1704           Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1705        batch_file_list{iprocess}=filebat;
1706        [fid,message]=fopen(filebat,'w');% create the executable file
1707        if isequal(fid,-1)
1708            msgbox_uvmat('ERROR', ['creation of .bat file: ' message]);
1709            return
1710        end
1711       
1712        % set the log file name
1713        filelog=fullfile_uvmat(DirLog,'',Param.InputTable{1,3},'.log',OutputNomType,...
1714            Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1715       
1716        % fill and save the executable file
1717        switch ActionExt
1718            case '.m'% Matlab function
1719                switch computer
1720                    case {'GLNX86','GLNXA64','MACI64'}
1721                        cmd=[...
1722                            '#!/bin/bash \n'...
1723                            '. /etc/sysprofile \n'...
1724                            'matlab -nodisplay -nosplash -nojvm -logfile ''' filelog ''' <<END_MATLAB \n'...
1725                            'addpath(''' path_series '''); \n'...
1726                            'addpath(''' Param.Action.ActionPath '''); \n'...
1727                            '' Param.Action.ActionName  '( ''' filexml '''); \n'...
1728                            'exit \n'...
1729                            'END_MATLAB \n'];
1730                        fprintf(fid,cmd);%fill the executable file with the  char string cmd
1731                        fclose(fid);% close the executable file
1732                        system(['chmod +x ' filebat]);% set the file to executable
1733                    case {'PCWIN','PCWIN64'}
1734                        text_matlabscript=['matlab -automation -logfile ' regexprep(filelog,'\\','\\\\')...
1735                            ' -r "addpath(''' regexprep(path_series,'\\','\\\\') ''');'...
1736                            'addpath(''' regexprep(Param.Action.ActionPath,'\\','\\\\') ''');'...
1737                            '' Param.Action.ActionName  '( ''' regexprep(filexml,'\\','\\\\') ''');exit"'];
1738                        fprintf(fid,text_matlabscript);%fill the executable file with the  char string cmd
1739                        fclose(fid);% close the executable file
1740                end
1741            case '.sh' % compiled Matlab function
1742                switch computer
1743                    case {'GLNX86','GLNXA64','MACI64'}
1744                        cmd=['#!/bin/bash \n '...
1745                            '#$ -cwd \n '...
1746                            'hostname && date \n '...
1747                            'umask 002 \n'...
1748                            fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml];%allow writting access to created files for user group
1749                        fprintf(fid,cmd);%fill the executable file with the  char string cmd
1750                        fclose(fid);% close the executable file
1751                        system(['chmod +x ' filebat]);% set the file to executable
1752                       
1753                    case {'PCWIN','PCWIN64'}    %       TODO: adapt to Windows system
1754                        %                                 cmd=['matlab -automation -logfile ' regexprep(filelog,'\\','\\\\')...
1755                        %                                     ' -r "addpath(''' regexprep(path_series,'\\','\\\\') ''');'...
1756                        %                                     'addpath(''' regexprep(Param.Action.ActionPath,'\\','\\\\') ''');'...
1757                        %                                     '' Param.Action.ActionName  '( ''' regexprep(filexml,'\\','\\\\') ''');exit"'];
1758                        fprintf(fid,cmd);
1759                        fclose(fid);
1760                        %                               dos([filebat ' &']);
1761                end
1762        end
1763    end
1764end
1765
1766%% launch the executable files for background or cluster processing
1767switch RunMode
1768    case 'background'
1769        for iprocess=1:NbProcess
1770            system([batch_file_list{iprocess} ' &'])% directly execute the command file for each process
1771        end
1772    case 'cluster_oar' % option 'oar-parexec' used
1773        %create subdirectory for oar command and log files
1774        DirOAR=fullfile(OutputDir,'0_OAR');
1775        if exist(DirOAR,'dir')% delete the content of the dir 0_OAR to allow new input
1776            curdir=pwd;
1777            cd(DirOAR)
1778            delete('*')
1779            cd(curdir)
1780        else
1781            [tild,msg1]=mkdir(DirOAR);
1782            if ~strcmp(msg1,'')
1783                msgbox_uvmat('ERROR',['cannot create ' DirOAR ': ' msg1]);%error message for directory creation
1784                return
1785            end
1786        end
1787        max_walltime=3600*12; % 12h max total calculation
1788        walltime_onejob=600;%seconds, max estimated time for asingle file index value
1789        filename_joblist=fullfile(DirOAR,'job_list.txt');%create name of the global executable file
1790        fid=fopen(filename_joblist,'w');
1791        for p=1:length(batch_file_list)
1792            fprintf(fid,[batch_file_list{p} '\n']);% list of exe files
1793        end
1794        fclose(fid);
1795        system(['chmod +x ' filename_joblist]);% set the file to executable
1796        oar_command=['oarsub -n CIVX '...
1797            '-t idempotent --checkpoint ' num2str(walltime_onejob+60) ' '...
1798            '-l /core=' num2str(NbCore) ','...
1799            'walltime=' datestr(min(1.05*walltime_onejob/86400*max(NbProcess*BlockLength*nbfield_j,NbCore)/NbCore,max_walltime/86400),13) ' '...
1800            '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
1801            '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
1802            extra_oar ' '...
1803            '"oar-parexec -s -f ' filename_joblist ' '...
1804            '-l ' filename_joblist '.log"\n'];
1805        filename_oarcommand=fullfile(DirOAR,'oar_command');
1806        fid=fopen(filename_oarcommand,'w');
1807        fprintf(fid,oar_command);
1808        fclose(fid);
1809        fprintf(oar_command);% display in command line
1810        %system(['chmod +x ' oar_command]);% set the file to executable
1811        system(oar_command);     
1812end
1813
1814%% reset the GUI series
1815update_waitbar(handles.Waitbar,1); % put the waitbar to end position to indicate launching is finished
1816set(handles.RUN, 'Enable','On')
1817set(handles.RUN,'BackgroundColor',[1 0 0])
1818set(handles.RUN, 'Value',0)
1819
1820%------------------------------------------------------------------------
1821function STOP_Callback(hObject, eventdata, handles)
1822%------------------------------------------------------------------------
1823set(handles.RUN, 'BusyAction','cancel')
1824set(handles.RUN,'BackgroundColor',[1 0 0])
1825set(handles.RUN,'enable','on')
1826set(handles.RUN, 'Value',0)
1827
1828% %------------------------------------------------------------------------
1829% % --- Executes on button press in BIN.
1830% function BIN_Callback(hObject, eventdata, handles)
1831% %------------------------------------------------------------------------
1832%     cmd=['#!/bin/bash \n '...
1833%         '#$ -cwd \n '...
1834%         'hostname && date \n '...
1835%         'umask 002 \n'...
1836%         Param.xml.CivmBin ' ' Param.xml.RunTime ' ' filename_xml ' ' OutputFile '.nc'];
1837%     
1838%------------------------------------------------------------------------
1839% --- Main launch command, called by RUN and BATCH
1840
1841%------------------------------------------------------------------------
1842% --- read parameters from the GUI series
1843%------------------------------------------------------------------------
1844function Param=read_GUI_series(handles)
1845
1846%% read raw parameters from the GUI series
1847Param=read_GUI(handles.series);
1848
1849%% clean the output structure by removing unused information
1850if isfield(Param,'Pairs')
1851    Param=rmfield(Param,'Pairs'); %info Pairs not needed for output
1852end
1853Param.IndexRange=rmfield(Param.IndexRange,'TimeTable');
1854empty_line=false(size(Param.InputTable,1),1);
1855for iline=1:size(Param.InputTable,1)
1856    empty_line(iline)=isempty(cell2mat(Param.InputTable(iline,1:3)));
1857end
1858Param.InputTable(empty_line,:)=[];
1859
1860%------------------------------------------------------------------------
1861% --- Executes on selection change in ActionName.
1862function ActionName_Callback(hObject, eventdata, handles)
1863%------------------------------------------------------------------------
1864%% stop any ongoing series processing
1865if isequal(get(handles.RUN,'Value'),1)
1866    answer= msgbox_uvmat('INPUT_Y-N','stop current Action process?');
1867    if strcmp(answer,'Yes')
1868        STOP_Callback(hObject, eventdata, handles)
1869    else
1870        return
1871    end
1872end
1873set(handles.ActionName,'BackgroundColor',[1 1 0])
1874huigetfile=findobj(allchild(0),'tag','status_display');
1875if ~isempty(huigetfile)
1876    delete(huigetfile)
1877end
1878drawnow
1879
1880%% get Action name and path
1881nb_builtin_ACTION=4; %nbre of functions initially proposed in the menu ActionName (as defined in the Opening fct of series)
1882ActionList=get(handles.ActionName,'String');% list menu fields
1883ActionIndex=get(handles.ActionName,'Value');
1884if ~isequal(ActionIndex,1)% if we are not just opening series
1885    InputTable=get(handles.InputTable,'Data');
1886    if isempty(InputTable{1,4})
1887        msgbox_uvmat('ERROR','no input file available: use Open in the menu bar')
1888        return
1889    end
1890end
1891ActionName= ActionList{get(handles.ActionName,'Value')}; % selected function name
1892ActionPathList=get(handles.ActionName,'UserData');%list of recorded paths to functions of the list ActionName
1893
1894%% add a new function to the menu if 'more...' has been selected in the menu ActionName
1895if isequal(ActionName,'more...')
1896    [FileName, PathName] = uigetfile( ...
1897        {'*.m', ' (*.m)';
1898        '*.m',  '.m files '; ...
1899        '*.*', 'All Files (*.*)'}, ...
1900        'Pick a series processing function ',get(handles.ActionPath,'String'));
1901    if length(FileName)<2
1902        return
1903    end
1904    [ActionPath,ActionName,ActionExt]=fileparts(FileName);
1905   
1906    % insert the choice in the menu ActionName
1907    ActionIndex=find(strcmp(ActionName,ActionList),1);% look for the selected function in the menu Action
1908    if isempty(ActionIndex)%the input string does not exist in the menu
1909        ActionIndex= length(ActionList);
1910        ActionList=[ActionList(1:end-1);{ActionName};ActionList(end)];% the selected function is appended in the menu, before the last item 'more...'
1911        set(handles.ActionName,'String',ActionList)
1912    end
1913   
1914    % record the file extension and extend the path list if it is a new extension
1915    ActionExtList=get(handles.ActionExt,'String');
1916    ActionExtIndex=find(strcmp(ActionExt,ActionExtList), 1);
1917    if isempty(ActionExtIndex)
1918        set(handles.ActionExt,'String',[ActionExtList;{ActionExt}])
1919        ActionExtIndex=numel(ActionExtList)+1;
1920        ActionPathNew=cell(size(ActionPathList,1),1);%new column of ActionPath
1921        ActionPathList=[ActionPathList ActionPathNew];
1922    end
1923    set(handles.ActionName,'UserData',ActionPathList);
1924
1925    % remove old Action options in the menu (keeping a menu length <nb_builtin_ACTION+5)
1926    if length(ActionList)>nb_builtin_ACTION+5; %nb_builtin=nbre of functions always remaining in the initial menu
1927        nbremove=length(ActionList)-nb_builtin_ACTION-5;
1928        ActionList(nb_builtin_ACTION+1:end-5)=[];
1929        ActionPathList(nb_builtin_ACTION+1:end-4,:)=[];
1930        ActionIndex=ActionIndex-nbremove;
1931    end
1932   
1933    % record action menu, choice and path
1934    set(handles.ActionName,'Value',ActionIndex)
1935    set(handles.ActionName,'String',ActionList)
1936    set(handles.ActionExt,'Value',ActionExtIndex)
1937    ActionPathList{ActionIndex,ActionExtIndex}=PathName;
1938       
1939    %record the user defined menu additions in personal file profil_perso
1940    dir_perso=prefdir;
1941    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
1942    if nb_builtin_ACTION+1<=numel(ActionList)-1
1943        ActionListUser=ActionList(nb_builtin_ACTION+1:numel(ActionList)-1);
1944        ActionPathListUser=ActionPathList(nb_builtin_ACTION+1:numel(ActionList)-1,:);
1945        ActionExtListUser={};
1946        if numel(ActionExtList)>2
1947            ActionExtListUser=ActionExtList(3:end);
1948        end
1949        if exist(profil_perso,'file')
1950            save(profil_perso,'ActionListUser','ActionPathListUser','ActionExtListUser','-append')
1951        else
1952            save(profil_perso,'ActionListUser','ActionPathListUser','ActionExtListUser','-V6')
1953        end
1954    end
1955end
1956
1957%% check the current ActionPath to the selected function
1958ActionPath=ActionPathList{ActionIndex};%current recorded path
1959set(handles.ActionPath,'String',ActionPath); %show the path to the senlected function
1960
1961%% reinitialise the waitbar
1962update_waitbar(handles.Waitbar,0)
1963
1964%% default setting for the visibility of the GUI elements
1965% set(handles.FieldTransform,'Visible','off')
1966% set(handles.CheckObject,'Visible','off');
1967% set(handles.ProjObject,'Visible','off');
1968% set(handles.CheckMask,'Visible','off')
1969% set(handles.Mask,'Visible','off')
1970
1971%% create the function handle for Action
1972path_series=which('series');
1973if ~isequal(ActionPath,path_series)
1974    eval(['spath=which(''' ActionName ''');']) %spath = current path of the selected function ACTION
1975    if ~exist(ActionPath,'dir')
1976        errormsg=['The prescribed function path ' ActionPath ' does not exist'];
1977        return
1978    end
1979    if ~isequal(spath,ActionPath)
1980        addpath(ActionPath)% add the prescribed path if not the current one
1981    end
1982end
1983eval(['h_fun=@' ActionName ';'])%create a function handle for ACTION
1984if ~isequal(ActionPath,path_series)
1985        rmpath(ActionPath)% add the prescribed path if not the current one   
1986end
1987
1988%% Activate the Action fct
1989Param=read_GUI_series(handles);% read the parameters from the GUI series
1990ParamOut=h_fun(Param);
1991
1992%% Put the first line of the selected Action fct as tooltip help
1993try
1994    [fid,errormsg] =fopen([ActionName '.m']);
1995    InputText=textscan(fid,'%s',1,'delimiter','\n');
1996    fclose(fid);
1997    set(handles.ActionName,'ToolTipString',InputText{1}{1})% put the first line of the selected function as tooltip help
1998end
1999
2000%% Detect the types of input files
2001SeriesData=get(handles.series,'UserData');
2002iview_civ=[];nb_netcdf=0;
2003if ~isempty(SeriesData)
2004    iview_civ=find(strcmp('civx',SeriesData.FileType)|strcmp('civdata',SeriesData.FileType));
2005    nb_netcdf=numel(find(strcmp('netcdf',SeriesData.FileType)));
2006end
2007%menu={''};
2008if numel(iview_civ)>=1
2009    menu=set_veltype_display(SeriesData.FileInfo{iview_civ(1)}.CivStage,SeriesData.FileType{iview_civ(1)});
2010    set(handles.VelType,'String',[{'*'};menu])
2011    if numel(iview_civ)>=2
2012        menu=set_veltype_display(SeriesData.FileInfo{iview_civ(2)}.CivStage,SeriesData.FileType{iview_civ(2)});
2013        set(handles.VelType_1,'String',[{'*'};menu])
2014    end
2015end       
2016
2017%% Check whether alphabetical sorting of input Subdir is alowed by the Action fct  (for multiples series entries)
2018if isfield(ParamOut,'AllowInputSort')&&isequal(ParamOut.AllowInputSort,'on')&& size(Param.InputTable,1)>1
2019    [tild,iview]=sort(InputTable(:,2)); %subdirectories sorted in alphabetical order
2020    set(handles.InputTable,'Data',InputTable(iview,:));
2021    MinIndex_i=get(handles.MinIndex_i,'Data');
2022    MinIndex_j=get(handles.MinIndex_j,'Data');
2023    MaxIndex_i=get(handles.MaxIndex_i,'Data');
2024    MaxIndex_j=get(handles.MaxIndex_j,'Data');
2025    set(handles.MinIndex_i,'Data',MinIndex_i(iview,:));
2026    set(handles.MinIndex_j,'Data',MinIndex_j(iview,:));
2027    set(handles.MaxIndex_i,'Data',MaxIndex_i(iview,:));
2028    set(handles.MaxIndex_j,'Data',MaxIndex_j(iview,:));
2029    TimeTable=get(handles.TimeTable,'Data');
2030    set(handles.TimeTable,'Data',TimeTable(iview,:));
2031    PairString=get(handles.PairString,'Data');
2032    set(handles.PairString,'Data',PairString(iview,:));
2033end
2034
2035%% Impose the whole input file index range if requested
2036if isfield(ParamOut,'WholeIndexRange')&&isequal(ParamOut.WholeIndexRange,'on')
2037    MinIndex_i=get(handles.MinIndex_i,'Data');
2038    MinIndex_j=get(handles.MinIndex_j,'Data');
2039    MaxIndex_i=get(handles.MaxIndex_i,'Data');
2040    MaxIndex_j=get(handles.MaxIndex_j,'Data');
2041    set(handles.num_first_i,'String',num2str(MinIndex_i(1)))% set first as the min index (for the first line)
2042    set(handles.num_last_i,'String',num2str(MaxIndex_i(1)))% set last as the max index (for the first line)
2043    set(handles.num_incr_i,'String','1')
2044    set(handles.num_first_j,'String',num2str(MinIndex_j(1)))% set first as the min index (for the first line)
2045    set(handles.num_last_j,'String',num2str(MaxIndex_j(1)))% set last as the max index (for the first line)
2046    set(handles.num_incr_j,'String','1')
2047else  % check index ranges
2048    first_i=1;last_i=1;first_j=1;last_j=1;
2049    if isfield(Param.IndexRange,'first_i')
2050        first_i=Param.IndexRange.first_i;
2051       % incr_i=Param.IndexRange.incr_i;
2052        last_i=Param.IndexRange.last_i;
2053    end
2054    if isfield(Param.IndexRange,'first_j')
2055        first_j=Param.IndexRange.first_j;
2056       % incr_j=Param.IndexRange.incr_j;
2057        last_j=Param.IndexRange.last_j;
2058    end
2059    if last_i < first_i || last_j < first_j , msgbox_uvmat('ERROR','last field number must be larger than the first one'),...
2060            set(handles.RUN, 'Enable','On'), set(handles.RUN,'BackgroundColor',[1 0 0]),return,end;
2061end
2062
2063%% NbSlice visibility
2064NbSliceVisible='off';%default
2065if isfield(ParamOut,'NbSlice') && isequal(ParamOut.NbSlice,'on')
2066    NbSliceVisible='on';
2067    set(handles.num_NbProcess,'String',get(handles.num_NbSlice,'String'))% the nbre of processes is imposed as the nbre of slices
2068else
2069    set(handles.num_NbProcess,'String','')% free nbre of processes
2070end
2071set(handles.num_NbSlice,'Visible',NbSliceVisible)
2072set(handles.NbSlice_title,'Visible',NbSliceVisible)
2073
2074%% Visibility of VelType and VelType_1 menus
2075VelTypeVisible='off';  %hidden by default
2076VelType_1Visible='off';
2077InputFieldsVisible='off';%visibility of the frame Fields
2078if isfield(ParamOut,'VelType')
2079    if strcmp( ParamOut.VelType,'one')||strcmp( ParamOut.VelType,'two')
2080        if numel(iview_civ)>=1
2081            VelTypeVisible='on';
2082            InputFieldsVisible='on';
2083        end
2084    end
2085    if strcmp( ParamOut.VelType,'two')
2086        if numel(iview_civ)>=2
2087            VelType_1Visible='on';
2088        end
2089    end
2090end
2091set(handles.VelType,'Visible',VelTypeVisible)
2092set(handles.VelType_text,'Visible',VelTypeVisible);
2093set(handles.VelType_1,'Visible',VelType_1Visible)
2094set(handles.VelType_text_1,'Visible',VelType_1Visible);
2095
2096%% Visibility of FieldName and FieldName_1 menus
2097FieldNameVisible='off';  %hidden by default
2098FieldName_1Visible='off';  %hidden by default
2099if isfield(ParamOut,'FieldName')
2100    if strcmp( ParamOut.FieldName,'one')||strcmp( ParamOut.FieldName,'two')
2101        if (numel(iview_civ)+nb_netcdf)>=1
2102            InputFieldsVisible='on';
2103            FieldNameVisible='on';
2104        end
2105    end
2106    if strcmp( ParamOut.FieldName,'two')
2107        if (numel(iview_civ)+nb_netcdf)>=1
2108            FieldName_1Visible='on';
2109        end
2110    end
2111end
2112set(handles.InputFields,'Visible',InputFieldsVisible)
2113set(handles.FieldName,'Visible',FieldNameVisible) % test for MenuBorser
2114set(handles.FieldName_1,'Visible',FieldName_1Visible)
2115
2116%% Visibility of FieldTransform menu
2117FieldTransformVisible='off';  %hidden by default
2118if isfield(ParamOut,'FieldTransform')
2119    FieldTransformVisible=ParamOut.FieldTransform; 
2120    TransformName_Callback([],[], handles)
2121end
2122set(handles.FieldTransform,'Visible',FieldTransformVisible)
2123if isfield(ParamOut,'TransformPath')
2124    set(handles.ActionExt,'UserData',ParamOut.TransformPath)
2125else
2126    set(handles.ActionExt,'UserData',[])
2127end
2128
2129%% Visibility of projection object
2130ProjObjectVisible='off';  %hidden by default
2131if isfield(ParamOut,'ProjObject')
2132    ProjObjectVisible=ParamOut.ProjObject;
2133end
2134set(handles.CheckObject,'Visible',ProjObjectVisible)
2135if ~get(handles.CheckObject,'Value')
2136    ProjObjectVisible='off';
2137end
2138set(handles.ProjObject,'Visible',ProjObjectVisible)
2139set(handles.DeleteObject,'Visible',ProjObjectVisible)
2140set(handles.ViewObject,'Visible',ProjObjectVisible)
2141
2142
2143%% Visibility of mask input
2144MaskVisible='off';  %hidden by default
2145if isfield(ParamOut,'Mask')
2146    MaskVisible=ParamOut.Mask;
2147end
2148%set(handles.Mask,'Visible',MaskVisible)
2149set(handles.CheckMask,'Visible',MaskVisible);
2150
2151%% definition of the directory containing the output files
2152OutputDirVisible='off';
2153if isfield(ParamOut,'OutputDirExt')&&~isempty(ParamOut.OutputDirExt)
2154    set(handles.OutputDirExt,'String',ParamOut.OutputDirExt)
2155    OutputDirVisible='on';
2156    SubDir=InputTable(1:end-1,2); %set of subdirectories sorted in alphabetical order
2157    SubDirOut=SubDir{1};
2158    if numel(SubDir)>1
2159        for ilist=2:numel(SubDir)
2160            SubDirOut=[SubDirOut '-' SubDir{ilist}];
2161        end
2162    end
2163    set(handles.OutputSubDir,'String',SubDirOut)
2164end
2165set(handles.OutputDirExt,'Visible',OutputDirVisible)
2166set(handles.OutputSubDir,'Visible',OutputDirVisible)
2167set(handles.OutputDir_title,'Visible',OutputDirVisible)
2168set(handles.RunMode,'Visible',OutputDirVisible)
2169set(handles.ActionExt,'Visible',OutputDirVisible)
2170set(handles.RunMode_title,'Visible',OutputDirVisible)
2171set(handles.ActionExt_title,'Visible',OutputDirVisible)
2172
2173
2174%% Expected nbre of output files
2175if isfield(ParamOut,'OutputFileMode')
2176StatusData.OutputFileMode=ParamOut.OutputFileMode;
2177set(handles.status,'UserData',StatusData)
2178end
2179
2180%% definition of an additional parameter set, determined by an ancillary GUI
2181if isfield(ParamOut,'ActionInput')
2182    set(handles.ActionInput,'Visible','on')
2183    set(handles.ActionInput_title,'Visible','on')
2184    set(handles.ActionInputView,'Visible','on')
2185    set(handles.ActionInputView,'Value',0)
2186    set(handles.ActionInput,'String',ActionName)
2187    ParamOut.ActionInput.Program=ActionName; % record the program in ActionInput
2188    SeriesData.ActionInput=ParamOut.ActionInput;
2189else
2190    set(handles.ActionInput,'Visible','off')
2191    set(handles.ActionInput_title,'Visible','off')
2192    set(handles.ActionInputView,'Visible','off')
2193    if isfield(SeriesData,'ActionInput')
2194    SeriesData=rmfield(SeriesData,'ActionInput');
2195    end
2196end   
2197set(handles.series,'UserData',SeriesData)
2198set(handles.ActionName,'BackgroundColor',[1 1 1])
2199
2200%------------------------------------------------------------------------
2201% --- Executes on button press in ActionInputView.
2202function ActionInputView_Callback(hObject, eventdata, handles)
2203%------------------------------------------------------------------------
2204if get(handles.ActionInputView,'Value')
2205ActionName_Callback(hObject, eventdata, handles)
2206end
2207
2208%------------------------------------------------------------------------
2209% --- Executes on selection change in FieldName.
2210function FieldName_Callback(hObject, eventdata, handles)
2211%------------------------------------------------------------------------
2212field_str=get(handles.FieldName,'String');
2213field_index=get(handles.FieldName,'Value');
2214field=field_str{field_index(1)};
2215if isequal(field,'get_field...')
2216    hget_field=findobj(allchild(0),'name','get_field');
2217    if ~isempty(hget_field)
2218        delete(hget_field)%delete opened versions of get_field
2219    end
2220    Param=read_GUI(handles.series);
2221    Param.InputTable=Param.InputTable(1,:);
2222    filecell=get_file_series(Param);
2223    if exist(filecell{1,1},'file')
2224        GetFieldData=get_field(filecell{1,1});
2225        FieldList={};
2226        XName=GetFieldData.XVarName;
2227        if GetFieldData.CheckVector
2228            UName=GetFieldData.PanelVectors.vector_x;
2229            VName=GetFieldData.PanelVectors.vector_y;
2230            XName=GetFieldData.XVarName;
2231            YName=GetFieldData.YVarName;
2232            CName=GetFieldData.PanelVectors.vec_color;
2233            [FieldList,VecColorList]=set_field_list(UName,VName,CName);
2234        elseif GetFieldData.CheckScalar
2235            AName=GetFieldData.PanelScalar.scalar;
2236            XName=GetFieldData.XVarName;
2237            YName=GetFieldData.YVarName;
2238            FieldList={AName};
2239        elseif GetFieldData.CheckPlot1D;
2240            YName=GetFieldData.CheckPlot1D.ordinate;
2241        end
2242        set(handles.Coord_x,'String',{XName})
2243        set(handles.Coord_y,'String',{YName})
2244        set(handles.FieldName,'Value',1)
2245        set(handles.FieldName,'String',[FieldList; {'get_field...'}]);
2246        %         set(handles.ColorScalar,'Value',1)
2247        %         set(handles.ColorScalar,'String',VecColorList);
2248        %         UvData.FileType{1}='netcdf';
2249        %         set(handles.uvmat,'UserData',UvData)
2250    end
2251    % elseif isequal(field,'more...')
2252    %     str=calc_field;
2253    %     [ind_answer,v] = listdlg('PromptString','Select a file:',...
2254    %                 'SelectionMode','single',...
2255    %                 'ListString',str);
2256    %        % edit the choice in the fields and actionname menu
2257    %      scalar=cell2mat(str(ind_answer));
2258    %      update_menu(handles.FieldName,scalar)
2259end
2260
2261%------------------------------------------------------------------------
2262% --- Executes on selection change in FieldName_1.
2263function FieldName_1_Callback(hObject, eventdata, handles)
2264%------------------------------------------------------------------------
2265field_str=get(handles.FieldName_1,'String');
2266field_index=get(handles.FieldName_1,'Value');
2267field=field_str{field_index};
2268if isequal(field,'get_field...')   
2269     hget_field=findobj(allchild(0),'name','get_field_1');
2270     if ~isempty(hget_field)
2271         delete(hget_field)
2272     end
2273     SeriesData=get(handles.series,'UserData');
2274     filename=SeriesData.CurrentInputFile_1;
2275     if exist(filename,'file')
2276        hget_field=get_field(filename);
2277        set(hget_field,'name','get_field_1')
2278     end
2279% elseif isequal(field,'more...')
2280%     str=calc_field;
2281%     [ind_answer,v] = listdlg('PromptString','Select a file:',...
2282%                 'SelectionMode','single',...
2283%                 'ListString',str);
2284%        % edit the choice in the fields and actionname menu
2285%      scalar=cell2mat(str(ind_answer));
2286%      update_menu(handles.FieldName_1,scalar)
2287end   
2288
2289
2290%%%%%%%%%%%%%
2291function [ind_remove]=find_pairs(dirpair,ind_i,last_i)
2292indsel=ind_i;
2293indiff=diff(ind_i); %test index increment to detect multiplets (several pairs with the same index ind_i) and holes in the series
2294indiff=[1 indiff last_i-ind_i(end)+1];%for testing gaps with the imposed bounds
2295if ~isempty(indiff)
2296    indiff2=diff(indiff);
2297    indiffp=[indiff2 1];
2298    indiffm=[1 indiff2];
2299    ind_multi_m=find((indiff==0)&(indiffm<0))-1;%indices of first members of multiplets
2300    ind_multi_p=find((indiff==0)&(indiffp>0));%indices of last members of multiplets
2301    %for each multiplet, select the most recent file
2302    ind_remove=[];
2303    for i=1:length(ind_multi_m)
2304        ind_pairs=ind_multi_m(i):ind_multi_p(i);
2305        for imulti=1:length(ind_pairs)
2306            datepair(imulti)=datenum(dirpair(ind_pairs(imulti)).date);%dates of creation
2307        end
2308        [datenew,indsort2]=sort(datepair); %sort the multiplet by creation date
2309        ind_s=indsort2(1:end-1);%
2310        ind_remove=[ind_remove ind_pairs(ind_s)];%remove these indices, leave the last one
2311    end
2312end
2313
2314%------------------------------------------------------------------------
2315% --- determine the list of index pairstring of processing file
2316function [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)
2317%------------------------------------------------------------------------
2318num_i1=num_i;% set of first image numbers by default
2319num_i2=num_i;
2320num_j1=num_j;
2321num_j2=num_j;
2322num_i_out=num_i;
2323num_j_out=num_j;
2324% if isequal (NomType,'_1-2_1') || isequal (NomType,'_1-2')
2325if isequal(mode,'series(Di)')
2326    num_i1_line=num_i+ind_shift(3);% set of first image numbers
2327    num_i2_line=num_i+ind_shift(4);
2328    % adjust the first and last field number
2329        indsel=find(num_i1_line >= 1);
2330    num_i_out=num_i(indsel);
2331    num_i1_line=num_i1_line(indsel);
2332    num_i2_line=num_i2_line(indsel);
2333    num_j1=meshgrid(num_j,ones(size(num_i1_line)));
2334    num_j2=meshgrid(num_j,ones(size(num_i1_line)));
2335    [xx,num_i1]=meshgrid(num_j,num_i1_line);
2336    [xx,num_i2]=meshgrid(num_j,num_i2_line);
2337elseif isequal (mode,'series(Dj)')||isequal (mode,'bursts')
2338    if isequal(mode,'bursts') %case of bursts (png_old or png_2D)
2339        num_j1=ind_shift(1)*ones(size(num_i));
2340        num_j2=ind_shift(2)*ones(size(num_i));
2341    else
2342        num_j1_col=num_j+ind_shift(1);% set of first image numbers
2343        num_j2_col=num_j+ind_shift(2);
2344        % adjust the first field number
2345        indsel=find((num_j1_col >= 1));   
2346        num_j_out=num_j(indsel);
2347        num_j1_col=num_j1_col(indsel);
2348        num_j2_col=num_j2_col(indsel);
2349        [num_i1,num_j1]=meshgrid(num_i,num_j1_col);
2350        [num_i2,num_j2]=meshgrid(num_i,num_j2_col);
2351    end   
2352end
2353
2354%------------------------------------------------------------------------
2355% --- Executes on button press in CheckObject.
2356%------------------------------------------------------------------------
2357function CheckObject_Callback(hObject, eventdata, handles)
2358
2359hset_object=findobj(allchild(0),'tag','set_object');%find the set_object interface handle
2360if get(handles.CheckObject,'Value')
2361    SeriesData=get(handles.series,'UserData');
2362    if isfield(SeriesData,'ProjObject') && ~isempty(SeriesData.ProjObject)
2363        set(handles.ViewObject,'Value',1)
2364        ViewObject_Callback(hObject, eventdata, handles)
2365    else
2366        if ishandle(hset_object)
2367            uistack(hset_object,'top')% show the GUI set_object if opened
2368        else
2369            %get the object file
2370            InputTable=get(handles.InputTable,'Data');
2371            defaultname=InputTable{1,1};
2372            if isempty(defaultname)
2373                defaultname={''};
2374            end
2375            fileinput=uigetfile_uvmat('pick a xml object file (or use uvmat to create it)',defaultname,'.xml');
2376%             [FileName, PathName] = uigetfile( ...
2377%                 {'*.xml;*.mat', ' (*.xml,*.mat)';
2378%                 '*.xml',  '.xml files '; ...
2379%                 '*.mat',  '.mat matlab files '}, ...
2380%                 'Pick an xml object file (or use uvmat to create it)',defaultname);
2381%             fileinput=[PathName FileName];%complete file name
2382%             sizf=size(fileinput);
2383            if isempty(fileinput),return;end
2384            %read the file
2385            data=xml2struct(fileinput);
2386            if ~isfield(data,'Type')
2387                msgbox_uvmat('ERROR',[fileinput ' is not an object xml file'])
2388                return
2389            end
2390            if ~isfield(data,'ProjMode')
2391                data.ProjMode='none';
2392            end
2393            hset_object=set_object(data);% call the set_object interface
2394        end
2395        ProjObject=read_GUI(hset_object);
2396        set(handles.ProjObject,'String',ProjObject.Name);%display the object name
2397        SeriesData=get(handles.series,'UserData');
2398        SeriesData.ProjObject=ProjObject;
2399        set(handles.series,'UserData',SeriesData);
2400    end
2401    set(handles.EditObject,'Visible','on');
2402    set(handles.DeleteObject,'Visible','on');
2403    set(handles.ViewObject,'Visible','on');
2404    set(handles.ProjObject,'Visible','on');
2405else
2406    set(handles.EditObject,'Visible','off');
2407    set(handles.DeleteObject,'Visible','off');
2408    set(handles.ViewObject,'Visible','off');
2409    if ~ishandle(hset_object)
2410    set(handles.ViewObject,'Value',0);
2411    end
2412    set(handles.ProjObject,'Visible','off');
2413end
2414
2415%------------------------------------------------------------------------
2416% --- Executes on button press in ViewObject.
2417%------------------------------------------------------------------------
2418function ViewObject_Callback(hObject, eventdata, handles)
2419
2420% if get(handles.ViewObject,'Value')
2421   % set(handles.EditObject,'Value',0)
2422        UserData=get(handles.series,'UserData');
2423    hset_object=findobj(allchild(0),'Tag','set_object');
2424    if ~isempty(hset_object)
2425        delete(hset_object)% refresh set_object if already opened
2426    end
2427    hset_object=set_object(UserData.ProjObject);
2428    set(hset_object,'Name','view_object_series')
2429% else
2430%     hset_object=findobj(allchild(0),'Tag','set_object');
2431%     if ~isempty(hset_object)
2432%         delete(hset_object)
2433%     end
2434% end
2435
2436%------------------------------------------------------------------------
2437% --- Executes on button press in EditObject.
2438%------------------------------------------------------------------------
2439function EditObject_Callback(hObject, eventdata, handles)
2440
2441if get(handles.EditObject,'Value')
2442    set(handles.ViewObject,'Value',0)
2443        UserData=get(handles.series,'UserData');
2444    hset_object=set_object(UserData.ProjObject);
2445    set(hset_object,'Name','edit_object_series')
2446    set(get(hset_object,'Children'),'Enable','on')
2447else
2448    hset_object=findobj(allchild(0),'Tag','set_object');
2449    if ~isempty(hset_object)
2450        set(get(hset_object,'Children'),'Enable','off')
2451    end
2452end
2453
2454%------------------------------------------------------------------------
2455% --- Executes on button press in DeleteObject.
2456%------------------------------------------------------------------------
2457function DeleteObject_Callback(hObject, eventdata, handles)
2458
2459% if get(handles.DeleteObject,'Value')
2460        SeriesData=get(handles.series,'UserData');
2461    SeriesData.ProjObject=[];
2462    set(handles.series,'UserData',SeriesData)
2463    set(handles.ProjObject,'String','')
2464    set(handles.CheckObject,'Value',0)
2465    set(handles.ViewObject,'Visible','off')
2466    set(handles.EditObject,'Visible','off')
2467    hset_object=findobj(allchild(0),'Tag','set_object');
2468    if ~isempty(hset_object)
2469        delete(hset_object)
2470    end
2471    set(handles.DeleteObject,'Visible','off')
2472%     set(handles.DeleteObject,'Value',0)
2473% end
2474
2475%------------------------------------------------------------------------
2476% --- Executed when CheckMask is activated
2477%------------------------------------------------------------------------
2478function CheckMask_Callback(hObject, eventdata, handles)
2479
2480if get(handles.CheckMask,'Value')
2481    MaskData=get(handles.MaskTable,'Data');
2482    InputTable=get(handles.InputTable,'Data');
2483    nbview=size(InputTable,1);
2484    %     MaskTable=cell(nbview,1);
2485    for iview=1:nbview
2486        RootPath=InputTable{iview,1};
2487        if ~isempty(RootPath)
2488            if isempty(MaskData{iview})
2489                SubDir=InputTable{iview,2};
2490                MaskSubDir=regexprep(SubDir,'\..*','');%take the root part of SubDir, before the first dot '.'
2491                MaskName=fullfile(RootPath,[MaskSubDir '.mask'],'mask_1.png');
2492                if ~exist(MaskName,'file')
2493                    MaskName=uigetfile_uvmat('select a mask file:',RootPath,'image');
2494                end
2495                MaskTable{iview,1}=MaskName ;
2496                ListMask{iview,1}=num2str(iview);
2497            end
2498        end
2499    end
2500    nbview=size(MaskTable,1);
2501    set(handles.MaskTable,'Data',MaskTable)
2502    %     set(handles.MaskTable,'ColumnFormat',{MaskTable'})
2503    set(handles.MaskTable,'Visible','on')
2504    set(handles.MaskBrowse,'Visible','on')
2505    set(handles.ListMask,'Visible','on')
2506    set(handles.ListMask,'String',ListMask)
2507    set(handles.ListMask,'Value',numel(ListMask))
2508else
2509    set(handles.MaskTable,'Visible','off')
2510    set(handles.MaskBrowse,'Visible','off')
2511    set(handles.ListMask,'Visible','off')
2512end
2513
2514%------------------------------------------------------------------------
2515% --- Executes on button press in MaskBrowse.
2516%------------------------------------------------------------------------
2517function MaskBrowse_Callback(hObject, eventdata, handles)
2518InputTable=get(handles.InputTable,'Data');
2519iview=get(handles.ListMask,'Value');
2520%     MaskTable=cell(nbview,1);
2521
2522RootPath=InputTable{iview,1};
2523%         if ~isempty(RootPath)
2524%         SubDir=InputTable{iview,2};
2525%         MaskSubDir=regexprep(SubDir,'\..*','');%take the root part of SubDir, before the first dot '.'
2526%         MaskName=fullfile(RootPath,[MaskSubDir '.mask'],'mask_1.png');
2527%         if ~exist(MaskName,'file')
2528MaskName=uigetfile_uvmat('select a mask file:',RootPath,'image');
2529%         end
2530if ~isempty(MaskName)
2531    MaskTable=get(handles.MaskTable,'Data');
2532MaskTable{iview,1}=MaskName ;
2533%         end
2534set(handles.MaskTable,'Data',MaskTable)
2535end
2536   % set(handles.MaskTable,'ColumnFormat',{MaskTable'})
2537
2538%------------------------------------------------------------------------
2539% --- Executes when selected cell(s) is changed in MaskTable.
2540%------------------------------------------------------------------------
2541function MaskTable_CellSelectionCallback(hObject, eventdata, handles)
2542
2543if numel(eventdata.Indices)>=1
2544set(handles.ListMask,'Value',eventdata.Indices(1))
2545end
2546
2547%-------------------------------------------------------------------
2548function MenuHelp_Callback(hObject, eventdata, handles)
2549%-------------------------------------------------------------------
2550path_to_uvmat=which ('uvmat');% check the path of uvmat
2551pathelp=fileparts(path_to_uvmat);
2552helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
2553if isempty(dir(helpfile)), msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
2554else
2555    addpath (fullfile(pathelp,'uvmat_doc'))
2556    web([helpfile '#series'])
2557end
2558
2559%-------------------------------------------------------------------
2560% --- Executes on selection change in TransformName.
2561function TransformName_Callback(hObject, eventdata, handles)
2562%----------------------------------------------------------------------
2563TransformList=get(handles.TransformName,'String');
2564TransformIndex=get(handles.TransformName,'Value');
2565TransformName=TransformList{TransformIndex};
2566TransformPathList=get(handles.TransformName,'UserData');
2567nb_builtin_transform=4;
2568% ff=functions(list_transform{end});
2569if isequal(TransformName,'more...');
2570%     coord_fct='';
2571%     prompt = {'Enter the name of the transform function'};
2572%     dlg_title = 'user defined transform';
2573%     num_lines= 1;
2574    [FileName, PathName] = uigetfile( ...
2575       {'*.m', ' (*.m)';
2576        '*.m',  '.m files '; ...
2577        '*.*', 'All Files (*.*)'}, ...
2578        'Pick a transform function',get(handles.TransformPath,'String'));
2579    if isequal(FileName,0)
2580        return     %browser closed without choice
2581    end
2582    if isequal(PathName(end),'/')||isequal(PathName(end),'\')
2583        PathName(end)=[];
2584    end
2585    [TransformPath,TransformName,TransformExt]=fileparts(FileName);% removes extension .m
2586    if ~strcmp(TransformExt,'.m')
2587        msgbox_uvmat('ERROR','a Matlab function .m must be introduced');
2588        return
2589    end
2590     % insert the choice in the menu
2591    TransformIndex=find(strcmp(TransformName,TransformList),1);% look for the selected function in the menu Action
2592    if isempty(TransformIndex)%the input string does not exist in the menu
2593        TransformIndex= length(TransformList);
2594        TransformList=[TransformList(1:end-1);{TransformName};TransformList(end)];% the selected function is appended in the menu, before the last item 'more...'
2595        set(handles.TransformName,'String',TransformList)
2596        TransformPathList=[TransformPathList;{TransformPath}];
2597    end
2598   % save the new menu in the personal file 'uvmat_perso.mat'
2599   dir_perso=prefdir;%personal Matalb directory
2600   profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
2601   if exist(profil_perso,'file')
2602       for ilist=nb_builtin_transform+1:numel(TransformPathList)
2603           TransformListUser{ilist-nb_builtin_transform}=TransformList{ilist};
2604           TransformPathListUser{ilist-nb_builtin_transform}=TransformPathList{ilist};
2605       end
2606       save (profil_perso,'TransformPathListUser','TransformListUser','-append'); %store the root name for future opening of uvmat
2607   end
2608end
2609
2610%display the current function path
2611set(handles.TransformPath,'String',TransformPathList{TransformIndex}); %show the path to the senlected function
2612set(handles.TransformName,'UserData',TransformPathList);
2613
2614%------------------------------------------------------------------------
2615% --- fct activated by the upper bar menu ExportConfig
2616%------------------------------------------------------------------------
2617function MenuExportConfig_Callback(hObject, eventdata, handles)
2618
2619global Param
2620Param=read_GUI_series(handles);
2621evalin('base','global Param')%make CurData global in the workspace
2622display('current series config :')
2623evalin('base','Param') %display CurData in the workspace
2624commandwindow; %brings the Matlab command window to the front
2625
2626%------------------------------------------------------------------------
2627% --- fct activated by the upper bar menu InportConfig
2628%------------------------------------------------------------------------
2629function MenuImportConfig_Callback(hObject, eventdata, handles)
2630
2631InputTable=get(handles.InputTable,'Data');
2632filexml=uigetfile_uvmat('pick a xml parameter file',InputTable{1,1},'.xml');
2633% [FileName, PathName] = uigetfile( ...
2634%        {'*.xml', ' (*.xml)';
2635%        '*.xml',  '.xml files '; ...
2636%         '*.*',  'All Files (*.*)'}, ...
2637%         'Pick a file',InputTable{1,1});
2638% filexml=[PathName FileName];%complete file name
2639if ~isempty(filexml)%abandon if no file is introduced by the browser
2640    Param=xml2struct(filexml);
2641    fill_GUI(Param,handles.series)
2642    if isfield(Param,'ActionInput')
2643            set(handles.ActionInput,'Visible','on')
2644    set(handles.ActionInput_title,'Visible','on')
2645    set(handles.ActionInputView,'Visible','on')
2646    set(handles.ActionInputView,'Value',0)
2647    %set(handles.ActionInput,'String',ActionName)
2648%    ParamOut.ActionInput.Program=ActionName; % record the program in ActionInput
2649    SeriesData=get(handles.series,'UserData');
2650    SeriesData.ActionInput=Param.ActionInput;
2651    set(handles.series,'UserData',SeriesData)
2652    end
2653    ActionName_Callback([],[],handles)
2654end
2655
2656%------------------------------------------------------------------------
2657% --- Executes when the GUI series is resized.
2658%------------------------------------------------------------------------
2659function series_ResizeFcn(hObject, eventdata, handles)
2660
2661%% input table
2662set(handles.InputTable,'Unit','pixel')
2663Pos=get(handles.InputTable,'Position');
2664set(handles.InputTable,'Unit','normalized')
2665ColumnWidth=round([0.5 0.14 0.14 0.14 0.08]*(Pos(3)-52));
2666ColumnWidth=num2cell(ColumnWidth);
2667set(handles.InputTable,'ColumnWidth',ColumnWidth)
2668
2669%% MinIndex_j and MaxIndex_i
2670unit=get(handles.MinIndex_i,'Unit');
2671set(handles.MinIndex_i,'Unit','pixel')
2672Pos=get(handles.MinIndex_i,'Position');
2673set(handles.MinIndex_i,'Unit',unit)
2674set(handles.MinIndex_i,'ColumnWidth',{Pos(3)-18})
2675set(handles.MaxIndex_i,'ColumnWidth',{Pos(3)-18})
2676set(handles.MinIndex_j,'ColumnWidth',{Pos(3)-18})
2677set(handles.MaxIndex_j,'ColumnWidth',{Pos(3)-18})
2678
2679%% TimeTable
2680set(handles.TimeTable,'Unit','pixel')
2681Pos=get(handles.TimeTable,'Position');
2682set(handles.TimeTable,'Unit','normalized')
2683% ColumnWidth=get(handles.TimeTable,'ColumnWidth');
2684ColumnWidth=num2cell(floor([0.25 0.25 0.25 0.25]*(Pos(3)-20)));
2685set(handles.TimeTable,'ColumnWidth',ColumnWidth)
2686
2687
2688%% PairString
2689set(handles.PairString,'Unit','pixel')
2690Pos=get(handles.PairString,'Position');
2691set(handles.PairString,'Unit','normalized')
2692set(handles.PairString,'ColumnWidth',{Pos(3)-5})
2693
2694%% MaskTable
2695set(handles.MaskTable,'Unit','pixel')
2696Pos=get(handles.MaskTable,'Position');
2697set(handles.MaskTable,'Unit','normalized')
2698set(handles.MaskTable,'ColumnWidth',{Pos(3)-5})
2699
2700%------------------------------------------------------------------------
2701% --- Executes on button press in status.
2702%------------------------------------------------------------------------
2703function status_Callback(hObject, eventdata, handles)
2704
2705if get(handles.status,'Value')
2706    set(handles.status,'BackgroundColor',[1 1 0])
2707    drawnow
2708    %StatusData.time_ref=get(handles.RUN,'UserData');% get the time of launch
2709    Param=read_GUI(handles.series);
2710    RootPath=Param.InputTable{1,1};
2711    if ~isfield(Param,'OutputSubDir')   
2712        msgbox_uvmat('ERROR','no directory defined for output files')
2713        return
2714    end
2715    OutputSubDir=[Param.OutputSubDir Param.OutputDirExt];% subdirectory for output files
2716    OutputDir=fullfile(RootPath,OutputSubDir);
2717    uigetfile_uvmat('status_display',OutputDir)
2718else
2719    %% delete current display fig if selection is off
2720    set(handles.status,'BackgroundColor',[0 1 0])
2721    hfig=findobj(allchild(0),'name','status_display');
2722    if ~isempty(hfig)
2723        delete(hfig)
2724    end
2725    return
2726end
2727
2728
2729%------------------------------------------------------------------------   
2730% launched by selecting a file on the list
2731%------------------------------------------------------------------------
2732function view_file(hObject, eventdata)
2733
2734list=get(hObject,'String');
2735index=get(hObject,'Value');
2736rootroot=get(hObject,'UserData');
2737selectname=list{index};
2738ind_dot=regexp(selectname,'\.\.\.');
2739if ~isempty(ind_dot)
2740    selectname=selectname(1:ind_dot-1);
2741end
2742FullSelectName=fullfile(rootroot,selectname);
2743if exist(FullSelectName,'dir')% a directory has been selected
2744    ListFiles=dir(FullSelectName);
2745    ListDisplay=cell(numel(ListFiles),1);
2746    for ilist=2:numel(ListDisplay)% suppress the first line '.'
2747        ListDisplay{ilist-1}=ListFiles(ilist).name;
2748    end
2749    set(hObject,'Value',1)
2750    set(hObject,'String',ListDisplay)
2751    if strcmp(selectname,'..')
2752        FullSelectName=fileparts(fileparts(FullSelectName));
2753    end
2754    set(hObject,'UserData',FullSelectName)
2755    hfig=get(hObject,'parent');
2756    htitlebox=findobj(hfig,'tag','titlebox');   
2757    set(htitlebox,'String',FullSelectName)
2758elseif exist(FullSelectName,'file')%visualise the vel field if it exists
2759    FileType=get_file_type(FullSelectName);
2760    if strcmp(FileType,'txt')
2761        edit(FullSelectName)
2762    elseif strcmp(FileType,'xml')
2763        editxml(FullSelectName)
2764    else
2765        uvmat(FullSelectName)
2766    end
2767    set(gcbo,'Value',1)
2768end
2769
2770
2771%------------------------------------------------------------------------   
2772% launched by refreshing the status figure
2773%------------------------------------------------------------------------
2774function refresh_GUI(hfig)
2775
2776htitlebox=findobj(hfig,'tag','titlebox');
2777hlist=findobj(hfig,'tag','list');
2778hseries=findobj(allchild(0),'tag','series');
2779hstatus=findobj(hseries,'tag','status');
2780StatusData=get(hstatus,'UserData');
2781OutputDir=get(htitlebox,'String');
2782if ischar(OutputDir),OutputDir={OutputDir};end
2783ListFiles=dir(OutputDir{1});
2784if numel(ListFiles)<1
2785    return
2786end
2787ListFiles(1)=[];%removes the first line ='.'
2788ListDisplay=cell(numel(ListFiles),1);
2789testrecent=0;
2790datnum=zeros(numel(ListDisplay),1);
2791for ilist=1:numel(ListDisplay)
2792    ListDisplay{ilist}=ListFiles(ilist).name;
2793      if ~ListFiles(ilist).isdir && isfield(ListFiles(ilist),'datenum')
2794            datnum(ilist)=ListFiles(ilist).datenum;%only available in recent matlab versions
2795            testrecent=1;
2796       end
2797end
2798set(hlist,'String',ListDisplay)
2799
2800%% Look at date of creation
2801ListDisplay=ListDisplay(datnum~=0);
2802datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
2803NbOutputFile=[];
2804if isempty(datnum)
2805    if testrecent
2806        message='no civ result created yet';
2807    else
2808        message='';
2809    end
2810else
2811    [first,indfirst]=min(datnum);
2812    [last,indlast]=max(datnum);
2813    NbOutputFile_str='?';
2814    NbOutputFile=[];
2815    if isfield(StatusData,'NbOutputFile')
2816        NbOutputFile=StatusData.NbOutputFile;
2817        NbOutputFile_str=num2str(NbOutputFile);
2818    end
2819    message={[num2str(numel(datnum)) ' file(s) done over ' NbOutputFile_str] ;['oldest modification:  ' ListDisplay{indfirst} ' : ' datestr(first)];...
2820        ['latest modification:  ' ListDisplay{indlast} ' : ' datestr(last)]};
2821end
2822set(htitlebox,'String', [OutputDir{1};message])
2823
2824%% update the waitbar
2825hwaitbar=findobj(hfig,'tag','waitbar');
2826if ~isempty(NbOutputFile)
2827    BarPosition=get(hwaitbar,'Position');
2828    BarPosition(3)=0.9*numel(datnum)/NbOutputFile;
2829    set(hwaitbar,'Position',BarPosition)
2830end
2831
2832%------------------------------------------------------------------------
2833% --- Executes on selection change in ActionExt.
2834%------------------------------------------------------------------------
2835function ActionExt_Callback(hObject, eventdata, handles)
2836
2837ActionExtList=get(handles.ActionExt,'String');
2838ActionExt=ActionExtList{get(handles.ActionExt,'Value')};
2839ActionList=get(handles.ActionName,'String');
2840ActionName=ActionList{get(handles.ActionName,'Value')};
2841TransformPath='';
2842if ~isempty(get(handles.ActionExt,'UserData'))
2843    TransformPath=get(handles.ActionExt,'UserData');
2844end
2845if strcmp(ActionExt,'.sh')
2846    set(handles.ActionExt,'BackgroundColor',[1 1 0])
2847    ActionFullName=fullfile(get(handles.ActionPath,'String'),[ActionName '.sh']);
2848    if ~exist(ActionFullName,'file')
2849        answer=msgbox_uvmat('INPUT_Y-N','compiled version has not been created: compile now?');
2850        if strcmp(answer,'Yes')
2851            set(handles.ActionExt,'BackgroundColor',[1 1 0])
2852            path_uvmat=fileparts(which('series'));
2853            currentdir=pwd;
2854            cd(get(handles.ActionPath,'String'))% go to the directory of Action
2855            %  addpath(get(handles.TransformPath,'String'))
2856            addpath(path_uvmat)% add the path to uvmat to run the fct 'compile'
2857           % addpath(fullfile(path_uvmat,'transform_field'))% add the path to uvmat to run the fct 'compile'
2858            compile(ActionName,TransformPath)
2859            cd(currentdir)
2860        end       
2861    else
2862        sh_file_info=dir(fullfile(get(handles.ActionPath,'String'),[ActionName '.sh']));
2863        m_file_info=dir(fullfile(get(handles.ActionPath,'String'),[ActionName '.m']));
2864        if isfield(m_file_info,'datenum') && m_file_info.datenum>sh_file_info.datenum
2865            set(handles.ActionExt,'BackgroundColor',[1 1 0])
2866            drawnow
2867            answer=msgbox_uvmat('INPUT_Y-N',[ActionName '.sh needs to be updated: recompile now?']);
2868            if strcmp(answer,'Yes')
2869                path_uvmat=fileparts(which('series'));
2870                currentdir=pwd;
2871                cd(get(handles.ActionPath,'String'))% go to the directory of Action
2872                %  addpath(get(handles.TransformPath,'String'))
2873                addpath(path_uvmat)% add the path to uvmat to run the fct 'compile'
2874                addpath(fullfile(path_uvmat,'transform_field'))% add the path to uvmat to run the fct 'compile'
2875                compile(ActionName,TransformPath)
2876                cd(currentdir)
2877            end
2878        end
2879    end
2880    set(handles.ActionExt,'BackgroundColor',[1 1 1])
2881end
2882
2883
2884
2885
2886function num_NbProcess_Callback(hObject, eventdata, handles)
2887
2888
2889function num_NbSlice_Callback(hObject, eventdata, handles)
2890NbSlice=str2num(get(handles.num_NbSlice,'String'));
2891set(handles.num_NbProcess,'String',num2str(NbSlice))
2892
2893%------------------------------------------------------------------------
2894% --- set the visibility of relevant velocity type menus:
2895function menu=set_veltype_display(Civ,FileType)
2896%------------------------------------------------------------------------
2897if ~exist('FileType','var')
2898    FileType='civx';
2899end
2900switch FileType
2901    case 'civx'
2902        menu={'civ1';'interp1';'filter1';'civ2';'interp2';'filter2'};
2903        if isequal(Civ,0)
2904            imax=0;
2905        elseif isequal(Civ,1) || isequal(Civ,2)
2906            imax=1;
2907        elseif isequal(Civ,3)
2908            imax=3;
2909        elseif isequal(Civ,4) || isequal(Civ,5)
2910            imax=4;
2911        elseif isequal(Civ,6) %patch2
2912            imax=6;
2913        end
2914    case 'civdata'
2915        menu={'civ1';'filter1';'civ2';'filter2'};
2916        if isequal(Civ,0)
2917            imax=0;
2918        elseif isequal(Civ,1) || isequal(Civ,2)
2919            imax=1;
2920        elseif isequal(Civ,3)
2921            imax=2;
2922        elseif isequal(Civ,4) || isequal(Civ,5)
2923            imax=3;
2924        elseif isequal(Civ,6) %patch2
2925            imax=4;
2926        end
2927end
2928menu=menu(1:imax);
Note: See TracBrowser for help on using the repository browser.