source: trunk/src/series.m @ 630

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

generalisation of update_imadoc, improverment of the GUI get_field

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