source: trunk/src/series.m @ 650

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

bugs corrected: handles.TimeName? in uvmat, 0_OAR emptied for culter computations with series.

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