source: trunk/src/series.m @ 610

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

various bugs fixed after tests under widows
introduce uigetfile_uvmat for series/status (some problems need to be solved)

File size: 112.7 KB
Line 
1%'series': master function associated to the GUI series.m for analysis field series 
2%------------------------------------------------------------------------
3% function varargout = series(varargin)
4% associated with the GUI series.fig
5%
6%INPUT
7% param: structure with input parameters (link with the GUI uvmat)
8%      .menu_coord_str: string for the TransformName (menu for coordinate transforms)
9%      .menu_coord_val: value for TransformName (menu for coordinate transforms)
10%      .FileName: input file name
11%      .FileName_1: second input file name
12%      .list_field: menu of input fields
13%      .index_fields: chosen index
14%      .civ1=0 or 1, .interp1,  ... : input civ field type
15%
16%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
17%  Copyright Joel Sommeria, 2008, LEGI / CNRS-UJF-INPG, sommeria@coriolis-legi.org.
18%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
19%     This file is part of the toolbox UVMAT.
20%
21%     UVMAT is free software; you can redistribute it and/or modify
22%     it under the terms of the GNU General Public License as published by
23%     the Free Software Foundation; either version 2 of the License, or
24%     (at your option) any later version.
25%
26%     UVMAT is distributed in the hope that it will be useful,
27%     but WITHOUT ANY WARRANTY; without even the implied warranty of
28%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
30%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
31
32%------------------------------------------------------------------------
33%------------------------------------------------------------------------
34%  I - MAIN FUNCTION series
35%------------------------------------------------------------------------
36%------------------------------------------------------------------------
37function varargout = series(varargin)
38
39% Begin initialization code - DO NOT EDIT
40gui_Singleton = 1;
41gui_State = struct('gui_Name',       mfilename, ...
42                   'gui_Singleton',  gui_Singleton, ...
43                   'gui_OpeningFcn', @series_OpeningFcn, ...
44                   'gui_OutputFcn',  @series_OutputFcn, ...
45                   'gui_LayoutFcn',  [] , ...
46                   'gui_Callback',   []);
47if nargin && ischar(varargin{1})
48    gui_State.gui_Callback = str2func(varargin{1});
49end
50
51if nargout
52    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
53else
54    gui_mainfcn(gui_State, varargin{:});
55end
56% End initialization code - DO NOT EDIT
57
58%--------------------------------------------------------------------------
59% --- Executes just before series is made visible.
60%--------------------------------------------------------------------------
61function series_OpeningFcn(hObject, eventdata, handles,Param)
62
63% Choose default command line output for series
64handles.output = hObject;
65% Update handles structure
66guidata(hObject, handles);
67
68%% initial settings
69set(0,'Unit','points')
70ScreenSize=get(0,'ScreenSize');%size of the current screen
71Width=750;% prefered width of the GUI in points (1/72 inch)
72Height=520;
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
701if strcmp(InputTable{iview,4},'*')
702    if ~isempty(VideoObject)
703        imainfo=get(VideoObject);
704        time=zeros(imainfo.NumberOfFrames+1,2);
705        time(:,2)=(0:1/imainfo.FrameRate:(imainfo.NumberOfFrames)/imainfo.FrameRate)';
706        TimeSource='video';
707       % set(han:dles.Dt_txt,'String',['Dt=' num2str(1000/imainfo.FrameRate) 'ms']);%display the elementary time interval in millisec
708        ColorType='truecolor';
709    elseif ~isempty(imformats(regexprep(InputTable{iview,5},'^.',''))) || isequal(InputTable{iview,5},'.vol')%&& isequal(NomType,'*')% multi-frame image
710        if ~isempty(InputTable{iview,2})
711            imainfo=imfinfo(fullfile(InputTable{iview,1},InputTable{iview,2},[InputTable{iview,3} InputTable{iview,5}]));
712        else
713            imainfo=imfinfo([FileBase InputTable{iview,5}]);
714        end
715        ColorType=imainfo.ColorType;%='truecolor' for color images
716        if length(imainfo) >1 %case of image with multiple frames
717            nbfield=length(imainfo);
718            nbfield_j=1;
719        end
720    end
721end
722
723%%  read image documentation file  if found
724XmlData=[];
725NbSlice_calib={};
726XmlFileName=find_imadoc(InputTable{iview,1},InputTable{iview,2},InputTable{iview,3},InputTable{iview,5});
727TimeUnit='';
728if ~isempty(XmlFileName)
729        [XmlData,warntext]=imadoc2struct(XmlFileName);
730        if isfield(XmlData,'Heading') && isfield(XmlData.Heading,'ImageName') && ischar(XmlData.Heading.ImageName)
731            [PP,FF,ext_ima_read]=fileparts(XmlData.Heading.ImageName);
732        end
733        if isfield(XmlData,'Time')
734            time=XmlData.Time;
735            TimeSource='xml';
736        end
737        if isfield(XmlData,'Camera')
738            if isfield(XmlData.Camera,'NbSlice')&& ~isempty(XmlData.Camera.NbSlice)
739                NbSlice_calib{iview}=XmlData.Camera.NbSlice;% Nbre of slices for Zindex in phys transform
740                if ~isequal(NbSlice_calib{iview},NbSlice_calib{1})
741                    msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
742                end
743            end
744            if isfield(XmlData.Camera,'TimeUnit')&& ~isempty(XmlData.Camera.TimeUnit)
745                TimeUnit=XmlData.Camera.TimeUnit;
746            end
747        end
748        if ~isempty(warntext)
749            msgbox_uvmat('WARNING',warntext)
750        end 
751end
752
753%% update time table
754if ~isempty(time)
755    TimeTable=get(handles.TimeTable,'Data');
756    first_i=str2num(get(handles.num_first_i,'String'));
757    last_i=str2num(get(handles.num_last_i,'String'));
758    first_j=str2num(get(handles.num_first_j,'String'));
759    last_j=str2num(get(handles.num_last_j,'String'));
760    MinIndexTable=get(handles.MinIndex,'Data');
761    MinIndex_i=MinIndexTable{iview,1};
762    MinIndex_j=MinIndexTable{iview,2};
763    MaxIndexTable=get(handles.MaxIndex,'Data');
764    MaxIndex_i=MaxIndexTable{iview,1};
765    MaxIndex_j=MaxIndexTable{iview,2};
766    if isempty(MinIndex_j)% only i index
767        if MinIndex_i>0
768            TimeTable{iview,1}=time(MinIndex_i+1);
769        end
770        TimeTable{iview,2}=time(first_i+1);
771        TimeTable{iview,3}=time(last_i+1);
772        TimeTable{iview,4}=time(MaxIndex_i+1);
773    elseif ~isempty(time)
774        if MinIndex_i>0
775            TimeTable{iview,1}=time(MinIndex_i,MinIndex_j);
776        end
777        if size(time)>=[last_i+1 last_j+1]
778            TimeTable{iview,2}=time(first_i+1,first_j+1);
779            TimeTable{iview,3}=time(last_i+1,last_j+1);
780        end
781        if size(time)>=[MaxIndex_i+1 MaxIndex_j+1];
782            TimeTable{iview,4}=time(MaxIndex_i+1,MaxIndex_j+1);
783        end
784    end
785    set(handles.TimeTable,'Data',TimeTable)
786end
787
788%% number of slices
789NbSlice=1;%default
790check_calib=0;
791if isfield(XmlData,'GeometryCalib')
792    check_calib=1;
793    if isfield(XmlData.GeometryCalib,'SliceCoord')
794    siz=size(XmlData.GeometryCalib.SliceCoord);
795    if siz(1)>1
796        NbSlice=siz(1);
797    end
798    end
799end
800set(handles.num_NbSlice,'String',num2str(NbSlice))
801   
802%% update pair menus
803set(handles.Pairs,'Visible','on')
804set(handles.PairString,'Visible','on')
805ListView=get(handles.ListView,'String');
806ListView{iview}=num2str(iview);
807set(handles.ListView,'String',ListView);
808set(handles.ListView,'Value',iview)
809update_mode(handles,i1_series,i2_series,j1_series,j2_series,time)
810
811%% update the series info in 'UserData'
812SeriesData=get(handles.series,'UserData');
813SeriesData.i1_series{iview}=i1_series;
814SeriesData.i2_series{iview}=i2_series;
815SeriesData.j1_series{iview}=j1_series;
816SeriesData.j2_series{iview}=j2_series;
817SeriesData.FileType{iview}=FileType;
818SeriesData.FileInfo{iview}=FileInfo;
819SeriesData.Time{iview}=time;
820if ~isempty(TimeSource)
821    SeriesData.TimeSource=TimeSource;
822end
823if ~isempty(TimeUnit)
824    SeriesData.TimeUnit=TimeUnit;
825end
826if check_calib
827SeriesData.GeometryCalib{iview}=XmlData.GeometryCalib;
828end
829set(handles.series,'UserData',SeriesData)
830
831%% enable j index visibilitycellfun(@isempty,regexp(PairString,'^j'))
832% state='off';
833check_jindex=~cellfun(@isempty,SeriesData.j1_series); %look for non empty j indices
834if isempty(find(check_jindex))
835    enable_j(handles,'off') % no j index needed
836else
837    PairString=get(handles.PairString,'Data');
838    if isempty(find(cellfun(@isempty,regexp(PairString,'^j'))))% if all pair string begins by j (burst)
839        enable_j(handles,'off') % no j index needed
840    else
841        enable_j(handles,'on')
842    end
843end
844
845%% display the set of existing files as an image
846set(handles.FileStatus,'Units','pixels')
847Position=get(handles.FileStatus,'Position');
848set(handles.FileStatus,'Units','normalized')
849xI=0.5:Position(3)-0.5;
850nbview=numel(SeriesData.i1_series);
851pair_max=cell(1,nbview);
852for iview=1:nbview
853    pair_max{iview}=squeeze(max(SeriesData.i1_series{iview},[],1)); %max on pair index
854    if (strcmp(get(handles.num_first_j,'Visible'),'off')&& size(pair_max{iview},2)~=1)
855        pair_max{iview}=squeeze(max(pair_max{iview},[],1)); % consider only the i index
856    end
857    index_min(iview)=find(pair_max{iview}>0, 1 );
858    index_max(iview)=find(pair_max{iview}>0, 1, 'last' );
859end
860index_min=min(index_min);
861index_max=max(index_max);
862range_index=index_max-index_min+1;
863scale_y=Position(4)/nbview;
864scale_x=Position(3)/range_index;
865x=(0.5:range_index-0.5)*Position(3)/range_index;
866% y=(0.5:nbview-0.5)*Position(4)/nbview;
867range_y=max(1,floor(Position(4)/nbview));
868CData=zeros(nbview*range_y,Position(3));
869for iview=1:nbview
870    ind_y=1+(iview-1)*range_y:iview*range_y;
871    LineData=zeros(1,range_index);
872    x_index=find(pair_max{iview}>0)-index_min+1;
873    LineData(x_index)=1;
874    if numel(x)>1
875    LineData=interp1(x,LineData,xI,'nearest');
876    CData(ind_y,:)=ones(size(ind_y'))*LineData;
877    end
878end
879CData=cat(3,zeros(size(CData)),CData,zeros(size(CData)));
880set(handles.FileStatus,'CData',CData);
881
882
883%% enable field and veltype menus, in accordance with the current action
884ActionName_Callback([],[], handles)
885
886%% check for pair display
887check_pairs=0;
888for iview=1:numel(SeriesData.i2_series)
889    if ~isempty(SeriesData.i2_series{iview})||~isempty(SeriesData.j2_series{iview})
890        check_pairs=1;
891    end
892end
893if check_pairs
894    set(handles.Pairs,'Visible','on')
895    set(handles.PairString,'Visible','on')
896else
897    set(handles.Pairs,'Visible','off')
898    set(handles.PairString,'Visible','off')
899end
900
901%% set length of waitbar
902displ_time(handles)
903
904
905%% set default options in menu 'Fields'
906switch FileType
907    case {'civx','civdata'}
908        [FieldList,ColorList]=set_field_list('U','V','C');
909        set(handles.FieldName,'String',[{'image'};FieldList;{'get_field...'}]);%standard menu for civx data
910        set(handles.FieldName,'Value',2) % set menu to 'velocity
911        set(handles.Coord_x,'Value',1);
912        set(handles.Coord_x,'String',{'X'});
913        set(handles.Coord_y,'Value',1);
914        set(handles.Coord_y,'String',{'Y'});
915    case 'netcdf'
916        set(handles.FieldName,'Value',1)
917        set(handles.FieldName,'String',{'get_field...'})
918        if isempty(i2_series)
919            i2=[];
920        else
921            i2=i2_series(1,ref_j+1,ref_i+1);
922        end
923        if isempty(j1_series)
924            j1=[];j2=[];
925        else
926            j1=j1_series(1,ref_j+1,ref_i+1);
927            if isempty(j2_series)
928                j2=[];
929            else
930                j2=j2_series(1,ref_j+1,ref_i+1);
931            end
932        end
933        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);
934%         hget_field=get_field(FileName);
935%         hhget_field=guidata(hget_field);
936%         get_field('RUN_Callback',hhget_field.RUN,[],hhget_field);
937    otherwise
938        set(handles.FieldName,'Value',1) % set menu to 'image'
939        set(handles.FieldName,'String',{'image'})
940        set(handles.Coord_x,'Value',1);
941        set(handles.Coord_x,'String',{'AX'});
942        set(handles.Coord_y,'Value',1);
943        set(handles.Coord_y,'String',{'AY'});
944end
945
946%------------------------------------------------------------------------
947function num_first_i_Callback(hObject, eventdata, handles)
948%------------------------------------------------------------------------
949num_last_i_Callback(hObject, eventdata, handles)
950
951%------------------------------------------------------------------------
952function num_last_i_Callback(hObject, eventdata, handles)
953%------------------------------------------------------------------------
954SeriesData=get(handles.series,'UserData');
955if ~isfield(SeriesData,'Time')
956    SeriesData.Time{1}=[];
957end
958displ_time(handles);
959
960%------------------------------------------------------------------------
961function num_first_j_Callback(hObject, eventdata, handles)
962%------------------------------------------------------------------------
963 num_last_j_Callback(hObject, eventdata, handles)
964
965%------------------------------------------------------------------------
966function num_last_j_Callback(hObject, eventdata, handles)
967%------------------------------------------------------------------------
968first_j=str2num(get(handles.num_first_j,'String'));
969last_j=str2num(get(handles.num_last_j,'String'));
970ref_j=ceil((first_j+last_j)/2);
971set(handles.num_ref_j,'String', num2str(ref_j))
972num_ref_j_Callback(hObject, eventdata, handles)
973SeriesData=get(handles.series,'UserData');
974if ~isfield(SeriesData,'Time')
975    SeriesData.Time{1}=[];
976end
977displ_time(handles);
978
979
980%------------------------------------------------------------------------
981% ---- find the times corresponding to the first and last indices of a series
982function displ_time(handles)
983%------------------------------------------------------------------------
984SeriesData=get(handles.series,'UserData');%
985ref_i=[str2num(get(handles.num_first_i,'String')) str2num(get(handles.num_last_i,'String'))];
986ref_j=[str2num(get(handles.num_first_j,'String')) str2num(get(handles.num_last_j,'String'))];
987TimeTable=get(handles.TimeTable,'Data');
988Pairs=get(handles.PairString,'Data');
989for iview=1:size(TimeTable,1)
990    if size(SeriesData.Time,1)<iview
991        break
992    end
993    i1=ref_i;
994    j1=ref_j;
995    i2=ref_i;
996    j2=ref_j;
997    % case of pairs
998    if ~isempty(Pairs{iview,1})
999        r=regexp(Pairs{iview,1},'(?<mode>(Di=)|(Dj=)) -*(?<num1>\d+)\|(?<num2>\d+)','names');
1000        if isempty(r)
1001            r=regexp(Pairs{iview,1},'(?<num1>\d+)(?<mode>-)(?<num2>\d+)','names');
1002        end
1003        switch r.mode
1004            case 'Di='  %  case 'series(Di)')
1005                i1=ref_i-str2num(r.num1);
1006                i2=ref_i+str2num(r.num2);
1007            case 'Dj='  %  case 'series(Dj)'
1008                j1=ref_j-str2num(r.num1);
1009                j2=ref_j+str2num(r.num2);
1010            case '-'  % case 'bursts'
1011                j1=str2num(r.num1)*ones(size(ref_i));
1012                j2=str2num(r.num2)*ones(size(ref_i));
1013        end
1014    end
1015    TimeTable{iview,2}=[];
1016    TimeTable{iview,3}=[];
1017    if size(SeriesData.Time{iview},1)>=i2(2)&&size(SeriesData.Time{iview},1)>=j2(2)
1018        if isempty(ref_j)
1019            time_first=(SeriesData.Time{iview}(i1(1)+1)+SeriesData.Time{iview}(i2(1)+1))/2;
1020            time_last=(SeriesData.Time{iview}(i1(2)+1)+SeriesData.Time{iview}(i2(2))+1)/2;
1021        else
1022            time_first=(SeriesData.Time{iview}(i1(1)+1,j1(1)+1)+SeriesData.Time{iview}(i2(1)+1,j2(1)+1))/2;
1023            time_last=(SeriesData.Time{iview}(i1(2)+1,j1(2)+1)+SeriesData.Time{iview}(i2(2)+1,j2(2)+1))/2;
1024        end
1025        TimeTable{iview,2}=time_first; %TODO: take into account pairs
1026        TimeTable{iview,3}=time_last; %TODO: take into account pairs
1027    end
1028end
1029set(handles.TimeTable,'Data',TimeTable)
1030
1031%% set the waitbar position with respect to the min and max in the series
1032for iview=1:numel(SeriesData.i1_series)
1033    pair_max{iview}=squeeze(max(SeriesData.i1_series{iview},[],1)); %max on pair index
1034    if (strcmp(get(handles.num_first_j,'Visible'),'off')&& size(pair_max{iview},2)~=1)
1035        pair_max{iview}=squeeze(max(pair_max{iview},[],1)); % consider only the i index
1036    end
1037    pair_max{iview}=reshape(pair_max{iview},1,[]);
1038    index_min(iview)=find(pair_max{iview}>0, 1 );
1039    index_max(iview)=find(pair_max{iview}>0, 1, 'last' );
1040end
1041[index_min,iview_min]=min(index_min);
1042[index_max,iview_max]=min(index_max);
1043if size(SeriesData.i1_series{iview_min},2)==1% movie
1044    index_first=ref_i(1);
1045    index_last=ref_i(2);
1046else
1047    index_first=(ref_i(1)-1)*(size(SeriesData.i1_series{iview_min},1))+ref_j(1)+1;
1048    index_last=(ref_i(2)-1)*(size(SeriesData.i1_series{iview_max},1))+ref_j(2)+1;
1049end
1050range=index_max-index_min+1;
1051coeff_min=(index_first-index_min)/range;
1052coeff_max=(index_last-index_min+1)/range;
1053Position=get(handles.Waitbar,'Position');% position of the waitbar:= [ x,y, width, height]
1054Position_status=get(handles.FileStatus,'Position');
1055Position(1)=coeff_min*Position_status(3)+Position_status(1);
1056Position(3)=Position_status(3)*(coeff_max-coeff_min);
1057set(handles.Waitbar,'Position',Position)
1058update_waitbar(handles.Waitbar,0)
1059
1060%------------------------------------------------------------------------
1061% --- Executes when selected cell(s) is changed in PairString.
1062function PairString_CellSelectionCallback(hObject, eventdata, handles)
1063%------------------------------------------------------------------------   
1064set(handles.ListView,'Value',eventdata.Indices(1))% detect the selected raw index
1065ListView_Callback ([],[],handles) % update the list of available pairs
1066
1067%------------------------------------------------------------------------
1068%------------------------------------------------------------------------
1069%  III - FUNCTIONS ASSOCIATED TO THE FRAME SET PAIRS
1070%------------------------------------------------------------------------
1071%------------------------------------------------------------------------
1072% --- Executes on selection change in ListView.
1073function ListView_Callback(hObject, eventdata, handles)
1074%------------------------------------------------------------------------   
1075SeriesData=get(handles.series,'UserData');
1076i2_series=[];
1077j2_series=[];
1078iview=get(handles.ListView,'Value');
1079if ~isempty(SeriesData.i2_series{iview})
1080    i2_series=SeriesData.i2_series{iview};
1081end
1082if ~isempty(SeriesData.j2_series{iview})
1083    j2_series=SeriesData.j2_series{iview};
1084end
1085update_mode(handles,SeriesData.i1_series{iview},SeriesData.i2_series{iview},...
1086    SeriesData.j1_series{iview},SeriesData.j2_series{iview},SeriesData.Time{iview})
1087
1088%------------------------------------------------------------------------
1089% --- Executes on button press in mode.
1090function mode_Callback(hObject, eventdata, handles)
1091%------------------------------------------------------------------------       
1092SeriesData=get(handles.series,'UserData');
1093iview=get(handles.ListView,'Value');
1094mode_list=get(handles.mode,'String');
1095mode=mode_list{get(handles.mode,'Value')};
1096if isequal(mode,'bursts')
1097    enable_i(handles,'On')
1098    enable_j(handles,'Off') %do not display j index scanning in burst mode (j is fixed by the burst choice)
1099else
1100    enable_i(handles,'On')
1101    enable_j(handles,'Off')
1102end
1103fill_ListPair(handles,SeriesData.i1_series{iview},SeriesData.i2_series{iview},...
1104    SeriesData.j1_series{iview},SeriesData.j2_series{iview},SeriesData.Time{iview})
1105ListPairs_Callback([],[],handles)
1106
1107%-------------------------------------------------------------
1108% --- Executes on selection in ListPairs.
1109function ListPairs_Callback(hObject,eventdata,handles)
1110%------------------------------------------------------------
1111list_pair=get(handles.ListPairs,'String');%get the menu of image pairs
1112if isempty(list_pair)
1113    string='';
1114else
1115    string=list_pair{get(handles.ListPairs,'Value')};
1116    string=regexprep(string,',.*','');%removes time indication (after ',')
1117end
1118PairString=get(handles.PairString,'Data');
1119iview=get(handles.ListView,'Value');
1120PairString{iview,1}=string;
1121% report the selected pair string to the table PairString
1122set(handles.PairString,'Data',PairString)
1123
1124%------------------------------------------------------------------------
1125function num_ref_i_Callback(hObject, eventdata, handles)
1126%------------------------------------------------------------------------
1127mode_list=get(handles.mode,'String');
1128mode=mode_list{get(handles.mode,'Value')};
1129SeriesData=get(handles.series,'UserData');
1130iview=get(handles.ListView,'Value');
1131fill_ListPair(handles,SeriesData.i1_series{iview},SeriesData.i2_series{iview},...
1132    SeriesData.j1_series{iview},SeriesData.j2_series{iview},SeriesData.Time{iview});% update the menu of pairs depending on the available netcdf files
1133ListPairs_Callback([],[],handles)
1134
1135%------------------------------------------------------------------------
1136function num_ref_j_Callback(hObject, eventdata, handles)
1137%------------------------------------------------------------------------
1138num_ref_i_Callback(hObject, eventdata, handles)
1139
1140%------------------------------------------------------------------------
1141function update_mode(handles,i1_series,i2_series,j1_series,j2_series,time)
1142%------------------------------------------------------------------------   
1143% check_burst=0;
1144if isempty(j2_series)% no j pair
1145    if isempty(i2_series)
1146        set(handles.mode,'Value',1)
1147        set(handles.mode,'String',{''})% no pair menu to display
1148    else   
1149        set(handles.mode,'Value',1)
1150        set(handles.mode,'String',{'series(Di)'}) % pair menu with only option Di
1151    end
1152else %existence of j pairs
1153    pair_max=squeeze(max(i1_series,[],1)); %max on pair index
1154    j_max=max(pair_max,[],1);
1155    MaxIndex_i=max(find(j_max))-1;% max ref index i
1156    MinIndex_i=min(find(j_max))-1;% min ref index i
1157    i_max=max(pair_max,[],2);
1158    MaxIndex_j=max(find(i_max))-1;% max ref index i
1159    MinIndex_j=min(find(i_max))-1;% min ref index i
1160    if MaxIndex_j==MinIndex_j
1161        set(handles.mode,'Value',1);
1162        set(handles.mode,'String',{'bursts'})
1163%         check_burst=1;
1164    elseif MaxIndex_i==MinIndex_i
1165        set(handles.mode,'Value',1);
1166        set(handles.mode,'String',{'series(Dj)'})
1167    else
1168        set(handles.mode,'String',{'bursts';'series(Dj)'})
1169        if (MaxIndex_j-MinIndex_j)>10
1170            set(handles.mode,'Value',2);%set mode to series(Dj) if more than 10 j values
1171        else
1172            set(handles.mode,'Value',1);
1173%             check_burst=1;
1174        end
1175    end
1176end
1177% if check_burst
1178%     enable_i(handles,'On')
1179%     enable_j(handles,'Off') %do not display j index scanning in burst mode (j is fixed by the burst choice)
1180% else
1181%     enable_i(handles,'On')
1182%     if isempty(j1_series)
1183%          enable_j(handles,'Off')
1184%     else
1185%         enable_j(handles,'On')
1186%     end
1187% end
1188fill_ListPair(handles,i1_series,i2_series,j1_series,j2_series,time)
1189ListPairs_Callback([],[],handles)
1190
1191%--------------------------------------------------------------
1192% determine the menu for civ1 pairstring depending on existing netcdf files
1193% with the reference indices num_ref_i and num_ref_j
1194%----------------------------------------------------------------
1195function fill_ListPair(handles,i1_series,i2_series,j1_series,j2_series,time)
1196
1197mode_list=get(handles.mode,'String');
1198mode=mode_list{get(handles.mode,'Value')};
1199ref_i=str2num(get(handles.num_ref_i,'String'));
1200if isempty(ref_i)
1201    ref_i=1;
1202end
1203if strcmp(get(handles.num_ref_j,'Visible'),'on')
1204    ref_j=str2num(get(handles.num_ref_j,'String'));
1205    if isempty(ref_j)
1206        ref_j=1;
1207    end
1208else
1209    ref_j=1;
1210end
1211TimeUnit=get(handles.TimeUnit,'String');
1212if length(TimeUnit)>=1
1213    dtunit=['m' TimeUnit];
1214else
1215    dtunit='e-03';
1216end
1217
1218displ_pair={};
1219if strcmp(mode,'series(Di)')
1220    if isempty(i2_series)
1221        msgbox_uvmat('ERROR','no i1-i2 pair available')
1222        return
1223    end
1224    diff_i=i2_series-i1_series;
1225    min_diff=min(diff_i(diff_i>0));
1226    max_diff=max(diff_i(diff_i>0));
1227    for ipair=min_diff:max_diff
1228        if numel(diff_i(diff_i==ipair))>0
1229            pair_string=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
1230            if ~isempty(time)
1231                if ref_i<=floor(ipair/2)
1232                    ref_i=floor(ipair/2)+1;% shift ref_i to get the first pair
1233                end
1234                Dt=time(ref_i+ceil(ipair/2),ref_j)-time(ref_i-floor(ipair/2),ref_j);
1235                pair_string=[pair_string ', Dt=' num2str(Dt) ' ' dtunit];
1236            end
1237            displ_pair=[displ_pair;{pair_string}];
1238        end
1239    end
1240    if ~isempty(displ_pair)
1241        displ_pair=[displ_pair;{'Di=*|*'}];
1242    end
1243elseif strcmp(mode,'series(Dj)')
1244    if isempty(j2_series)
1245        msgbox_uvmat('ERROR','no j1-j2 pair available')
1246        return
1247    end
1248    diff_j=j2_series-j1_series;
1249    min_diff=min(diff_j(diff_j>0));
1250    max_diff=max(diff_j(diff_j>0));
1251    for ipair=min_diff:max_diff
1252        if numel(diff_j(diff_j==ipair))>0
1253            pair_string=['Dj= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
1254            if ~isempty(time)
1255                if ref_j<=floor(ipair/2)
1256                    ref_j=floor(ipair/2)+1;% shift ref_i to get the first pair
1257                end
1258                Dt=time(ref_i,ref_j+ceil(ipair/2))-time(ref_i,ref_j-floor(ipair/2));
1259                pair_string=[pair_string ', Dt=' num2str(Dt) ' ' dtunit];
1260            end
1261            displ_pair=[displ_pair;{pair_string}];
1262        end
1263    end
1264    if ~isempty(displ_pair)
1265        displ_pair=[displ_pair;{'Dj=*|*'}];
1266    end
1267elseif strcmp(mode,'bursts')
1268    if isempty(j2_series)
1269        msgbox_uvmat('ERROR','no j1-j2 pair available')
1270        return
1271    end
1272    diff_j=j2_series-j1_series;
1273    min_j1=min(j1_series(j1_series>0));
1274    max_j1=max(j1_series(j1_series>0));
1275    min_j2=min(j2_series(j2_series>0));
1276    max_j2=max(j2_series(j2_series>0));
1277    for pair1=min_j1:min(max_j1,min_j1+20)
1278        for pair2=min_j2:min(max_j2,min_j2+20)
1279        if numel(j1_series(j1_series==pair1))>0 && numel(j2_series(j2_series==pair2))>0
1280            displ_pair=[displ_pair;{['j= ' num2str(pair1) '-' num2str(pair2)]}];
1281        end
1282        end
1283    end
1284    if ~isempty(displ_pair)
1285        displ_pair=[displ_pair;{'j=*-*'}];
1286    end
1287end
1288set(handles.num_ref_i,'String',num2str(ref_i)) % update ref_i and ref_j
1289set(handles.num_ref_j,'String',num2str(ref_j))
1290
1291%% display list of pairstring
1292displ_pair_list=get(handles.ListPairs,'String');
1293NewVal=[];
1294if ~isempty(displ_pair_list)
1295Val=get(handles.ListPairs,'Value');
1296NewVal=find(strcmp(displ_pair_list{Val},displ_pair),1);% look at the previous display in the new menu displ_pï¿œir
1297end
1298if ~isempty(NewVal)
1299    set(handles.ListPairs,'Value',NewVal)
1300else
1301    set(handles.ListPairs,'Value',1)
1302end
1303set(handles.ListPairs,'String',displ_pair)
1304
1305%-------------------------------------
1306function enable_i(handles,state)
1307set(handles.i_txt,'Visible',state)
1308set(handles.num_first_i,'Visible',state)
1309set(handles.num_last_i,'Visible',state)
1310set(handles.num_incr_i,'Visible',state)
1311% set(handles.num_MaxIndex_i,'Visible',state)
1312set(handles.num_ref_i,'Visible',state)
1313set(handles.ref_i_text,'Visible',state)
1314
1315%-----------------------------------
1316function enable_j(handles,state)
1317set(handles.j_txt,'Visible',state)
1318set(handles.num_first_j,'Visible',state)
1319set(handles.num_last_j,'Visible',state)
1320set(handles.num_incr_j,'Visible',state)
1321set(handles.num_ref_j,'Visible',state)
1322set(handles.ref_j_text,'Visible',state)
1323% if strcmp(state,'off')
1324%     set(handles.MinIndex,'ColumnName',{'imax'})
1325% set(handles.MinIndex,'ColumnEditable',logical(0))
1326% else
1327%         set(handles.MinIndex,'ColumnName',{'imax','jmax'})
1328% end
1329
1330
1331%%%%%%%%%%%%%%%%%%%%
1332%%  MAIN ActionName FUNCTIONS
1333%%%%%%%%%%%%%%%%%%%%
1334%------------------------------------------------------------------------
1335% --- Executes on button press in RUN.
1336function RUN_Callback(hObject, eventdata, handles)
1337%------------------------------------------------------------------------
1338
1339set(handles.RUN,'BusyAction','queue');
1340set(0,'CurrentFigure',handles.series)
1341set(handles.RUN, 'Enable','Off')
1342set(handles.RUN,'BackgroundColor',[0.831 0.816 0.784])
1343drawnow
1344
1345%% read the input parameters and set the output dir and nomenclature
1346[Series,OutputDir,errormsg]=prepare_jobs(handles);% get parameters form the GUI series
1347if ~isempty(errormsg)
1348    if ~strcmp(errormsg,'Cancel')
1349    msgbox_uvmat('ERROR',errormsg)
1350    end
1351    STOP_Callback([],[], handles)
1352    return
1353end
1354OutputNomType=nomtype2pair(Series.InputTable{1,4});% nomenclature for output files
1355DirXml=fullfile(OutputDir,'0_XML');
1356if ~exist(DirXml,'dir')
1357    [tild,msg1]=mkdir(DirXml);
1358    if ~strcmp(msg1,'')
1359        msgbox_uvmat('ERROR',['cannot create ' DirXml ': ' msg1]);%error message for directory creation
1360        return
1361    end
1362end
1363
1364%% select the Action modes
1365RunMode='local';%default
1366if isfield(Series.Action,'RunMode')
1367RunMode=Series.Action.RunMode;
1368end
1369ActionExt='.m';%default
1370if isfield(Series.Action,'ActionExt')
1371    ActionExt=Series.Action.ActionExt;% '.m' or '.sh' (compiled)
1372end
1373ActionName=Series.Action.ActionName;
1374ActionPath=Series.Action.ActionPath;
1375path_series=fileparts(which('series'));
1376
1377%% create the Action fct handle if RunMode option = 'local'
1378if strcmp(RunMode,'local')
1379    if ~isequal(ActionPath,path_series)
1380        eval(['spath=which(''' ActionName ''');']) %spath = current path of the selected function ACTION
1381        if ~exist(ActionPath,'dir')
1382            msgbox_uvmat('ERROR',['The prescribed function path ' ActionPath ' does not exist']);
1383            return
1384        end
1385        if ~isequal(spath,ActionPath)
1386            addpath(ActionPath)% add the prescribed path if not the current one
1387        end
1388    end
1389    eval(['h_fun=@' ActionName ';'])%create a function handle for ACTION
1390    if ~isequal(ActionPath,path_series)
1391        rmpath(ActionPath)% add the prescribed path if not the current one
1392    end
1393end
1394
1395%% Get RunTime code from the file PARAM.xml (needed to run compiled functions)
1396errormsg='';%default error message
1397xmlfile=fullfile(path_series,'PARAM.xml');
1398test_batch=0;%default: ,no batch mode available
1399if ~exist(xmlfile,'file')
1400    [success,message]=copyfile(fullfile(path_series,'PARAM.xml.default'),xmlfile);
1401end
1402RunTime='';
1403if strcmp(ActionExt,'.sh')
1404    if exist(xmlfile,'file')
1405        s=xml2struct(xmlfile);
1406        if strcmp(RunMode,'cluster_oar') && isfield(s,'BatchParam')
1407            if isfield(s.BatchParam,'RunTime')
1408                RunTime=s.BatchParam.RunTime;
1409            end
1410            if isfield(s.BatchParam,'NbCore')
1411                NbCore=s.BatchParam.NbCore;
1412            end
1413        elseif (strcmp(RunMode,'background')||strcmp(RunMode,'local')) && isfield(s,'RunParam')
1414            if isfield(s.RunParam,'RunTime')
1415                RunTime=s.RunParam.RunTime;
1416            end
1417            if isfield(s.RunParam,'NbCore')
1418                NbCore=s.RunParam.NbCore;
1419            end
1420        end
1421    end
1422    if isempty(RunTime) && strcmp(RunMode,'cluster_oar')
1423        msgbox_uvmat('ERROR','RunTime name not found in PARAM.xml, compiled version .sh cannot run on cluster')
1424        return
1425    end
1426%     Series.RunTime=RunTime;
1427end
1428
1429%% set nbre of cluster cores and processes
1430switch RunMode
1431    case {'local','background'}
1432        NbCore=1;% no need to split the calculation
1433    case 'cluster_oar'
1434        if strcmp(Series.Action.ActionExt,'.m')% case of Matlab function (uncompiled)
1435            NbCore=1;% one core used only (limitation of Matlab licences)
1436            msgbox_uvmat('WARNING','Number of cores =1: select the compiled version civ_matlab.sh for multi-core processing');
1437            extra_oar='';
1438        else
1439            answer=inputdlg({'Number of cores (max 36)','extra oar options'},'oarsub parameter',1,{'12',''});
1440            NbCore=str2double(answer{1});
1441            extra_oar=answer{2};
1442        end
1443end
1444if ~isfield(Series.IndexRange,'NbSlice')
1445    Series.IndexRange.NbSlice=[];
1446end
1447if isempty(Series.IndexRange.NbSlice)
1448    NbProcess=NbCore;% choose one process per core
1449else
1450    NbProcess=Series.IndexRange.NbSlice;% the nbre of run processes is equal to the number of slices
1451    NbCore=min(NbCore,NbProcess);% at least one process per core
1452end
1453       
1454
1455%% read index ranges
1456[first_i,incr_i,last_i,first_j,incr_j,last_j,errormsg]=get_index_range(Series.IndexRange);
1457if ~isempty(errormsg)
1458    msgbox_uvmat('ERROR',['series/Run_Callback/get_index_range' errormsg])
1459    set(handles.RUN, 'Enable','On'),
1460    set(handles.RUN,'BackgroundColor',[1 0 0])
1461    return
1462else
1463    BlockLength=ceil(numel(first_i:incr_i:last_i)/NbProcess);
1464end
1465nbfield_j=numel(first_j:incr_j:last_j);
1466
1467%% record nbre of output files and starting time for computation for status
1468StatusData=get(handles.status,'UserData');
1469if isfield(StatusData,'OutputFileMode')
1470    switch StatusData.OutputFileMode
1471        case 'NbInput'
1472            StatusData.NbOutputFile=numel(first_i:incr_i:last_i)*numel(first_j:incr_j:last_j);
1473        case 'NbInput_i'
1474            StatusData.NbOutputFile=numel(first_i:incr_i:last_i);
1475        case 'NbSlice'   
1476            StatusData.NbOutputFile=str2num(get(handles.num_NbSlice,'String'));
1477    end
1478end
1479StatusData.TimeStart=now;
1480set(handles.status,'UserData',StatusData)
1481
1482%% direct processing on the current Matlab session
1483if strcmp (RunMode,'local')
1484    Series.RUNHandle=handles.RUN;
1485    Series.WaitbarHandle=handles.Waitbar;
1486    for iprocess=1:NbProcess
1487        if isempty(Series.IndexRange.NbSlice)
1488            Series.IndexRange.first_i=first_i+(iprocess-1)*BlockLength*incr_i;
1489            if Series.IndexRange.first_i>last_i
1490                break
1491            end
1492            Series.IndexRange.last_i=min(first_i+(iprocess)*BlockLength*incr_i-1,last_i);
1493        else
1494            Series.IndexRange.first_i= first_i+incr_i*(iprocess-1);
1495            Series.IndexRange.incr_i=incr_i*Series.IndexRange.NbSlice;
1496        end
1497        t=struct2xml(Series);
1498        t=set(t,1,'name','Series');
1499        filexml=fullfile_uvmat(DirXml,'',Series.InputTable{1,3},'.xml',OutputNomType,...
1500            Series.IndexRange.first_i,Series.IndexRange.last_i,first_j,last_j);
1501        save(t,filexml);
1502        switch ActionExt
1503            case '.m'
1504                h_fun(Series);
1505            case '.sh'
1506                switch computer
1507                    case {'PCWIN','PCWIN64'} %Windows system
1508                        filexml=regexprep(filexml,'\\','\\\\');% add '\' so that '\' are left as characters
1509                        system([fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml]);% TODO: adapt to DOS system
1510                    case {'GLNX86','GLNXA64','MACI64'}%Linux  system
1511                        system([fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml]);
1512                end
1513        end
1514    end
1515elseif strcmp(get(handles.OutputDirExt,'Visible'),'off')
1516    msgbox_uvmat('ERROR',['no output file for Action ' ActionName ', use run mode = local']);% a output dir is needed for background option
1517    return
1518else
1519    %% processing on a different session of the same computer (background) or cluster, create executable files
1520    batch_file_list=cell(NbProcess,1);% initiate the list of executable files
1521    DirBat=fullfile(OutputDir,'0_BAT');
1522    %create subdirectory for executable files
1523    if ~exist(DirBat,'dir')
1524        [tild,msg1]=mkdir(DirBat);
1525        if ~strcmp(msg1,'')
1526            msgbox_uvmat('ERROR',['cannot create ' DirBat ': ' msg1]);%error message for directory creation
1527            return
1528        end
1529    end
1530    %create subdirectory for log files
1531    DirLog=fullfile(OutputDir,'0_LOG');
1532    if ~exist(DirLog,'dir')
1533        [tild,msg1]=mkdir(DirLog);
1534        if ~strcmp(msg1,'')
1535            msgbox_uvmat('ERROR',['cannot create ' DirLog ': ' msg1]);%error message for directory creation
1536            return
1537        end
1538    end
1539    for iprocess=1:NbProcess
1540        if isempty(Series.IndexRange.NbSlice)% process by blocks of i index
1541            Series.IndexRange.first_i=first_i+(iprocess-1)*BlockLength*incr_i;
1542            if Series.IndexRange.first_i>last_i
1543                NbProcess=iprocess-1;
1544                break% leave the loop, we are at the end of the calculation
1545            end
1546            Series.IndexRange.last_i=min(last_i,first_i+(iprocess)*BlockLength*incr_i-1);
1547        else% process by slices of i index if NbSlice is defined, computation in a single process if NbSlice =1
1548            Series.IndexRange.first_i= first_i+iprocess-1;
1549            Series.IndexRange.incr_i=incr_i*Series.IndexRange.NbSlice;
1550        end
1551       
1552        % create, fill and save the xml parameter file
1553        t=struct2xml(Series);
1554        t=set(t,1,'name','Series');
1555        filexml=fullfile_uvmat(DirXml,'',Series.InputTable{1,3},'.xml',OutputNomType,...
1556            Series.IndexRange.first_i,Series.IndexRange.last_i,first_j,last_j);
1557        save(t,filexml);% save the parameter file
1558       
1559        %create the executable file
1560%         filebat=fullfile_uvmat(DirBat,'',Series.InputTable{1,3},'.bat',OutputNomType,...
1561%             Series.IndexRange.first_i,Series.IndexRange.last_i,first_j,last_j);
1562         filebat=fullfile_uvmat(DirBat,'',Series.InputTable{1,3},'.sh',OutputNomType,...
1563           Series.IndexRange.first_i,Series.IndexRange.last_i,first_j,last_j);
1564        batch_file_list{iprocess}=filebat;
1565        [fid,message]=fopen(filebat,'w');% create the executable file
1566        if isequal(fid,-1)
1567            msgbox_uvmat('ERROR', ['creation of .bat file: ' message]);
1568            return
1569        end
1570       
1571        % set the log file name
1572        filelog=fullfile_uvmat(DirLog,'',Series.InputTable{1,3},'.log',OutputNomType,...
1573            Series.IndexRange.first_i,Series.IndexRange.last_i,first_j,last_j);
1574       
1575        % fill and save the executable file
1576        switch ActionExt
1577            case '.m'% Matlab function
1578                switch computer
1579                    case {'GLNX86','GLNXA64','MACI64'}
1580                        cmd=[...
1581                            '#!/bin/bash \n'...
1582                            '. /etc/sysprofile \n'...
1583                            'matlab -nodisplay -nosplash -nojvm -logfile ''' filelog ''' <<END_MATLAB \n'...
1584                            'addpath(''' path_series '''); \n'...
1585                            'addpath(''' Series.Action.ActionPath '''); \n'...
1586                            '' Series.Action.ActionName  '( ''' filexml '''); \n'...
1587                            'exit \n'...
1588                            'END_MATLAB \n'];
1589                        fprintf(fid,cmd);%fill the executable file with the  char string cmd
1590                        fclose(fid);% close the executable file
1591                        system(['chmod +x ' filebat]);% set the file to executable
1592                    case {'PCWIN','PCWIN64'}
1593                        text_matlabscript=['matlab -automation -logfile ' regexprep(filelog,'\\','\\\\')...
1594                            ' -r "addpath(''' regexprep(path_series,'\\','\\\\') ''');'...
1595                            'addpath(''' regexprep(Series.Action.ActionPath,'\\','\\\\') ''');'...
1596                            '' Series.Action.ActionName  '( ''' regexprep(filexml,'\\','\\\\') ''');exit"'];
1597                        fprintf(fid,text_matlabscript);%fill the executable file with the  char string cmd
1598                        fclose(fid);% close the executable file
1599                end
1600            case '.sh' % compiled Matlab function
1601                switch computer
1602                    case {'GLNX86','GLNXA64','MACI64'}
1603                        cmd=['#!/bin/bash \n '...
1604                            '#$ -cwd \n '...
1605                            'hostname && date \n '...
1606                            'umask 002 \n'...
1607                            fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml];%allow writting access to created files for user group
1608                        fprintf(fid,cmd);%fill the executable file with the  char string cmd
1609                        fclose(fid);% close the executable file
1610                        system(['chmod +x ' filebat]);% set the file to executable
1611                       
1612                    case {'PCWIN','PCWIN64'}    %       TODO: adapt to Windows system
1613                        %                                 cmd=['matlab -automation -logfile ' regexprep(filelog,'\\','\\\\')...
1614                        %                                     ' -r "addpath(''' regexprep(path_series,'\\','\\\\') ''');'...
1615                        %                                     'addpath(''' regexprep(Series.Action.ActionPath,'\\','\\\\') ''');'...
1616                        %                                     '' Series.Action.ActionName  '( ''' regexprep(filexml,'\\','\\\\') ''');exit"'];
1617                        fprintf(fid,cmd);
1618                        fclose(fid);
1619                        %                               dos([filebat ' &']);
1620                end
1621        end
1622    end
1623end
1624
1625%% launch the executable files for background or cluster processing
1626switch RunMode
1627    case 'background'
1628        for iprocess=1:NbProcess
1629            system([batch_file_list{iprocess} ' &'])% directly execute the command file for each process
1630        end
1631    case 'cluster_oar' % option 'oar-parexec' used
1632        %create subdirectory for oar command and log files
1633        DirOAR=fullfile(OutputDir,'0_OAR');
1634        if ~exist(DirOAR,'dir')
1635            [tild,msg1]=mkdir(DirOAR);
1636            if ~strcmp(msg1,'')
1637                msgbox_uvmat('ERROR',['cannot create ' DirOAR ': ' msg1]);%error message for directory creation
1638                return
1639            end
1640        end
1641        max_walltime=3600*12; % 12h max total calculation
1642        walltime_onejob=600;%seconds, max estimated time for asingle file index value
1643        filename_joblist=fullfile(DirOAR,'job_list.txt');%create name of the global executable file
1644        fid=fopen(filename_joblist,'w');
1645        for p=1:length(batch_file_list)
1646            fprintf(fid,[batch_file_list{p} '\n']);% list of exe files
1647        end
1648        fclose(fid);
1649        system(['chmod +x ' filename_joblist]);% set the file to executable
1650        oar_command=['oarsub -n CIVX '...
1651            '-t idempotent --checkpoint ' num2str(walltime_onejob+60) ' '...
1652            '-l /core=' num2str(NbCore) ','...
1653            'walltime=' datestr(min(1.05*walltime_onejob/86400*max(NbProcess*BlockLength*nbfield_j,NbCore)/NbCore,max_walltime/86400),13) ' '...
1654            '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
1655            '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
1656            extra_oar ' '...
1657            '"oar-parexec -s -f ' filename_joblist ' '...
1658            '-l ' filename_joblist '.log"\n'];
1659        filename_oarcommand=fullfile(DirOAR,'oar_command');
1660        fid=fopen(filename_oarcommand,'w');
1661        fprintf(fid,oar_command);
1662        fclose(fid);
1663        fprintf(oar_command);% display in command line
1664        %system(['chmod +x ' oar_command]);% set the file to executable
1665        system(oar_command);     
1666end
1667
1668%% reset the GUI series
1669update_waitbar(handles.Waitbar,1); % put the waitbar to end position to indicate launching is finished
1670set(handles.RUN, 'Enable','On')
1671set(handles.RUN,'BackgroundColor',[1 0 0])
1672set(handles.RUN, 'Value',0)
1673
1674%------------------------------------------------------------------------
1675function STOP_Callback(hObject, eventdata, handles)
1676%------------------------------------------------------------------------
1677set(handles.RUN, 'BusyAction','cancel')
1678set(handles.RUN,'BackgroundColor',[1 0 0])
1679set(handles.RUN,'enable','on')
1680set(handles.RUN, 'Value',0)
1681
1682% %------------------------------------------------------------------------
1683% % --- Executes on button press in BIN.
1684% function BIN_Callback(hObject, eventdata, handles)
1685% %------------------------------------------------------------------------
1686%     cmd=['#!/bin/bash \n '...
1687%         '#$ -cwd \n '...
1688%         'hostname && date \n '...
1689%         'umask 002 \n'...
1690%         Param.xml.CivmBin ' ' Param.xml.RunTime ' ' filename_xml ' ' OutputFile '.nc'];
1691%     
1692%------------------------------------------------------------------------
1693% --- Main launch command, called by RUN and BATCH
1694
1695function [Series,OutputDir,errormsg]=prepare_jobs(handles)
1696%INPUT:
1697% handles: handles of graphic objects on the GUI series
1698
1699%------------------------------------------------------------------------
1700OutputDir='';
1701errormsg='';
1702
1703%% Read parameters from series
1704Series=read_GUI(handles.series);
1705
1706%% get_field GUI
1707% if isfield(Series,'InputFields')&&isfield(Series.InputFields,'Field')
1708%     if strcmp(Series.InputFields.Field,'get_field...')
1709%         hget_field=findobj(allchild(0),'name','get_field');
1710%         Series.GetField=read_GUI(hget_field);
1711%     end
1712% end
1713
1714%% create the output data directory
1715%determine the root file corresponding to the first sub dir
1716if get(handles.RUN,'value') && isfield(Series,'OutputSubDir')
1717    SubDirOut=[get(handles.OutputSubDir,'String') Series.OutputDirExt];
1718    SubDirOutNew=SubDirOut;
1719    SeriesData=get(handles.series,'UserData');
1720    if size(Series.InputTable,1)>1 && isfield(SeriesData,'AllowInputSort') && SeriesData.AllowInputSort
1721        [tild,iview]=sort(Series.InputTable(:,2)); %subdirectories sorted in alphabetical order
1722        Series.InputTable=Series.InputTable(iview,:);
1723    end
1724    detect=exist(fullfile(Series.InputTable{1,1},SubDirOutNew),'dir');% test if  the dir  already exist
1725    check_create=1; %need to create the result directory by default
1726    while detect
1727        answer=msgbox_uvmat('INPUT_Y-N',['use existing ouput directory: ' fullfile(Series.InputTable{1,1},SubDirOutNew) ', possibly delete previous data']);
1728        if strcmp(answer,'Cancel')
1729            errormsg='Cancel';
1730            return
1731        elseif strcmp(answer,'Yes')
1732            detect=0;
1733            check_create=0;
1734        else
1735            r=regexp(SubDirOutNew,'(?<root>.*\D)(?<num1>\d+)$','names');%detect whether name ends by a number
1736            if isempty(r)
1737                r(1).root=[SubDirOutNew '_'];
1738                r(1).num1='0';
1739            end
1740            SubDirOutNew=[r(1).root num2str(str2num(r(1).num1)+1)];%increment the index by 1 or put 1
1741            detect=exist(fullfile(Series.InputTable{1,1},SubDirOutNew),'dir');% test if  the dir  already exists   
1742            check_create=1;
1743        end
1744    end
1745    Series.OutputDirExt=regexprep(SubDirOutNew,Series.OutputSubDir,'');
1746    Series.OutputRootFile=Series.InputTable{1,3};% the first sorted RootFile taken for output
1747    set(handles.OutputDirExt,'String',Series.OutputDirExt)
1748    OutputDir=fullfile(Series.InputTable{1,1},[Series.OutputSubDir Series.OutputDirExt]);% full name (with path) of output directory
1749    if check_create    % create output directory if it does not exist
1750        [tild,msg1]=mkdir(OutputDir);
1751        if ~strcmp(msg1,'')
1752            errormsg=['cannot create ' OutputDir ': ' msg1];%error message for directory creation
1753            return
1754        end
1755    end
1756   % RootOut=fullfile(OutputDir,Series.InputTable{1,3});% name of the parameter xml file set in this directory
1757end
1758
1759%% removes unused information on Series
1760if isfield(Series,'Pairs')
1761    Series=rmfield(Series,'Pairs'); %info Pairs not needed for output
1762end
1763Series.IndexRange=rmfield(Series.IndexRange,'TimeTable');
1764% Series.IndexRange=rmfield(Series.IndexRange,'MinIndex');
1765% Series.IndexRange=rmfield(Series.IndexRange,'MaxIndex');
1766empty_line=false(size(Series.InputTable,1),1);
1767for iline=1:size(Series.InputTable,1)
1768    empty_line(iline)=isequal(Series.InputTable(iline,1:3),{'','',''});
1769end
1770Series.InputTable(empty_line,:)=[];
1771
1772%------------------------------------------------------------------------
1773% --- Executes on selection change in ActionName.
1774function ActionName_Callback(hObject, eventdata, handles)
1775%------------------------------------------------------------------------
1776%% stop any ongoing series processing
1777if isequal(get(handles.RUN,'Value'),1)
1778    answer= msgbox_uvmat('INPUT_Y-N','stop current Action process?');
1779    if strcmp(answer,'Yes')
1780        STOP_Callback(hObject, eventdata, handles)
1781    else
1782        return
1783    end
1784end
1785set(handles.ActionName,'BackgroundColor',[1 1 0])
1786drawnow
1787
1788%% get Action name and path
1789nb_builtin_ACTION=4; %nbre of functions initially proposed in the menu ActionName (as defined in the Opening fct of series)
1790ActionList=get(handles.ActionName,'String');% list menu fields
1791ActionIndex=get(handles.ActionName,'Value');
1792if ~isequal(ActionIndex,1)
1793    InputTable=get(handles.InputTable,'Data');
1794    if isempty(InputTable{1,4})
1795        msgbox_uvmat('ERROR','no input file available: use Open in the menu bar')
1796        return
1797    end
1798end
1799ActionName= ActionList{get(handles.ActionName,'Value')}; % selected function name
1800ActionPathList=get(handles.ActionName,'UserData');%list of recorded paths to functions of the list ActionName
1801
1802%% add a new function to the menu if 'more...' has been selected in the menu ActionName
1803if isequal(ActionName,'more...')
1804    [FileName, PathName] = uigetfile( ...
1805        {'*.m', ' (*.m)';
1806        '*.m',  '.m files '; ...
1807        '*.*', 'All Files (*.*)'}, ...
1808        'Pick a series processing function ',get(handles.ActionPath,'String'));
1809    if length(FileName)<2
1810        return
1811    end
1812    [ActionPath,ActionName,ActionExt]=fileparts(FileName);
1813   
1814    % insert the choice in the menu ActionName
1815    ActionIndex=find(strcmp(ActionName,ActionList),1);% look for the selected function in the menu Action
1816    if isempty(ActionIndex)%the input string does not exist in the menu
1817        ActionIndex= length(ActionList);
1818        ActionList=[ActionList(1:end-1);{ActionName};ActionList(end)];% the selected function is appended in the menu, before the last item 'more...'
1819        set(handles.ActionName,'String',ActionList)
1820    end
1821   
1822    % record the file extension and extend the path list if it is a new extension
1823    ActionExtList=get(handles.ActionExt,'String');
1824    ActionExtIndex=find(strcmp(ActionExt,ActionExtList), 1);
1825    if isempty(ActionExtIndex)
1826        set(handles.ActionExt,'String',[ActionExtList;{ActionExt}])
1827        ActionExtIndex=numel(ActionExtList)+1;
1828        ActionPathNew=cell(size(ActionPathList,1),1);%new column of ActionPath
1829        ActionPathList=[ActionPathList ActionPathNew];
1830    end
1831    set(handles.ActionName,'UserData',ActionPathList);
1832
1833    % remove old Action options in the menu (keeping a menu length <nb_builtin_ACTION+5)
1834    if length(ActionList)>nb_builtin_ACTION+5; %nb_builtin=nbre of functions always remaining in the initial menu
1835        nbremove=length(ActionList)-nb_builtin_ACTION-5;
1836        ActionList(nb_builtin_ACTION+1:end-5)=[];
1837        ActionPathList(nb_builtin_ACTION+1:end-4,:)=[];
1838        ActionIndex=ActionIndex-nbremove;
1839    end
1840   
1841    % record action menu, choice and path
1842    set(handles.ActionName,'Value',ActionIndex)
1843    set(handles.ActionName,'String',ActionList)
1844    set(handles.ActionExt,'Value',ActionExtIndex)
1845    ActionPathList{ActionIndex,ActionExtIndex}=PathName;
1846       
1847    %record the user defined menu additions in personal file profil_perso
1848    dir_perso=prefdir;
1849    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
1850    if nb_builtin_ACTION+1<=numel(ActionList)-1
1851        ActionListUser=ActionList(nb_builtin_ACTION+1:numel(ActionList)-1);
1852        ActionPathListUser=ActionPathList(nb_builtin_ACTION+1:numel(ActionList)-1,:);
1853        ActionExtListUser={};
1854        if numel(ActionExtList)>2
1855            ActionExtListUser=ActionExtList(3:end);
1856        end
1857        if exist(profil_perso,'file')
1858            save(profil_perso,'ActionListUser','ActionPathListUser','ActionExtListUser','-append')
1859        else
1860            save(profil_perso,'ActionListUser','ActionPathListUser','ActionExtListUser','-V6')
1861        end
1862    end
1863end
1864
1865%% check the current ActionPath to the selected function
1866ActionPath=ActionPathList{ActionIndex};%current recorded path
1867set(handles.ActionPath,'String',ActionPath); %show the path to the senlected function
1868
1869%% reinitialise the waitbar
1870update_waitbar(handles.Waitbar,0)
1871
1872%% default setting for the visibility of the GUI elements
1873% set(handles.FieldTransform,'Visible','off')
1874% set(handles.CheckObject,'Visible','off');
1875% set(handles.ProjObject,'Visible','off');
1876% set(handles.CheckMask,'Visible','off')
1877% set(handles.Mask,'Visible','off')
1878
1879%% create the function handle for Action
1880path_series=which('series');
1881if ~isequal(ActionPath,path_series)
1882    eval(['spath=which(''' ActionName ''');']) %spath = current path of the selected function ACTION
1883    if ~exist(ActionPath,'dir')
1884        errormsg=['The prescribed function path ' ActionPath ' does not exist'];
1885        return
1886    end
1887    if ~isequal(spath,ActionPath)
1888        addpath(ActionPath)% add the prescribed path if not the current one
1889    end
1890end
1891eval(['h_fun=@' ActionName ';'])%create a function handle for ACTION
1892if ~isequal(ActionPath,path_series)
1893        rmpath(ActionPath)% add the prescribed path if not the current one   
1894end
1895
1896%% Activate the Action fct
1897[Series,tild,errormsg]=prepare_jobs(handles);% read the parameters from the GUI series
1898if ~isempty(errormsg)
1899    if ~strcmp(errormsg,'Cancel')
1900    msgbox_uvmat('ERROR',errormsg)
1901    end
1902    return
1903end
1904ParamOut=h_fun(Series);
1905
1906%% Put the first line of the selected Action fct as tooltip help
1907try
1908    [fid,errormsg] =fopen([ActionName '.m']);
1909    InputText=textscan(fid,'%s',1,'delimiter','\n');
1910    fclose(fid);
1911    set(handles.ActionName,'ToolTipString',InputText{1}{1})% put the first line of the selected function as tooltip help
1912end
1913
1914%% Detect the types of input files
1915SeriesData=get(handles.series,'UserData');
1916nb_civ=0;nb_netcdf=0;
1917if ~isempty(SeriesData)
1918    nb_civ=numel(find(strcmp('civx',SeriesData.FileType)|strcmp('civdata',SeriesData.FileType)));
1919    nb_netcdf=numel(find(strcmp('netcdf',SeriesData.FileType)));
1920end
1921
1922%% Check whether alphabetical sorting of input Subdir is alowed by the Action fct  (for multiples series entries)
1923SeriesData.AllowInputSort=0;%default
1924if isfield(ParamOut,'AllowInputSort')&&isequal(ParamOut.AllowInputSort,'on')
1925    SeriesData.AllowInputSort=1;
1926end
1927
1928%% Impose the whole input file index range if requested
1929if isfield(ParamOut,'WholeIndexRange')&&isequal(ParamOut.WholeIndexRange,'on')
1930    MinIndex=get(handles.MinIndex,'Data');
1931    MaxIndex=get(handles.MaxIndex,'Data');
1932    if ~isempty(MinIndex)
1933        set(handles.num_first_i,'String',num2str(MinIndex{1}))
1934        set(handles.num_last_i,'String',num2str(MaxIndex{1}))
1935        set(handles.num_incr_i,'String','1')
1936        if size(MinIndex,2)>=2
1937            set(handles.num_first_j,'String',num2str(MinIndex{1,2}))
1938            set(handles.num_last_j,'String',num2str(MaxIndex{1,2}))
1939            set(handles.num_incr_j,'String','1')
1940        end
1941    end
1942else
1943% check index ranges
1944first_i=1;last_i=1;first_j=1;last_j=1;
1945if isfield(Series.IndexRange,'first_i')
1946    first_i=Series.IndexRange.first_i;
1947    incr_i=Series.IndexRange.incr_i;
1948    last_i=Series.IndexRange.last_i;
1949end
1950if isfield(Series.IndexRange,'first_j')
1951    first_j=Series.IndexRange.first_j;
1952     incr_j=Series.IndexRange.incr_j;
1953    last_j=Series.IndexRange.last_j;
1954end
1955if last_i < first_i || last_j < first_j , msgbox_uvmat('ERROR','last field number must be larger than the first one'),...
1956    set(handles.RUN, 'Enable','On'), set(handles.RUN,'BackgroundColor',[1 0 0]),return,end;
1957end
1958
1959%% NbSlice visibility
1960NbSliceVisible='off';%default
1961if isfield(ParamOut,'NbSlice') && isequal(ParamOut.NbSlice,'on')
1962    NbSliceVisible='on';
1963    set(handles.num_NbProcess,'String',get(handles.num_NbSlice,'String'))% the nbre of processes is imposed as the nbre of slices
1964else
1965    set(handles.num_NbProcess,'String','')% free nbre of processes
1966end
1967set(handles.num_NbSlice,'Visible',NbSliceVisible)
1968set(handles.NbSlice_title,'Visible',NbSliceVisible)
1969
1970%% Visibility of VelType and VelType_1 menus
1971VelTypeVisible='off';  %hidden by default
1972VelType_1Visible='off';
1973InputFieldsVisible='off';%visibility of the frame Fields
1974if isfield(ParamOut,'VelType')
1975    if strcmp( ParamOut.VelType,'one')||strcmp( ParamOut.VelType,'two')
1976        if nb_civ>=1
1977            VelTypeVisible='on';
1978            InputFieldsVisible='on';
1979        end
1980    end
1981    if strcmp( ParamOut.VelType,'two')
1982        if nb_civ>=2
1983            VelType_1Visible='on';
1984        end
1985    end
1986end
1987set(handles.VelType,'Visible',VelTypeVisible)
1988set(handles.VelType_text,'Visible',VelTypeVisible);
1989set(handles.VelType_1,'Visible',VelType_1Visible)
1990set(handles.VelType_text_1,'Visible',VelType_1Visible);
1991
1992%% Visibility of FieldName and FieldName_1 menus
1993FieldNameVisible='off';  %hidden by default
1994FieldName_1Visible='off';  %hidden by default
1995if isfield(ParamOut,'FieldName')
1996    if strcmp( ParamOut.FieldName,'one')||strcmp( ParamOut.FieldName,'two')
1997        if (nb_civ+nb_netcdf)>=1
1998            InputFieldsVisible='on';
1999            FieldNameVisible='on';
2000        end
2001    end
2002    if strcmp( ParamOut.FieldName,'two')
2003        if (nb_civ+nb_netcdf)>=1
2004            FieldName_1Visible='on';
2005        end
2006    end
2007end
2008set(handles.InputFields,'Visible',InputFieldsVisible)
2009set(handles.FieldName,'Visible',FieldNameVisible) % test for MenuBorser
2010set(handles.FieldName_1,'Visible',FieldName_1Visible)
2011
2012%% Visibility of FieldTransform menu
2013FieldTransformVisible='off';  %hidden by default
2014if isfield(ParamOut,'FieldTransform')
2015    FieldTransformVisible=ParamOut.FieldTransform; 
2016    TransformName_Callback([],[], handles)
2017end
2018set(handles.FieldTransform,'Visible',FieldTransformVisible)
2019if isfield(ParamOut,'TransformPath')
2020    set(handles.ActionExt,'UserData',ParamOut.TransformPath)
2021else
2022    set(handles.ActionExt,'UserData',[])
2023end
2024
2025%% Visibility of projection object
2026ProjObjectVisible='off';  %hidden by default
2027if isfield(ParamOut,'ProjObject')
2028    ProjObjectVisible=ParamOut.ProjObject;
2029end
2030set(handles.CheckObject,'Visible',ProjObjectVisible)
2031if ~get(handles.CheckObject,'Value')
2032    ProjObjectVisible='off';
2033end
2034set(handles.ProjObject,'Visible',ProjObjectVisible)
2035set(handles.DeleteObject,'Visible',ProjObjectVisible)
2036set(handles.ViewObject,'Visible',ProjObjectVisible)
2037
2038
2039%% Visibility of mask input
2040MaskVisible='off';  %hidden by default
2041if isfield(ParamOut,'Mask')
2042    MaskVisible=ParamOut.Mask;
2043end
2044set(handles.Mask,'Visible',MaskVisible)
2045set(handles.CheckMask,'Visible',MaskVisible);
2046
2047%% definition of the directory containing the output files
2048OutputDirVisible='off';
2049if isfield(ParamOut,'OutputDirExt')&&~isempty(ParamOut.OutputDirExt)
2050    set(handles.OutputDirExt,'String',ParamOut.OutputDirExt)
2051    OutputDirVisible='on';
2052end
2053set(handles.OutputDirExt,'Visible',OutputDirVisible)
2054set(handles.OutputSubDir,'Visible',OutputDirVisible)
2055set(handles.OutputDir_title,'Visible',OutputDirVisible)
2056set(handles.RunMode,'Visible',OutputDirVisible)
2057set(handles.ActionExt,'Visible',OutputDirVisible)
2058set(handles.RunMode_title,'Visible',OutputDirVisible)
2059set(handles.ActionExt_title,'Visible',OutputDirVisible)
2060
2061%% Expected nbre of output files
2062if isfield(ParamOut,'OutputFileMode')
2063StatusData.OutputFileMode=ParamOut.OutputFileMode;
2064set(handles.status,'UserData',StatusData)
2065end
2066
2067%% definition of an additional parameter set, determined by an ancillary GUI
2068if isfield(ParamOut,'ActionInput')
2069    set(handles.ActionInput,'Visible','on')
2070    set(handles.ActionInput_title,'Visible','on')
2071    set(handles.ActionInputView,'Visible','on')
2072    set(handles.ActionInputView,'Value',0)
2073    set(handles.ActionInput,'String',ActionName)
2074    ParamOut.ActionInput.Program=ActionName; % record the program in ActionInput
2075    SeriesData.ActionInput=ParamOut.ActionInput;
2076else
2077    set(handles.ActionInput,'Visible','off')
2078    set(handles.ActionInput_title,'Visible','off')
2079    set(handles.ActionInputView,'Visible','off')
2080    if isfield(SeriesData,'ActionInput')
2081    SeriesData=rmfield(SeriesData,'ActionInput');
2082    end
2083end   
2084set(handles.series,'UserData',SeriesData)
2085set(handles.ActionName,'BackgroundColor',[1 1 1])
2086
2087%------------------------------------------------------------------------
2088% --- Executes on button press in ActionInputView.
2089function ActionInputView_Callback(hObject, eventdata, handles)
2090%------------------------------------------------------------------------
2091if get(handles.ActionInputView,'Value')
2092ActionName_Callback(hObject, eventdata, handles)
2093end
2094
2095%------------------------------------------------------------------------
2096% --- Executes on selection change in FieldName.
2097function FieldName_Callback(hObject, eventdata, handles)
2098%------------------------------------------------------------------------
2099field_str=get(handles.FieldName,'String');
2100field_index=get(handles.FieldName,'Value');
2101field=field_str{field_index(1)};
2102if isequal(field,'get_field...')
2103    hget_field=findobj(allchild(0),'name','get_field');
2104    if ~isempty(hget_field)
2105        delete(hget_field)%delete opened versions of get_field
2106    end
2107    Series=read_GUI(handles.series);
2108    Series.InputTable=Series.InputTable(1,:);
2109    filecell=get_file_series(Series);
2110    if exist(filecell{1,1},'file')
2111        GetFieldData=get_field(filecell{1,1});
2112        FieldList={};
2113        XName=GetFieldData.XVarName;
2114        if GetFieldData.CheckVector
2115            UName=GetFieldData.PanelVectors.vector_x;
2116            VName=GetFieldData.PanelVectors.vector_y;
2117            XName=GetFieldData.XVarName;
2118            YName=GetFieldData.YVarName;
2119            CName=GetFieldData.PanelVectors.vec_color;
2120            [FieldList,VecColorList]=set_field_list(UName,VName,CName);
2121        elseif GetFieldData.CheckScalar
2122            AName=GetFieldData.PanelScalar.scalar;
2123            XName=GetFieldData.XVarName;
2124            YName=GetFieldData.YVarName;
2125            FieldList={AName};
2126        elseif GetFieldData.CheckPlot1D;
2127            YName=GetFieldData.CheckPlot1D.ordinate;
2128        end
2129        set(handles.Coord_x,'String',{XName})
2130        set(handles.Coord_y,'String',{YName})
2131        set(handles.FieldName,'Value',1)
2132        set(handles.FieldName,'String',[FieldList; {'get_field...'}]);
2133        %         set(handles.ColorScalar,'Value',1)
2134        %         set(handles.ColorScalar,'String',VecColorList);
2135        %         UvData.FileType{1}='netcdf';
2136        %         set(handles.uvmat,'UserData',UvData)
2137    end
2138    % elseif isequal(field,'more...')
2139    %     str=calc_field;
2140    %     [ind_answer,v] = listdlg('PromptString','Select a file:',...
2141    %                 'SelectionMode','single',...
2142    %                 'ListString',str);
2143    %        % edit the choice in the fields and actionname menu
2144    %      scalar=cell2mat(str(ind_answer));
2145    %      update_menu(handles.FieldName,scalar)
2146end
2147
2148%------------------------------------------------------------------------
2149% --- Executes on selection change in FieldName_1.
2150function FieldName_1_Callback(hObject, eventdata, handles)
2151%------------------------------------------------------------------------
2152field_str=get(handles.FieldName_1,'String');
2153field_index=get(handles.FieldName_1,'Value');
2154field=field_str{field_index};
2155if isequal(field,'get_field...')   
2156     hget_field=findobj(allchild(0),'name','get_field_1');
2157     if ~isempty(hget_field)
2158         delete(hget_field)
2159     end
2160     SeriesData=get(handles.series,'UserData');
2161     filename=SeriesData.CurrentInputFile_1;
2162     if exist(filename,'file')
2163        hget_field=get_field(filename);
2164        set(hget_field,'name','get_field_1')
2165     end
2166% elseif isequal(field,'more...')
2167%     str=calc_field;
2168%     [ind_answer,v] = listdlg('PromptString','Select a file:',...
2169%                 'SelectionMode','single',...
2170%                 'ListString',str);
2171%        % edit the choice in the fields and actionname menu
2172%      scalar=cell2mat(str(ind_answer));
2173%      update_menu(handles.FieldName_1,scalar)
2174end   
2175
2176
2177%%%%%%%%%%%%%
2178function [ind_remove]=find_pairs(dirpair,ind_i,last_i)
2179indsel=ind_i;
2180indiff=diff(ind_i); %test index increment to detect multiplets (several pairs with the same index ind_i) and holes in the series
2181indiff=[1 indiff last_i-ind_i(end)+1];%for testing gaps with the imposed bounds
2182if ~isempty(indiff)
2183    indiff2=diff(indiff);
2184    indiffp=[indiff2 1];
2185    indiffm=[1 indiff2];
2186    ind_multi_m=find((indiff==0)&(indiffm<0))-1;%indices of first members of multiplets
2187    ind_multi_p=find((indiff==0)&(indiffp>0));%indices of last members of multiplets
2188    %for each multiplet, select the most recent file
2189    ind_remove=[];
2190    for i=1:length(ind_multi_m)
2191        ind_pairs=ind_multi_m(i):ind_multi_p(i);
2192        for imulti=1:length(ind_pairs)
2193            datepair(imulti)=datenum(dirpair(ind_pairs(imulti)).date);%dates of creation
2194        end
2195        [datenew,indsort2]=sort(datepair); %sort the multiplet by creation date
2196        ind_s=indsort2(1:end-1);%
2197        ind_remove=[ind_remove ind_pairs(ind_s)];%remove these indices, leave the last one
2198    end
2199end
2200
2201%------------------------------------------------------------------------
2202% --- determine the list of index pairstring of processing file
2203function [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)
2204%------------------------------------------------------------------------
2205num_i1=num_i;% set of first image numbers by default
2206num_i2=num_i;
2207num_j1=num_j;
2208num_j2=num_j;
2209num_i_out=num_i;
2210num_j_out=num_j;
2211% if isequal (NomType,'_1-2_1') || isequal (NomType,'_1-2')
2212if isequal(mode,'series(Di)')
2213    num_i1_line=num_i+ind_shift(3);% set of first image numbers
2214    num_i2_line=num_i+ind_shift(4);
2215    % adjust the first and last field number
2216        indsel=find(num_i1_line >= 1);
2217    num_i_out=num_i(indsel);
2218    num_i1_line=num_i1_line(indsel);
2219    num_i2_line=num_i2_line(indsel);
2220    num_j1=meshgrid(num_j,ones(size(num_i1_line)));
2221    num_j2=meshgrid(num_j,ones(size(num_i1_line)));
2222    [xx,num_i1]=meshgrid(num_j,num_i1_line);
2223    [xx,num_i2]=meshgrid(num_j,num_i2_line);
2224elseif isequal (mode,'series(Dj)')||isequal (mode,'bursts')
2225    if isequal(mode,'bursts') %case of bursts (png_old or png_2D)
2226        num_j1=ind_shift(1)*ones(size(num_i));
2227        num_j2=ind_shift(2)*ones(size(num_i));
2228    else
2229        num_j1_col=num_j+ind_shift(1);% set of first image numbers
2230        num_j2_col=num_j+ind_shift(2);
2231        % adjust the first field number
2232        indsel=find((num_j1_col >= 1));   
2233        num_j_out=num_j(indsel);
2234        num_j1_col=num_j1_col(indsel);
2235        num_j2_col=num_j2_col(indsel);
2236        [num_i1,num_j1]=meshgrid(num_i,num_j1_col);
2237        [num_i2,num_j2]=meshgrid(num_i,num_j2_col);
2238    end   
2239end
2240
2241%------------------------------------------------------------------------
2242% --- Executes on button press in CheckObject.
2243function CheckObject_Callback(hObject, eventdata, handles)
2244%------------------------------------------------------------------------
2245hset_object=findobj(allchild(0),'tag','set_object');%find the set_object interface handle
2246value=get(handles.CheckObject,'Value');
2247if value
2248    SeriesData=get(handles.series,'UserData');
2249    if ~(isfield(SeriesData,'ProjObject')&&~isempty(SeriesData.ProjObject))
2250        if ishandle(hset_object)
2251            uistack(hset_object,'top')% show the GUI set_object if opened
2252        else
2253            %get the object file
2254            InputTable=get(handles.InputTable,'Data');
2255            defaultname=InputTable{1,1};
2256            if isempty(defaultname)
2257                defaultname={''};
2258            end
2259            [FileName, PathName] = uigetfile( ...
2260                {'*.xml;*.mat', ' (*.xml,*.mat)';
2261                '*.xml',  '.xml files '; ...
2262                '*.mat',  '.mat matlab files '}, ...
2263                'Pick an xml object file (or use uvmat to create it)',defaultname);
2264            fileinput=[PathName FileName];%complete file name
2265            sizf=size(fileinput);
2266            if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end
2267            %read the file
2268            data=xml2struct(fileinput);
2269            if ~isfield(data,'Type')
2270                msgbox_uvmat('ERROR',[fileinput ' is not an object xml file'])
2271                return
2272            end
2273            if ~isfield(data,'ProjMode')
2274                data.ProjMode='none';
2275            end
2276            hset_object=set_object(data);% call the set_object interface
2277        end
2278        ProjObject=read_GUI(hset_object);
2279        set(handles.ProjObject,'String',ProjObject.Name);%display the object name
2280        SeriesData=get(handles.series,'UserData');
2281        SeriesData.ProjObject=ProjObject;
2282        set(handles.series,'UserData',SeriesData);
2283    end
2284    set(handles.DeleteObject,'Visible','on');
2285    set(handles.ViewObject,'Visible','on');
2286    set(handles.ProjObject,'Visible','on');
2287else
2288    set(handles.DeleteObject,'Visible','off');
2289    set(handles.ViewObject,'Visible','off');
2290    if ~ishandle(hset_object)
2291    set(handles.ViewObject,'Value',0);
2292    end
2293    set(handles.ProjObject,'Visible','off');
2294end
2295%set(handles.series,'UserData',SeriesData)
2296
2297%--------------------------------------------------------------
2298function CheckMask_Callback(hObject, eventdata, handles)
2299value=get(handles.CheckMask,'Value');
2300if value
2301    msgbox_uvmat('ERROR','not implemented yet')
2302end
2303%--------------------------------------------------------------
2304
2305%-------------------------------------------------------------------
2306%'uv_ncbrowser': interactively calls the netcdf file browser 'get_field.m'
2307function ncbrowser_uvmat(hObject, eventdata)
2308%-------------------------------------------------------------------
2309     bla=get(gcbo,'String');
2310     ind=get(gcbo,'Value');
2311     filename=cell2mat(bla(ind));
2312      blank=find(filename==' ');
2313      filename=filename(1:blank-1);
2314     get_field(filename)
2315
2316% ------------------------------------------------------------------
2317function MenuHelp_Callback(hObject, eventdata, handles)
2318%-------------------------------------------------------------------
2319path_to_uvmat=which ('uvmat');% check the path of uvmat
2320pathelp=fileparts(path_to_uvmat);
2321helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
2322if isempty(dir(helpfile)), msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
2323else
2324    addpath (fullfile(pathelp,'uvmat_doc'))
2325    web([helpfile '#series'])
2326end
2327
2328%-------------------------------------------------------------------
2329% --- Executes on selection change in TransformName.
2330function TransformName_Callback(hObject, eventdata, handles)
2331%----------------------------------------------------------------------
2332TransformList=get(handles.TransformName,'String');
2333TransformIndex=get(handles.TransformName,'Value');
2334TransformName=TransformList{TransformIndex};
2335TransformPathList=get(handles.TransformName,'UserData');
2336nb_builtin_transform=4;
2337% ff=functions(list_transform{end});
2338if isequal(TransformName,'more...');
2339%     coord_fct='';
2340%     prompt = {'Enter the name of the transform function'};
2341%     dlg_title = 'user defined transform';
2342%     num_lines= 1;
2343    [FileName, PathName] = uigetfile( ...
2344       {'*.m', ' (*.m)';
2345        '*.m',  '.m files '; ...
2346        '*.*', 'All Files (*.*)'}, ...
2347        'Pick a transform function',get(handles.TransformPath,'String'));
2348    if isequal(FileName,0)
2349        return     %browser closed without choice
2350    end
2351    if isequal(PathName(end),'/')||isequal(PathName(end),'\')
2352        PathName(end)=[];
2353    end
2354    [TransformPath,TransformName,TransformExt]=fileparts(FileName);% removes extension .m
2355    if ~strcmp(TransformExt,'.m')
2356        msgbox_uvmat('ERROR','a Matlab function .m must be introduced');
2357        return
2358    end
2359     % insert the choice in the menu
2360    TransformIndex=find(strcmp(TransformName,TransformList),1);% look for the selected function in the menu Action
2361    if isempty(TransformIndex)%the input string does not exist in the menu
2362        TransformIndex= length(TransformList);
2363        TransformList=[TransformList(1:end-1);{TransformnName};TransformList(end)];% the selected function is appended in the menu, before the last item 'more...'
2364        set(handles.TransformName,'String',TransformList)
2365        TransformPathList=[TransformPathList;{TransformPath}];
2366    end
2367   % save the new menu in the personal file 'uvmat_perso.mat'
2368   dir_perso=prefdir;%personal Matalb directory
2369   profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
2370   if exist(profil_perso,'file')
2371       for ilist=nb_builtin_transform+1:numel(TransformPathList)
2372           TransformListUser{ilist-nb_builtin_transform}=TransformList{ilist};
2373           TransformPathListUser{ilist-nb_builtin_transform}=TransformPathList{ilist};
2374       end
2375       save (profil_perso,'TransformPathListUser','TransformListUser','-append'); %store the root name for future opening of uvmat
2376   end
2377end
2378
2379%display the current function path
2380set(handles.TransformPath,'String',TransformPathList{TransformIndex}); %show the path to the senlected function
2381set(handles.TransformName,'UserData',TransformPathList);
2382
2383
2384% --------------------------------------------------------------------
2385function MenuExportConfig_Callback(hObject, eventdata, handles)
2386global Series
2387[Series,errormsg]=prepare_jobs(handles);
2388
2389evalin('base','global Series')%make CurData global in the workspace
2390display('current series config :')
2391evalin('base','Series') %display CurData in the workspace
2392commandwindow; %brings the Matlab command window to the front
2393
2394
2395% --------------------------------------------------------------------
2396function MenuImportConfig_Callback(hObject, eventdata, handles)
2397% --------------------------------------------------------------------
2398InputTable=get(handles.InputTable,'Data');
2399[FileName, PathName] = uigetfile( ...
2400       {'*.xml', ' (*.xml)';
2401       '*.xml',  '.xml files '; ...
2402        '*.*',  'All Files (*.*)'}, ...
2403        'Pick a file',InputTable{1,1});
2404filexml=[PathName FileName];%complete file name
2405if isempty(filexml),return;end %abandon if no file is introduced by the browser
2406Param=xml2struct(filexml);
2407fill_GUI(Param,handles.series)
2408
2409% --- Executes on selection change in RunMode.
2410function RunMode_Callback(hObject, eventdata, handles)
2411
2412% --- Executes on selection change in Coord_x.
2413function Coord_x_Callback(hObject, eventdata, handles)
2414
2415
2416% --- Executes on selection change in Coord_y.
2417function Coord_y_Callback(hObject, eventdata, handles)
2418
2419
2420
2421% --- Executes when series is resized.
2422function series_ResizeFcn(hObject, eventdata, handles)
2423%% input table
2424set(handles.InputTable,'Unit','pixel')
2425Pos=get(handles.InputTable,'Position');
2426set(handles.InputTable,'Unit','normalized')
2427ColumnWidth=round([0.5 0.14 0.14 0.14 0.08]*(Pos(3)-52));
2428ColumnWidth=num2cell(ColumnWidth);
2429set(handles.InputTable,'ColumnWidth',ColumnWidth)
2430
2431%% MinIndex and MaxIndex
2432set(handles.MinIndex,'Unit','pixel')
2433Pos=get(handles.MinIndex,'Position');
2434set(handles.MinIndex,'Unit','normalized')
2435ColumnWidth=get(handles.MinIndex,'ColumnWidth');
2436if numel(ColumnWidth)==2
2437    ColumnWidth=num2cell(floor([0.5 0.5]*(Pos(3)-20)));
2438else
2439    ColumnWidth={Pos(3)-5};
2440end   
2441set(handles.MinIndex,'ColumnWidth',ColumnWidth)
2442set(handles.MaxIndex,'ColumnWidth',ColumnWidth)
2443
2444%% TimeTable
2445set(handles.TimeTable,'Unit','pixel')
2446Pos=get(handles.TimeTable,'Position');
2447set(handles.TimeTable,'Unit','normalized')
2448ColumnWidth=get(handles.TimeTable,'ColumnWidth');
2449ColumnWidth=num2cell(floor([0.25 0.25 0.25 0.25]*(Pos(3)-20)));
2450set(handles.TimeTable,'ColumnWidth',ColumnWidth)
2451
2452
2453%% PairString
2454set(handles.PairString,'Unit','pixel')
2455Pos=get(handles.PairString,'Position');
2456set(handles.PairString,'Unit','normalized')
2457set(handles.PairString,'ColumnWidth',{Pos(3)-5})
2458
2459
2460% --- Executes on button press in status.
2461function status_Callback(hObject, eventdata, handles)
2462
2463if get(handles.status,'Value')
2464    set(handles.status,'BackgroundColor',[1 1 0])
2465    drawnow
2466    %StatusData.time_ref=get(handles.RUN,'UserData');% get the time of launch
2467    Param=read_GUI(handles.series);
2468    RootPath=Param.InputTable{1,1};
2469    if ~isfield(Param,'OutputSubDir')   
2470        msgbox_uvmat('ERROR','no directory defined for output files')
2471        return
2472    end
2473    OutputSubDir=[Param.OutputSubDir Param.OutputDirExt];% subdirectory for output files
2474    OutputDir=fullfile(RootPath,OutputSubDir);
2475    uigetfile_uvmat('status_display',OutputDir)
2476   
2477%     hfig=findobj(allchild(0),'name','series_status');
2478%     if isempty(hfig)
2479%         ScreenSize=get(0,'ScreenSize');
2480%         hfig=figure('DeleteFcn',@stop_status,'Position',[ScreenSize(3)-600 ScreenSize(4)-640 560 600]);
2481%         set(hfig,'MenuBar','none')% suppress the menu bar
2482%         set(hfig,'NumberTitle','off')%suppress the fig number in the title
2483%         set(hfig,'name','series_status')
2484%         set(hfig,'tag','series_status')
2485%         uicontrol('Style','listbox','Units','normalized', 'Position',[0.05 0.09 0.9 0.71], 'Callback', @view_file,'tag','list','UserData',OutputDir);
2486%         uicontrol('Style','edit','Units','normalized', 'Position', [0.05 0.87 0.9 0.1],'tag','titlebox','Max',2,'String',OutputDir);
2487%         uicontrol('Style','frame','Units','normalized', 'Position', [0.05 0.81 0.9 0.05]);
2488%         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);
2489%         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);
2490%         %set(hrefresh,'UserData',StatusData)
2491%         BarPosition=[0.05 0.81 0.01 0.05];
2492%         uicontrol('Style','frame','Units','normalized', 'Position',BarPosition ,'BackgroundColor',[1 0 0],'tag','waitbar');
2493%         drawnow
2494%     end
2495%     refresh_GUI(hfig)
2496else
2497    %% delete current display fig if selection is off
2498    set(handles.status,'BackgroundColor',[0 1 0])
2499    hfig=findobj(allchild(0),'name','series_status');
2500    if ~isempty(hfig)
2501        delete(hfig)
2502    end
2503    return
2504end
2505
2506
2507%------------------------------------------------------------------------   
2508% launched by selecting a file on the list
2509function view_file(hObject, eventdata)
2510%------------------------------------------------------------------------
2511list=get(hObject,'String');
2512index=get(hObject,'Value');
2513rootroot=get(hObject,'UserData');
2514selectname=list{index};
2515ind_dot=regexp(selectname,'\.\.\.');
2516if ~isempty(ind_dot)
2517    selectname=selectname(1:ind_dot-1);
2518end
2519FullSelectName=fullfile(rootroot,selectname);
2520if exist(FullSelectName,'dir')% a directory has been selected
2521    ListFiles=dir(FullSelectName);
2522    ListDisplay=cell(numel(ListFiles),1);
2523    for ilist=2:numel(ListDisplay)% suppress the first line '.'
2524        ListDisplay{ilist-1}=ListFiles(ilist).name;
2525    end
2526    set(hObject,'Value',1)
2527    set(hObject,'String',ListDisplay)
2528    if strcmp(selectname,'..')
2529        FullSelectName=fileparts(fileparts(FullSelectName));
2530    end
2531    set(hObject,'UserData',FullSelectName)
2532    hfig=get(hObject,'parent');
2533    htitlebox=findobj(hfig,'tag','titlebox');   
2534    set(htitlebox,'String',FullSelectName)
2535elseif exist(FullSelectName,'file')%visualise the vel field if it exists
2536    FileType=get_file_type(FullSelectName);
2537    if strcmp(FileType,'txt')
2538        edit(FullSelectName)
2539    elseif strcmp(FileType,'xml')
2540        editxml(FullSelectName)
2541    else
2542        uvmat(FullSelectName)
2543    end
2544    set(gcbo,'Value',1)
2545end
2546
2547
2548%------------------------------------------------------------------------   
2549% launched by refreshing the status figure
2550function refresh_GUI(hfig)
2551%------------------------------------------------------------------------
2552htitlebox=findobj(hfig,'tag','titlebox');
2553hlist=findobj(hfig,'tag','list');
2554hseries=findobj(allchild(0),'tag','series');
2555hstatus=findobj(hseries,'tag','status');
2556StatusData=get(hstatus,'UserData');
2557OutputDir=get(htitlebox,'String');
2558if ischar(OutputDir),OutputDir={OutputDir};end
2559ListFiles=dir(OutputDir{1});
2560if numel(ListFiles)<1
2561    return
2562end
2563ListFiles(1)=[];%removes the first line ='.'
2564ListDisplay=cell(numel(ListFiles),1);
2565testrecent=0;
2566datnum=zeros(numel(ListDisplay),1);
2567for ilist=1:numel(ListDisplay)
2568    ListDisplay{ilist}=ListFiles(ilist).name;
2569      if ~ListFiles(ilist).isdir && isfield(ListFiles(ilist),'datenum')
2570            datnum(ilist)=ListFiles(ilist).datenum;%only available in recent matlab versions
2571            testrecent=1;
2572       end
2573end
2574set(hlist,'String',ListDisplay)
2575
2576%% Look at date of creation
2577ListDisplay=ListDisplay(datnum~=0);
2578datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
2579NbOutputFile=[];
2580if isempty(datnum)
2581    if testrecent
2582        message='no civ result created yet';
2583    else
2584        message='';
2585    end
2586else
2587    [first,indfirst]=min(datnum);
2588    [last,indlast]=max(datnum);
2589    NbOutputFile_str='?';
2590    NbOutputFile=[];
2591    if isfield(StatusData,'NbOutputFile')
2592        NbOutputFile=StatusData.NbOutputFile;
2593        NbOutputFile_str=num2str(NbOutputFile);
2594    end
2595    message={[num2str(numel(datnum)) ' file(s) done over ' NbOutputFile_str] ;['oldest modification:  ' ListDisplay{indfirst} ' : ' datestr(first)];...
2596        ['latest modification:  ' ListDisplay{indlast} ' : ' datestr(last)]};
2597end
2598set(htitlebox,'String', [OutputDir{1};message])
2599
2600%% update the waitbar
2601hwaitbar=findobj(hfig,'tag','waitbar');
2602if ~isempty(NbOutputFile)
2603    BarPosition=get(hwaitbar,'Position');
2604    BarPosition(3)=0.9*numel(datnum)/NbOutputFile;
2605    set(hwaitbar,'Position',BarPosition)
2606end
2607%TODO: adjust waitbar
2608
2609% civ_files=get(hfig,'UserData');
2610
2611% [filepath,filename,ext]=fileparts(civ_files{1});
2612% [tild,SubDir,extdir]=fileparts(filepath);
2613% SubDir=[SubDir extdir];
2614% option_civ=StatusData.option_civ;
2615% nbfiles=numel(civ_files);
2616% testrecent=0;
2617% count=0;
2618% datnum=zeros(1,nbfiles);
2619% filefound=cell(1,nbfiles);
2620% for ifile=1:nbfiles
2621%     detect=exist(civ_files{ifile},'file'); % check the existence of the file
2622%     option=0;
2623%     if detect==0
2624%         option_str='not created';
2625%     else
2626%         datfile=dir(civ_files{ifile});
2627%         if isfield(datfile,'datenum')
2628%             datnum(ifile)=datfile.datenum;%only available in recent matlab versions
2629%             testrecent=1;
2630%         end
2631%         filefound(ifile)={datfile.name};
2632%         
2633%         % check the content  netcdf file
2634%         Data=nc2struct(civ_files{ifile},'ListGlobalAttribute','CivStage','patch2','fix2','civ2','patch','fix');
2635%         option_list={'civ1','fix1','patch1','civ2','fix2','patch2'};
2636%         if ~isempty(Data.CivStage)
2637%             option=Data.CivStage;%case of Matlab civ
2638%         else
2639%             if ~isempty(Data.patch2) && isequal(Data.patch2,1)
2640%                 option=6;
2641%             elseif ~isempty(Data.fix2) && isequal(Data.fix2,1)
2642%                 option=5;
2643%             elseif ~isempty(Data.civ2) && isequal(Data.civ2,1);
2644%                 option=4;
2645%             elseif ~isempty(Data.patch) && isequal(Data.patch,1);
2646%                 option=3;
2647%             elseif ~isempty(Data.fix) && isequal(Data.fix,1);
2648%                 option=2;
2649%             else
2650%                 option=1;
2651%             end
2652%         end
2653%         option_str=option_list{option};
2654%         if datnum(ifile)<StatusData.time_ref
2655%             option_str=[option_str '  --OLD--'];
2656%         end
2657%     end
2658%     if option >= option_civ
2659%         count=count+1;
2660%     end
2661%     [filepath,filename,ext]=fileparts(civ_files{ifile});
2662%     Tabchar{ifile,1}=[fullfile(SubDir,filename) ext  '...' option_str];
2663% end
2664% datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
2665% if isempty(datnum)
2666%     if testrecent
2667%         message='no civ result created yet';
2668%     else
2669%         message='';
2670%     end
2671% else
2672%     datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
2673%     [first,ind]=min(datnum);
2674%     [last,indlast]=max(datnum);
2675%     message={[num2str(count) ' file(s) done over ' num2str(nbfiles)] ;['oldest modification:  ' cell2mat(filefound(ind)) ' : ' datestr(first)];...
2676%         ['latest modification:  ' cell2mat(filefound(indlast)) ' : ' datestr(last)]};
2677% end
2678% hlist=findobj(hfig,'tag','list');
2679% htitlebox=findobj(hfig,'tag','titlebox');
2680% hwaitbar=findobj(hfig,'tag','waitbar');
2681% set(hlist,'String',Tabchar)
2682% set(htitlebox,'String', message)
2683%
2684%------------------------------------------------------------------------   
2685% launched by deleting the status figure
2686function stop_status(hObject, eventdata)
2687%------------------------------------------------------------------------
2688hciv=findobj(allchild(0),'tag','series');
2689hhciv=guidata(hciv);
2690set(hhciv.status,'value',0) %reset the status uicontrol in the GUI civ
2691set(hhciv.status,'BackgroundColor',[0 1 0])
2692delete(gcbf)
2693
2694% --- Executes on selection change in ActionExt.
2695function ActionExt_Callback(hObject, eventdata, handles)
2696ActionExtList=get(handles.ActionExt,'String');
2697ActionExt=ActionExtList{get(handles.ActionExt,'Value')};
2698ActionList=get(handles.ActionName,'String');
2699ActionName=ActionList{get(handles.ActionName,'Value')};
2700TransformPath='';
2701if ~isempty(get(handles.ActionExt,'UserData'))
2702    TransformPath=get(handles.ActionExt,'UserData');
2703end
2704if strcmp(ActionExt,'.sh')
2705    set(handles.ActionExt,'BackgroundColor',[1 1 0])
2706    ActionFullName=fullfile(get(handles.ActionPath,'String'),[ActionName '.sh']);
2707    if ~exist(ActionFullName,'file')
2708        answer=msgbox_uvmat('INPUT_Y-N','compiled version has not been created: compile now?');
2709        if strcmp(answer,'Yes')
2710            set(handles.ActionExt,'BackgroundColor',[1 1 0])
2711            path_uvmat=fileparts(which('series'));
2712            currentdir=pwd;
2713            cd(get(handles.ActionPath,'String'))% go to the directory of Action
2714            %  addpath(get(handles.TransformPath,'String'))
2715            addpath(path_uvmat)% add the path to uvmat to run the fct 'compile'
2716           % addpath(fullfile(path_uvmat,'transform_field'))% add the path to uvmat to run the fct 'compile'
2717            compile(ActionName,TransformPath)
2718            cd(currentdir)
2719        end
2720       
2721    else
2722        sh_file_info=dir(fullfile(get(handles.ActionPath,'String'),[ActionName '.sh']));
2723        m_file_info=dir(fullfile(get(handles.ActionPath,'String'),[ActionName '.m']));
2724        if isfield(m_file_info,'datenum') && m_file_info.datenum>sh_file_info.datenum
2725            set(handles.ActionExt,'BackgroundColor',[1 1 0])
2726            drawnow
2727            answer=msgbox_uvmat('INPUT_Y-N',[ActionName '.sh needs to be updated: recompile now?']);
2728            if strcmp(answer,'Yes')
2729                path_uvmat=fileparts(which('series'));
2730                currentdir=pwd;
2731                cd(get(handles.ActionPath,'String'))% go to the directory of Action
2732                %  addpath(get(handles.TransformPath,'String'))
2733                addpath(path_uvmat)% add the path to uvmat to run the fct 'compile'
2734                addpath(fullfile(path_uvmat,'transform_field'))% add the path to uvmat to run the fct 'compile'
2735                compile(ActionName,TransformPath)
2736                cd(currentdir)
2737            end
2738        end
2739    end
2740    set(handles.ActionExt,'BackgroundColor',[1 1 1])
2741end
2742
2743
2744function ActionInput_Callback(hObject, eventdata, handles)
2745
2746
2747% --- Executes on button press in DeleteObject.
2748function DeleteObject_Callback(hObject, eventdata, handles)
2749if get(handles.DeleteObject,'Value')
2750        SeriesData=get(handles.series,'UserData');
2751    SeriesData.ProjObject=[];
2752    set(handles.series,'UserData',SeriesData)
2753    set(handles.ProjObject,'String','')
2754    set(handles.CheckObject,'Value',0)
2755    set(handles.DeleteObject,'Visible','off')
2756    set(handles.ViewObject,'Visible','off')
2757    set(handles.DeleteObject,'Value',0)
2758end
2759
2760% --- Executes on button press in ViewObject.
2761function ViewObject_Callback(hObject, eventdata, handles)
2762if get(handles.ViewObject,'Value')
2763        UserData=get(handles.series,'UserData');
2764    set_object(UserData.ProjObject)
2765else
2766    hset_object=findobj(allchild(0),'Tag','set_object');
2767    if ~isempty(hset_object)
2768        delete(hset_object)
2769    end
2770end
2771
2772
2773function num_NbProcess_Callback(hObject, eventdata, handles)
2774
2775
2776function num_NbSlice_Callback(hObject, eventdata, handles)
2777NbSlice=str2num(get(handles.num_NbSlice,'String'));
2778set(handles.num_NbProcess,'String',num2str(NbSlice))
Note: See TracBrowser for help on using the repository browser.