source: trunk/src/series.m @ 615

Last change on this file since 615 was 615, checked in by sommeria, 8 years ago

a few bugs repaired

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