source: trunk/src/series.m @ 648

Last change on this file since 648 was 648, checked in by sommeria, 7 years ago

get_field updated, several bugs corrected,open_uvmat suppressd

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