source: trunk/src/series.m @ 644

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

various improvements: resize GUI uvmat, projection on lines

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