source: trunk/src/series.m @ 643

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

small bug corrections

File size: 116.8 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
1075for iview=1:numel(SeriesData.i1_series)
1076    pair_max{iview}=squeeze(max(SeriesData.i1_series{iview},[],1)); %max on pair index
1077    if (strcmp(get(handles.num_first_j,'Visible'),'off')&& size(pair_max{iview},2)~=1)
1078        pair_max{iview}=squeeze(max(pair_max{iview},[],1)); % consider only the i index
1079    end
1080    pair_max{iview}=reshape(pair_max{iview},1,[]);
1081    index_min(iview)=find(pair_max{iview}>0, 1 );
1082    index_max(iview)=find(pair_max{iview}>0, 1, 'last' );
1083end
1084[index_min,iview_min]=min(index_min);
1085[index_max,iview_max]=min(index_max);
1086if size(SeriesData.i1_series{iview_min},2)==1% movie
1087    index_first=ref_i(1);
1088    index_last=ref_i(2);
1089else
1090    index_first=(ref_i(1)-1)*(size(SeriesData.i1_series{iview_min},1))+ref_j(1)+1;
1091    index_last=(ref_i(2)-1)*(size(SeriesData.i1_series{iview_max},1))+ref_j(2)+1;
1092end
1093range=index_max-index_min+1;
1094coeff_min=(index_first-index_min)/range;
1095coeff_max=(index_last-index_min+1)/range;
1096Position=get(handles.Waitbar,'Position');% position of the waitbar:= [ x,y, width, height]
1097Position_status=get(handles.FileStatus,'Position');
1098Position(1)=coeff_min*Position_status(3)+Position_status(1);
1099Position(3)=Position_status(3)*(coeff_max-coeff_min);
1100set(handles.Waitbar,'Position',Position)
1101update_waitbar(handles.Waitbar,0)
1102
1103%------------------------------------------------------------------------
1104% --- Executes when selected cell(s) is changed in PairString.
1105function PairString_CellSelectionCallback(hObject, eventdata, handles)
1106%------------------------------------------------------------------------   
1107set(handles.ListView,'Value',eventdata.Indices(1))% detect the selected raw index
1108ListView_Callback ([],[],handles) % update the list of available pairs
1109
1110%------------------------------------------------------------------------
1111%------------------------------------------------------------------------
1112%  III - FUNCTIONS ASSOCIATED TO THE FRAME SET PAIRS
1113%------------------------------------------------------------------------
1114%------------------------------------------------------------------------
1115% --- Executes on selection change in ListView.
1116function ListView_Callback(hObject, eventdata, handles)
1117%------------------------------------------------------------------------   
1118SeriesData=get(handles.series,'UserData');
1119i2_series=[];
1120j2_series=[];
1121iview=get(handles.ListView,'Value');
1122if ~isempty(SeriesData.i2_series{iview})
1123    i2_series=SeriesData.i2_series{iview};
1124end
1125if ~isempty(SeriesData.j2_series{iview})
1126    j2_series=SeriesData.j2_series{iview};
1127end
1128update_mode(handles,SeriesData.i1_series{iview},SeriesData.i2_series{iview},...
1129    SeriesData.j1_series{iview},SeriesData.j2_series{iview},SeriesData.Time{iview})
1130
1131%------------------------------------------------------------------------
1132% --- Executes on button press in mode.
1133function mode_Callback(hObject, eventdata, handles)
1134%------------------------------------------------------------------------       
1135SeriesData=get(handles.series,'UserData');
1136iview=get(handles.ListView,'Value');
1137mode_list=get(handles.mode,'String');
1138mode=mode_list{get(handles.mode,'Value')};
1139if isequal(mode,'bursts')
1140    enable_i(handles,'On')
1141    enable_j(handles,'Off') %do not display j index scanning in burst mode (j is fixed by the burst choice)
1142else
1143    enable_i(handles,'On')
1144    enable_j(handles,'Off')
1145end
1146fill_ListPair(handles,SeriesData.i1_series{iview},SeriesData.i2_series{iview},...
1147    SeriesData.j1_series{iview},SeriesData.j2_series{iview},SeriesData.Time{iview})
1148ListPairs_Callback([],[],handles)
1149
1150%-------------------------------------------------------------
1151% --- Executes on selection in ListPairs.
1152function ListPairs_Callback(hObject,eventdata,handles)
1153%------------------------------------------------------------
1154list_pair=get(handles.ListPairs,'String');%get the menu of image pairs
1155if isempty(list_pair)
1156    string='';
1157else
1158    string=list_pair{get(handles.ListPairs,'Value')};
1159    string=regexprep(string,',.*','');%removes time indication (after ',')
1160end
1161PairString=get(handles.PairString,'Data');
1162iview=get(handles.ListView,'Value');
1163PairString{iview,1}=string;
1164% report the selected pair string to the table PairString
1165set(handles.PairString,'Data',PairString)
1166
1167%------------------------------------------------------------------------
1168function num_ref_i_Callback(hObject, eventdata, handles)
1169%------------------------------------------------------------------------
1170mode_list=get(handles.mode,'String');
1171mode=mode_list{get(handles.mode,'Value')};
1172SeriesData=get(handles.series,'UserData');
1173iview=get(handles.ListView,'Value');
1174fill_ListPair(handles,SeriesData.i1_series{iview},SeriesData.i2_series{iview},...
1175    SeriesData.j1_series{iview},SeriesData.j2_series{iview},SeriesData.Time{iview});% update the menu of pairs depending on the available netcdf files
1176ListPairs_Callback([],[],handles)
1177
1178%------------------------------------------------------------------------
1179function num_ref_j_Callback(hObject, eventdata, handles)
1180%------------------------------------------------------------------------
1181num_ref_i_Callback(hObject, eventdata, handles)
1182
1183%------------------------------------------------------------------------
1184function update_mode(handles,i1_series,i2_series,j1_series,j2_series,time)
1185%------------------------------------------------------------------------   
1186% check_burst=0;
1187if isempty(j2_series)% no j pair
1188    if isempty(i2_series)
1189        set(handles.mode,'Value',1)
1190        set(handles.mode,'String',{''})% no pair menu to display
1191    else   
1192        set(handles.mode,'Value',1)
1193        set(handles.mode,'String',{'series(Di)'}) % pair menu with only option Di
1194    end
1195else %existence of j pairs
1196    pair_max=squeeze(max(i1_series,[],1)); %max on pair index
1197    j_max=max(pair_max,[],1);
1198    MaxIndex_i=max(find(j_max))-1;% max ref index i
1199    MinIndex_i=min(find(j_max))-1;% min ref index i
1200    i_max=max(pair_max,[],2);
1201    MaxIndex_j=max(find(i_max))-1;% max ref index i
1202    MinIndex_j=min(find(i_max))-1;% min ref index i
1203    if MaxIndex_j==MinIndex_j
1204        set(handles.mode,'Value',1);
1205        set(handles.mode,'String',{'bursts'})
1206%         check_burst=1;
1207    elseif MaxIndex_i==MinIndex_i
1208        set(handles.mode,'Value',1);
1209        set(handles.mode,'String',{'series(Dj)'})
1210    else
1211        set(handles.mode,'String',{'bursts';'series(Dj)'})
1212        if (MaxIndex_j-MinIndex_j)>10
1213            set(handles.mode,'Value',2);%set mode to series(Dj) if more than 10 j values
1214        else
1215            set(handles.mode,'Value',1);
1216%             check_burst=1;
1217        end
1218    end
1219end
1220fill_ListPair(handles,i1_series,i2_series,j1_series,j2_series,time)
1221ListPairs_Callback([],[],handles)
1222
1223%--------------------------------------------------------------
1224% determine the menu for pairstring depending on existing netcdf files
1225% with the reference indices num_ref_i and num_ref_j
1226%----------------------------------------------------------------
1227function fill_ListPair(handles,i1_series,i2_series,j1_series,j2_series,time)
1228
1229mode_list=get(handles.mode,'String');
1230mode=mode_list{get(handles.mode,'Value')};
1231ref_i=str2num(get(handles.num_ref_i,'String'));
1232if isempty(ref_i)
1233    ref_i=1;
1234end
1235if strcmp(get(handles.num_ref_j,'Visible'),'on')
1236    ref_j=str2num(get(handles.num_ref_j,'String'));
1237    if isempty(ref_j)
1238        ref_j=1;
1239    end
1240else
1241    ref_j=1;
1242end
1243TimeUnit=get(handles.TimeUnit,'String');
1244if length(TimeUnit)>=1
1245    dtunit=['m' TimeUnit];
1246else
1247    dtunit='e-03';
1248end
1249
1250displ_pair={};
1251if strcmp(mode,'series(Di)')
1252    if isempty(i2_series)
1253        msgbox_uvmat('ERROR','no i1-i2 pair available')
1254        return
1255    end
1256    diff_i=i2_series-i1_series;
1257    min_diff=min(diff_i(diff_i>0));
1258    max_diff=max(diff_i(diff_i>0));
1259    for ipair=min_diff:max_diff
1260        if numel(diff_i(diff_i==ipair))>0
1261            pair_string=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
1262            if ~isempty(time)
1263                if ref_i<=floor(ipair/2)
1264                    ref_i=floor(ipair/2)+1;% shift ref_i to get the first pair
1265                end
1266                Dt=time(ref_i+ceil(ipair/2),ref_j)-time(ref_i-floor(ipair/2),ref_j);
1267                pair_string=[pair_string ', Dt=' num2str(Dt) ' ' dtunit];
1268            end
1269            displ_pair=[displ_pair;{pair_string}];
1270        end
1271    end
1272    if ~isempty(displ_pair)
1273        displ_pair=[displ_pair;{'Di=*|*'}];
1274    end
1275elseif strcmp(mode,'series(Dj)')
1276    if isempty(j2_series)
1277        msgbox_uvmat('ERROR','no j1-j2 pair available')
1278        return
1279    end
1280    diff_j=j2_series-j1_series;
1281    min_diff=min(diff_j(diff_j>0));
1282    max_diff=max(diff_j(diff_j>0));
1283    for ipair=min_diff:max_diff
1284        if numel(diff_j(diff_j==ipair))>0
1285            pair_string=['Dj= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
1286            if ~isempty(time)
1287                if ref_j<=floor(ipair/2)
1288                    ref_j=floor(ipair/2)+1;% shift ref_i to get the first pair
1289                end
1290                Dt=time(ref_i,ref_j+ceil(ipair/2))-time(ref_i,ref_j-floor(ipair/2));
1291                pair_string=[pair_string ', Dt=' num2str(Dt) ' ' dtunit];
1292            end
1293            displ_pair=[displ_pair;{pair_string}];
1294        end
1295    end
1296    if ~isempty(displ_pair)
1297        displ_pair=[displ_pair;{'Dj=*|*'}];
1298    end
1299elseif strcmp(mode,'bursts')
1300    if isempty(j2_series)
1301        msgbox_uvmat('ERROR','no j1-j2 pair available')
1302        return
1303    end
1304    diff_j=j2_series-j1_series;
1305    min_j1=min(j1_series(j1_series>0));
1306    max_j1=max(j1_series(j1_series>0));
1307    min_j2=min(j2_series(j2_series>0));
1308    max_j2=max(j2_series(j2_series>0));
1309    for pair1=min_j1:min(max_j1,min_j1+20)
1310        for pair2=min_j2:min(max_j2,min_j2+20)
1311        if numel(j1_series(j1_series==pair1))>0 && numel(j2_series(j2_series==pair2))>0
1312            displ_pair=[displ_pair;{['j= ' num2str(pair1) '-' num2str(pair2)]}];
1313        end
1314        end
1315    end
1316    if ~isempty(displ_pair)
1317        displ_pair=[displ_pair;{'j=*-*'}];
1318    end
1319end
1320set(handles.num_ref_i,'String',num2str(ref_i)) % update ref_i and ref_j
1321set(handles.num_ref_j,'String',num2str(ref_j))
1322
1323%% display list of pairstring
1324displ_pair_list=get(handles.ListPairs,'String');
1325NewVal=[];
1326if ~isempty(displ_pair_list)
1327Val=get(handles.ListPairs,'Value');
1328NewVal=find(strcmp(displ_pair_list{Val},displ_pair),1);% look at the previous display in the new menu displ_pï¿œir
1329end
1330if ~isempty(NewVal)
1331    set(handles.ListPairs,'Value',NewVal)
1332else
1333    set(handles.ListPairs,'Value',1)
1334end
1335set(handles.ListPairs,'String',displ_pair)
1336
1337%-------------------------------------
1338function enable_i(handles,state)
1339set(handles.i_txt,'Visible',state)
1340set(handles.num_first_i,'Visible',state)
1341set(handles.num_last_i,'Visible',state)
1342set(handles.num_incr_i,'Visible',state)
1343set(handles.num_ref_i,'Visible',state)
1344set(handles.ref_i_text,'Visible',state)
1345
1346%-----------------------------------
1347function enable_j(handles,state)
1348set(handles.j_txt,'Visible',state)
1349set(handles.num_first_j,'Visible',state)
1350set(handles.num_last_j,'Visible',state)
1351set(handles.num_incr_j,'Visible',state)
1352set(handles.num_ref_j,'Visible',state)
1353set(handles.ref_j_text,'Visible',state)
1354set(handles.MinIndex_j,'Visible',state)
1355set(handles.MaxIndex_j,'Visible',state)
1356
1357
1358%%%%%%%%%%%%%%%%%%%%
1359%%  MAIN ActionName FUNCTIONS
1360%%%%%%%%%%%%%%%%%%%%
1361%------------------------------------------------------------------------
1362% --- Executes on button press in RUN.
1363%------------------------------------------------------------------------
1364function RUN_Callback(hObject, eventdata, handles)
1365
1366%% settings of the button RUN
1367set(handles.RUN,'BusyAction','queue');% activation of STOP button will set BusyAction to 'cancel'
1368%set(0,'CurrentFigure',handles.series); % display the GUI series
1369set(handles.RUN, 'Enable','Off')% avoid further RUN action until the current one is finished
1370set(handles.RUN,'BackgroundColor',[1 1 0])%show activation of RUN by yellow color
1371drawnow
1372
1373%% read the data on the GUI series
1374Param=read_GUI_series(handles);%displayed parameters
1375SeriesData=get(handles.series,'UserData');%hidden parameters
1376
1377%% create the output data directory if needed
1378if isfield(Param,'OutputSubDir')
1379    SubDirOut=[get(handles.OutputSubDir,'String') Param.OutputDirExt];
1380    SubDirOutNew=SubDirOut;
1381    detect=exist(fullfile(Param.InputTable{1,1},SubDirOutNew),'dir');% test if  the dir  already exist
1382    check_create=1; %need to create the result directory by default
1383    while detect
1384        answer=msgbox_uvmat('INPUT_Y-N',['use existing ouput directory: ' fullfile(Param.InputTable{1,1},SubDirOutNew) ', possibly delete previous data']);
1385        if strcmp(answer,'Cancel')
1386            errormsg='Cancel';
1387            return
1388        elseif strcmp(answer,'Yes')
1389            detect=0;
1390            check_create=0;
1391        else
1392            r=regexp(SubDirOutNew,'(?<root>.*\D)(?<num1>\d+)$','names');%detect whether name ends by a number
1393            if isempty(r)
1394                r(1).root=[SubDirOutNew '_'];
1395                r(1).num1='0';
1396            end
1397            SubDirOutNew=[r(1).root num2str(str2num(r(1).num1)+1)];%increment the index by 1 or put 1
1398            detect=exist(fullfile(Param.InputTable{1,1},SubDirOutNew),'dir');% test if  the dir  already exists
1399            check_create=1;
1400        end
1401    end
1402    Param.OutputDirExt=regexprep(SubDirOutNew,Param.OutputSubDir,'');
1403    Param.OutputRootFile=Param.InputTable{1,3};% the first sorted RootFile taken for output
1404    set(handles.OutputDirExt,'String',Param.OutputDirExt)
1405    OutputDir=fullfile(Param.InputTable{1,1},[Param.OutputSubDir Param.OutputDirExt]);% full name (with path) of output directory
1406    if check_create    % create output directory if it does not exist
1407        [tild,msg1]=mkdir(OutputDir);
1408        if ~strcmp(msg1,'')
1409            errormsg=['cannot create ' OutputDir ': ' msg1];%error message for directory creation
1410            return
1411        end
1412    end
1413    OutputNomType=nomtype2pair(Param.InputTable{1,4});% nomenclature for output files
1414    DirXml=fullfile(OutputDir,'0_XML');
1415    if ~exist(DirXml,'dir')
1416        [tild,msg1]=mkdir(DirXml);
1417        if ~strcmp(msg1,'')
1418            msgbox_uvmat('ERROR',['cannot create ' DirXml ': ' msg1]);%error message for directory creation
1419            return
1420        end
1421    end
1422end
1423
1424%% select the Action mode, 'local', 'background' or 'cluster' (if available)
1425RunMode='local';%default (needed for first opening of the GUI series)
1426if isfield(Param.Action,'RunMode')
1427    RunMode=Param.Action.RunMode;
1428end
1429ActionExt='.m';%default
1430if isfield(Param.Action,'ActionExt')
1431    ActionExt=Param.Action.ActionExt;% '.m' or '.sh' (compiled)
1432end
1433ActionName=Param.Action.ActionName;
1434ActionPath=Param.Action.ActionPath;
1435path_series=fileparts(which('series'));
1436
1437%% create the Action fct handle if RunMode option = 'local'
1438if strcmp(RunMode,'local')
1439    if ~isequal(ActionPath,path_series)
1440        eval(['spath=which(''' ActionName ''');']) %spath = current path of the selected function ACTION
1441        if ~exist(ActionPath,'dir')
1442            msgbox_uvmat('ERROR',['The prescribed function path ' ActionPath ' does not exist']);
1443            return
1444        end
1445        if ~isequal(spath,ActionPath)
1446            addpath(ActionPath)% add the prescribed path if not the current one
1447        end
1448    end
1449    eval(['h_fun=@' ActionName ';'])%create a function handle for ACTION
1450    if ~isequal(ActionPath,path_series)
1451        rmpath(ActionPath)% add the prescribed path if not the current one
1452    end
1453end
1454
1455%% Get RunTime code from the file PARAM.xml (needed to run compiled functions)
1456errormsg='';%default error message
1457xmlfile=fullfile(path_series,'PARAM.xml');
1458test_batch=0;%default: ,no batch mode available
1459if ~exist(xmlfile,'file')
1460    [success,message]=copyfile(fullfile(path_series,'PARAM.xml.default'),xmlfile);
1461end
1462RunTime='';
1463if strcmp(ActionExt,'.sh')
1464    if exist(xmlfile,'file')
1465        s=xml2struct(xmlfile);
1466        if strcmp(RunMode,'cluster_oar') && isfield(s,'BatchParam')
1467            if isfield(s.BatchParam,'RunTime')
1468                RunTime=s.BatchParam.RunTime;
1469            end
1470            if isfield(s.BatchParam,'NbCore')
1471                NbCore=s.BatchParam.NbCore;
1472            end
1473        elseif (strcmp(RunMode,'background')||strcmp(RunMode,'local')) && isfield(s,'RunParam')
1474            if isfield(s.RunParam,'RunTime')
1475                RunTime=s.RunParam.RunTime;
1476            end
1477            if isfield(s.RunParam,'NbCore')
1478                NbCore=s.RunParam.NbCore;
1479            end
1480        end
1481    end
1482    if isempty(RunTime) && strcmp(RunMode,'cluster_oar')
1483        msgbox_uvmat('ERROR','RunTime name not found in PARAM.xml, compiled version .sh cannot run on cluster')
1484        return
1485    end
1486end
1487
1488%% set nbre of cluster cores and processes
1489switch RunMode
1490    case {'local','background'}
1491        NbCore=1;% no need to split the calculation
1492    case 'cluster_oar'
1493        if strcmp(Param.Action.ActionExt,'.m')% case of Matlab function (uncompiled)
1494            NbCore=1;% one core used only (limitation of Matlab licences)
1495            msgbox_uvmat('WARNING','Number of cores =1: select the compiled version civ_matlab.sh for multi-core processing');
1496            extra_oar='';
1497        else
1498            answer=inputdlg({'Number of cores (max 36)','extra oar options'},'oarsub parameter',1,{'12',''});
1499            NbCore=str2double(answer{1});
1500            extra_oar=answer{2};
1501        end
1502end
1503if ~isfield(Param.IndexRange,'NbSlice')
1504    Param.IndexRange.NbSlice=[];
1505end
1506if isempty(Param.IndexRange.NbSlice)
1507    NbProcess=NbCore;% choose one process per core
1508else
1509    NbProcess=Param.IndexRange.NbSlice;% the nbre of run processes is equal to the number of slices
1510    NbCore=min(NbCore,NbProcess);% at least one process per core
1511end
1512       
1513%% get the set of reference field indices
1514first_i=1;
1515last_i=1;
1516incr_i=1;
1517first_j=1;
1518last_j=1;
1519incr_j=1;
1520if isfield(Param.IndexRange,'first_i')
1521    first_i=Param.IndexRange.first_i;
1522    incr_i=Param.IndexRange.incr_i;
1523    last_i=Param.IndexRange.last_i;
1524end
1525if isfield(Param.IndexRange,'first_j')
1526    first_j=Param.IndexRange.first_j;
1527    last_j=Param.IndexRange.last_j;
1528    incr_j=Param.IndexRange.incr_j;
1529end
1530if last_i < first_i || last_j < first_j
1531    msgbox_uvmat('ERROR', 'series/Run_Callback:last field index must be larger or equal to the first one')
1532    set(handles.RUN, 'Enable','On'),
1533    set(handles.RUN,'BackgroundColor',[1 0 0])
1534    return
1535end
1536%incr_i must be defined, =1 by default, if NbSlice is active
1537if isempty(incr_i)&& ~isempty(Param.IndexRange.NbSlice)
1538    incr_i=1;
1539    set(handles.num_incr_i,'String','1')
1540end
1541if isempty(incr_i)
1542    if isempty(incr_j)
1543        [ref_j,ref_i]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1544        ref_j=ref_j(ref_j>=first_j & ref_j<=last_j);
1545        ref_i=ref_i(ref_i>=first_i & ref_i<=last_i);
1546        ref_j=ref_j-1;
1547        ref_i=ref_i-1;
1548    else
1549        ref_j=first_j:incr_j:last_j;
1550        [tild,ref_i]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1551        ref_i=ref_i-1;
1552        ref_i=ref_i(ref_i>=first_i & ref_i<=last_i);
1553    end
1554else
1555    ref_i=first_i:incr_i:last_i;
1556    if isempty(incr_j)
1557    [ref_j,tild]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1558    ref_j=ref_j-1;
1559    ref_j=ref_j(ref_j>=first_j & ref_j<=last_j);
1560    else
1561        ref_j=first_j:incr_j:last_j;
1562    end
1563end
1564BlockLength=ceil(numel(ref_i)/NbProcess);
1565nbfield_j=numel(ref_j);
1566
1567%% record nbre of output files and starting time for computation for status
1568StatusData=get(handles.status,'UserData');
1569if isfield(StatusData,'OutputFileMode')
1570    switch StatusData.OutputFileMode
1571        case 'NbInput'
1572            StatusData.NbOutputFile=numel(ref_i)*nbfield_j;
1573        case 'NbInput_i'
1574            StatusData.NbOutputFile=numel(ref_i);
1575        case 'NbSlice'   
1576            StatusData.NbOutputFile=str2num(get(handles.num_NbSlice,'String'));
1577    end
1578end
1579StatusData.TimeStart=now;
1580set(handles.status,'UserData',StatusData)
1581
1582%% direct processing on the current Matlab session
1583if strcmp (RunMode,'local')
1584    for iprocess=1:NbProcess
1585        if isempty(Param.IndexRange.NbSlice)
1586            %Param.IndexRange.first_i=first_i+(iprocess-1)*BlockLength*incr_i;
1587            Param.IndexRange.first_i=ref_i(1+(iprocess-1)*BlockLength);
1588            if Param.IndexRange.first_i>last_i
1589                break
1590            end
1591            Param.IndexRange.last_i=min(ref_i(iprocess*BlockLength),last_i);
1592            %Param.IndexRange.last_i=min(first_i+(iprocess)*BlockLength*incr_i-1,last_i);
1593        else %multislices (then incr_i is not empty)
1594             Param.IndexRange.first_i= first_i+incr_i*(iprocess-1);
1595             Param.IndexRange.incr_i=incr_i*Param.IndexRange.NbSlice;
1596        end
1597        if isfield(Param,'OutputSubDir')
1598        t=struct2xml(Param);
1599        t=set(t,1,'name','Series');
1600        filexml=fullfile_uvmat(DirXml,'',Param.InputTable{1,3},'.xml',OutputNomType,...
1601            Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1602        save(t,filexml);
1603        end
1604        switch ActionExt
1605            case '.m'
1606                h_fun(Param);
1607            case '.sh'
1608                switch computer
1609                    case {'PCWIN','PCWIN64'} %Windows system
1610                        filexml=regexprep(filexml,'\\','\\\\');% add '\' so that '\' are left as characters
1611                        system([fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml]);% TODO: adapt to DOS system
1612                    case {'GLNX86','GLNXA64','MACI64'}%Linux  system
1613                        system([fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml]);
1614                end
1615        end
1616    end
1617elseif strcmp(get(handles.OutputDirExt,'Visible'),'off')
1618    msgbox_uvmat('ERROR',['no output file for Action ' ActionName ', use run mode = local']);% a output dir is needed for background option
1619    return
1620else
1621    %% processing on a different session of the same computer (background) or cluster, create executable files
1622    batch_file_list=cell(NbProcess,1);% initiate the list of executable files
1623    DirBat=fullfile(OutputDir,'0_EXE');
1624    switch computer
1625        case {'PCWIN','PCWIN64'} %Windows system
1626            ExeExt='.bat';
1627        case {'GLNX86','GLNXA64','MACI64'}%Linux  system
1628           ExeExt='.sh';
1629    end
1630    %create subdirectory for executable files
1631    if ~exist(DirBat,'dir')
1632        [tild,msg1]=mkdir(DirBat);
1633        if ~strcmp(msg1,'')
1634            msgbox_uvmat('ERROR',['cannot create ' DirBat ': ' msg1]);%error message for directory creation
1635            return
1636        end
1637    end
1638    %create subdirectory for log files
1639    DirLog=fullfile(OutputDir,'0_LOG');
1640    if ~exist(DirLog,'dir')
1641        [tild,msg1]=mkdir(DirLog);
1642        if ~strcmp(msg1,'')
1643            msgbox_uvmat('ERROR',['cannot create ' DirLog ': ' msg1]);%error message for directory creation
1644            return
1645        end
1646    end
1647    for iprocess=1:NbProcess
1648        if isempty(Param.IndexRange.NbSlice)% process by blocks of i index
1649            Param.IndexRange.first_i=first_i+(iprocess-1)*BlockLength*incr_i;
1650            if Param.IndexRange.first_i>last_i
1651                NbProcess=iprocess-1;
1652                break% leave the loop, we are at the end of the calculation
1653            end
1654            Param.IndexRange.last_i=min(last_i,first_i+(iprocess)*BlockLength*incr_i-1);
1655        else% process by slices of i index if NbSlice is defined, computation in a single process if NbSlice =1
1656            Param.IndexRange.first_i= first_i+iprocess-1;
1657            Param.IndexRange.incr_i=incr_i*Param.IndexRange.NbSlice;
1658        end
1659       
1660        % create, fill and save the xml parameter file
1661        t=struct2xml(Param);
1662        t=set(t,1,'name','Series');
1663        filexml=fullfile_uvmat(DirXml,'',Param.InputTable{1,3},'.xml',OutputNomType,...
1664            Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1665        save(t,filexml);% save the parameter file
1666       
1667        %create the executable file
1668         filebat=fullfile_uvmat(DirBat,'',Param.InputTable{1,3},ExeExt,OutputNomType,...
1669           Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1670        batch_file_list{iprocess}=filebat;
1671        [fid,message]=fopen(filebat,'w');% create the executable file
1672        if isequal(fid,-1)
1673            msgbox_uvmat('ERROR', ['creation of .bat file: ' message]);
1674            return
1675        end
1676       
1677        % set the log file name
1678        filelog=fullfile_uvmat(DirLog,'',Param.InputTable{1,3},'.log',OutputNomType,...
1679            Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1680       
1681        % fill and save the executable file
1682        switch ActionExt
1683            case '.m'% Matlab function
1684                switch computer
1685                    case {'GLNX86','GLNXA64','MACI64'}
1686                        cmd=[...
1687                            '#!/bin/bash \n'...
1688                            '. /etc/sysprofile \n'...
1689                            'matlab -nodisplay -nosplash -nojvm -logfile ''' filelog ''' <<END_MATLAB \n'...
1690                            'addpath(''' path_series '''); \n'...
1691                            'addpath(''' Param.Action.ActionPath '''); \n'...
1692                            '' Param.Action.ActionName  '( ''' filexml '''); \n'...
1693                            'exit \n'...
1694                            'END_MATLAB \n'];
1695                        fprintf(fid,cmd);%fill the executable file with the  char string cmd
1696                        fclose(fid);% close the executable file
1697                        system(['chmod +x ' filebat]);% set the file to executable
1698                    case {'PCWIN','PCWIN64'}
1699                        text_matlabscript=['matlab -automation -logfile ' regexprep(filelog,'\\','\\\\')...
1700                            ' -r "addpath(''' regexprep(path_series,'\\','\\\\') ''');'...
1701                            'addpath(''' regexprep(Param.Action.ActionPath,'\\','\\\\') ''');'...
1702                            '' Param.Action.ActionName  '( ''' regexprep(filexml,'\\','\\\\') ''');exit"'];
1703                        fprintf(fid,text_matlabscript);%fill the executable file with the  char string cmd
1704                        fclose(fid);% close the executable file
1705                end
1706            case '.sh' % compiled Matlab function
1707                switch computer
1708                    case {'GLNX86','GLNXA64','MACI64'}
1709                        cmd=['#!/bin/bash \n '...
1710                            '#$ -cwd \n '...
1711                            'hostname && date \n '...
1712                            'umask 002 \n'...
1713                            fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml];%allow writting access to created files for user group
1714                        fprintf(fid,cmd);%fill the executable file with the  char string cmd
1715                        fclose(fid);% close the executable file
1716                        system(['chmod +x ' filebat]);% set the file to executable
1717                       
1718                    case {'PCWIN','PCWIN64'}    %       TODO: adapt to Windows system
1719                        %                                 cmd=['matlab -automation -logfile ' regexprep(filelog,'\\','\\\\')...
1720                        %                                     ' -r "addpath(''' regexprep(path_series,'\\','\\\\') ''');'...
1721                        %                                     'addpath(''' regexprep(Param.Action.ActionPath,'\\','\\\\') ''');'...
1722                        %                                     '' Param.Action.ActionName  '( ''' regexprep(filexml,'\\','\\\\') ''');exit"'];
1723                        fprintf(fid,cmd);
1724                        fclose(fid);
1725                        %                               dos([filebat ' &']);
1726                end
1727        end
1728    end
1729end
1730
1731%% launch the executable files for background or cluster processing
1732switch RunMode
1733    case 'background'
1734        for iprocess=1:NbProcess
1735            system([batch_file_list{iprocess} ' &'])% directly execute the command file for each process
1736        end
1737    case 'cluster_oar' % option 'oar-parexec' used
1738        %create subdirectory for oar command and log files
1739        DirOAR=fullfile(OutputDir,'0_OAR');
1740        if ~exist(DirOAR,'dir')
1741            [tild,msg1]=mkdir(DirOAR);
1742            if ~strcmp(msg1,'')
1743                msgbox_uvmat('ERROR',['cannot create ' DirOAR ': ' msg1]);%error message for directory creation
1744                return
1745            end
1746        end
1747        max_walltime=3600*12; % 12h max total calculation
1748        walltime_onejob=600;%seconds, max estimated time for asingle file index value
1749        filename_joblist=fullfile(DirOAR,'job_list.txt');%create name of the global executable file
1750        fid=fopen(filename_joblist,'w');
1751        for p=1:length(batch_file_list)
1752            fprintf(fid,[batch_file_list{p} '\n']);% list of exe files
1753        end
1754        fclose(fid);
1755        system(['chmod +x ' filename_joblist]);% set the file to executable
1756        oar_command=['oarsub -n CIVX '...
1757            '-t idempotent --checkpoint ' num2str(walltime_onejob+60) ' '...
1758            '-l /core=' num2str(NbCore) ','...
1759            'walltime=' datestr(min(1.05*walltime_onejob/86400*max(NbProcess*BlockLength*nbfield_j,NbCore)/NbCore,max_walltime/86400),13) ' '...
1760            '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
1761            '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
1762            extra_oar ' '...
1763            '"oar-parexec -s -f ' filename_joblist ' '...
1764            '-l ' filename_joblist '.log"\n'];
1765        filename_oarcommand=fullfile(DirOAR,'oar_command');
1766        fid=fopen(filename_oarcommand,'w');
1767        fprintf(fid,oar_command);
1768        fclose(fid);
1769        fprintf(oar_command);% display in command line
1770        %system(['chmod +x ' oar_command]);% set the file to executable
1771        system(oar_command);     
1772end
1773
1774%% reset the GUI series
1775update_waitbar(handles.Waitbar,1); % put the waitbar to end position to indicate launching is finished
1776set(handles.RUN, 'Enable','On')
1777set(handles.RUN,'BackgroundColor',[1 0 0])
1778set(handles.RUN, 'Value',0)
1779
1780%------------------------------------------------------------------------
1781function STOP_Callback(hObject, eventdata, handles)
1782%------------------------------------------------------------------------
1783set(handles.RUN, 'BusyAction','cancel')
1784set(handles.RUN,'BackgroundColor',[1 0 0])
1785set(handles.RUN,'enable','on')
1786set(handles.RUN, 'Value',0)
1787
1788% %------------------------------------------------------------------------
1789% % --- Executes on button press in BIN.
1790% function BIN_Callback(hObject, eventdata, handles)
1791% %------------------------------------------------------------------------
1792%     cmd=['#!/bin/bash \n '...
1793%         '#$ -cwd \n '...
1794%         'hostname && date \n '...
1795%         'umask 002 \n'...
1796%         Param.xml.CivmBin ' ' Param.xml.RunTime ' ' filename_xml ' ' OutputFile '.nc'];
1797%     
1798%------------------------------------------------------------------------
1799% --- Main launch command, called by RUN and BATCH
1800
1801%------------------------------------------------------------------------
1802% --- read parameters from the GUI series
1803%------------------------------------------------------------------------
1804function Param=read_GUI_series(handles)
1805
1806%% read raw parameters from the GUI series
1807Param=read_GUI(handles.series);
1808
1809%% clean the output structure by removing unused information
1810if isfield(Param,'Pairs')
1811    Param=rmfield(Param,'Pairs'); %info Pairs not needed for output
1812end
1813Param.IndexRange=rmfield(Param.IndexRange,'TimeTable');
1814empty_line=false(size(Param.InputTable,1),1);
1815for iline=1:size(Param.InputTable,1)
1816    empty_line(iline)=isempty(cell2mat(Param.InputTable(iline,1:3)));
1817end
1818Param.InputTable(empty_line,:)=[];
1819
1820%------------------------------------------------------------------------
1821% --- Executes on selection change in ActionName.
1822function ActionName_Callback(hObject, eventdata, handles)
1823%------------------------------------------------------------------------
1824%% stop any ongoing series processing
1825if isequal(get(handles.RUN,'Value'),1)
1826    answer= msgbox_uvmat('INPUT_Y-N','stop current Action process?');
1827    if strcmp(answer,'Yes')
1828        STOP_Callback(hObject, eventdata, handles)
1829    else
1830        return
1831    end
1832end
1833set(handles.ActionName,'BackgroundColor',[1 1 0])
1834drawnow
1835
1836%% get Action name and path
1837nb_builtin_ACTION=4; %nbre of functions initially proposed in the menu ActionName (as defined in the Opening fct of series)
1838ActionList=get(handles.ActionName,'String');% list menu fields
1839ActionIndex=get(handles.ActionName,'Value');
1840if ~isequal(ActionIndex,1)% if we are not just opening series
1841    InputTable=get(handles.InputTable,'Data');
1842    if isempty(InputTable{1,4})
1843        msgbox_uvmat('ERROR','no input file available: use Open in the menu bar')
1844        return
1845    end
1846end
1847ActionName= ActionList{get(handles.ActionName,'Value')}; % selected function name
1848ActionPathList=get(handles.ActionName,'UserData');%list of recorded paths to functions of the list ActionName
1849
1850%% add a new function to the menu if 'more...' has been selected in the menu ActionName
1851if isequal(ActionName,'more...')
1852    [FileName, PathName] = uigetfile( ...
1853        {'*.m', ' (*.m)';
1854        '*.m',  '.m files '; ...
1855        '*.*', 'All Files (*.*)'}, ...
1856        'Pick a series processing function ',get(handles.ActionPath,'String'));
1857    if length(FileName)<2
1858        return
1859    end
1860    [ActionPath,ActionName,ActionExt]=fileparts(FileName);
1861   
1862    % insert the choice in the menu ActionName
1863    ActionIndex=find(strcmp(ActionName,ActionList),1);% look for the selected function in the menu Action
1864    if isempty(ActionIndex)%the input string does not exist in the menu
1865        ActionIndex= length(ActionList);
1866        ActionList=[ActionList(1:end-1);{ActionName};ActionList(end)];% the selected function is appended in the menu, before the last item 'more...'
1867        set(handles.ActionName,'String',ActionList)
1868    end
1869   
1870    % record the file extension and extend the path list if it is a new extension
1871    ActionExtList=get(handles.ActionExt,'String');
1872    ActionExtIndex=find(strcmp(ActionExt,ActionExtList), 1);
1873    if isempty(ActionExtIndex)
1874        set(handles.ActionExt,'String',[ActionExtList;{ActionExt}])
1875        ActionExtIndex=numel(ActionExtList)+1;
1876        ActionPathNew=cell(size(ActionPathList,1),1);%new column of ActionPath
1877        ActionPathList=[ActionPathList ActionPathNew];
1878    end
1879    set(handles.ActionName,'UserData',ActionPathList);
1880
1881    % remove old Action options in the menu (keeping a menu length <nb_builtin_ACTION+5)
1882    if length(ActionList)>nb_builtin_ACTION+5; %nb_builtin=nbre of functions always remaining in the initial menu
1883        nbremove=length(ActionList)-nb_builtin_ACTION-5;
1884        ActionList(nb_builtin_ACTION+1:end-5)=[];
1885        ActionPathList(nb_builtin_ACTION+1:end-4,:)=[];
1886        ActionIndex=ActionIndex-nbremove;
1887    end
1888   
1889    % record action menu, choice and path
1890    set(handles.ActionName,'Value',ActionIndex)
1891    set(handles.ActionName,'String',ActionList)
1892    set(handles.ActionExt,'Value',ActionExtIndex)
1893    ActionPathList{ActionIndex,ActionExtIndex}=PathName;
1894       
1895    %record the user defined menu additions in personal file profil_perso
1896    dir_perso=prefdir;
1897    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
1898    if nb_builtin_ACTION+1<=numel(ActionList)-1
1899        ActionListUser=ActionList(nb_builtin_ACTION+1:numel(ActionList)-1);
1900        ActionPathListUser=ActionPathList(nb_builtin_ACTION+1:numel(ActionList)-1,:);
1901        ActionExtListUser={};
1902        if numel(ActionExtList)>2
1903            ActionExtListUser=ActionExtList(3:end);
1904        end
1905        if exist(profil_perso,'file')
1906            save(profil_perso,'ActionListUser','ActionPathListUser','ActionExtListUser','-append')
1907        else
1908            save(profil_perso,'ActionListUser','ActionPathListUser','ActionExtListUser','-V6')
1909        end
1910    end
1911end
1912
1913%% check the current ActionPath to the selected function
1914ActionPath=ActionPathList{ActionIndex};%current recorded path
1915set(handles.ActionPath,'String',ActionPath); %show the path to the senlected function
1916
1917%% reinitialise the waitbar
1918update_waitbar(handles.Waitbar,0)
1919
1920%% default setting for the visibility of the GUI elements
1921% set(handles.FieldTransform,'Visible','off')
1922% set(handles.CheckObject,'Visible','off');
1923% set(handles.ProjObject,'Visible','off');
1924% set(handles.CheckMask,'Visible','off')
1925% set(handles.Mask,'Visible','off')
1926
1927%% create the function handle for Action
1928path_series=which('series');
1929if ~isequal(ActionPath,path_series)
1930    eval(['spath=which(''' ActionName ''');']) %spath = current path of the selected function ACTION
1931    if ~exist(ActionPath,'dir')
1932        errormsg=['The prescribed function path ' ActionPath ' does not exist'];
1933        return
1934    end
1935    if ~isequal(spath,ActionPath)
1936        addpath(ActionPath)% add the prescribed path if not the current one
1937    end
1938end
1939eval(['h_fun=@' ActionName ';'])%create a function handle for ACTION
1940if ~isequal(ActionPath,path_series)
1941        rmpath(ActionPath)% add the prescribed path if not the current one   
1942end
1943
1944%% Activate the Action fct
1945Param=read_GUI_series(handles);% read the parameters from the GUI series
1946ParamOut=h_fun(Param);
1947
1948%% Put the first line of the selected Action fct as tooltip help
1949try
1950    [fid,errormsg] =fopen([ActionName '.m']);
1951    InputText=textscan(fid,'%s',1,'delimiter','\n');
1952    fclose(fid);
1953    set(handles.ActionName,'ToolTipString',InputText{1}{1})% put the first line of the selected function as tooltip help
1954end
1955
1956%% Detect the types of input files
1957SeriesData=get(handles.series,'UserData');
1958nb_civ=0;nb_netcdf=0;
1959if ~isempty(SeriesData)
1960    nb_civ=numel(find(strcmp('civx',SeriesData.FileType)|strcmp('civdata',SeriesData.FileType)));
1961    nb_netcdf=numel(find(strcmp('netcdf',SeriesData.FileType)));
1962end
1963if nb_civ>=1
1964    menu=set_veltype_display(SeriesData.FileInfo{1}.CivStage,SeriesData.FileType{1});
1965    set(handles.VelType,'String',[{'*'};menu])
1966    if nb_civ>=2
1967        menu=set_veltype_display(SeriesData.FileInfo{2}.CivStage,SeriesData.FileType{2});
1968        set(handles.VelType_1,'String',[{'*'};menu])
1969    end
1970end
1971       
1972   
1973
1974%% Check whether alphabetical sorting of input Subdir is alowed by the Action fct  (for multiples series entries)
1975if isfield(ParamOut,'AllowInputSort')&&isequal(ParamOut.AllowInputSort,'on')&& size(Param.InputTable,1)>1
1976    [tild,iview]=sort(InputTable(:,2)); %subdirectories sorted in alphabetical order
1977    set(handles.InputTable,'Data',InputTable(iview,:));
1978    MinIndex_i=get(handles.MinIndex_i,'Data');
1979    MinIndex_j=get(handles.MinIndex_j,'Data');
1980    MaxIndex_i=get(handles.MaxIndex_i,'Data');
1981    MaxIndex_j=get(handles.MaxIndex_j,'Data');
1982    set(handles.MinIndex_i,'Data',MinIndex_i(iview,:));
1983    set(handles.MinIndex_j,'Data',MinIndex_j(iview,:));
1984    set(handles.MaxIndex_i,'Data',MaxIndex_i(iview,:));
1985    set(handles.MaxIndex_j,'Data',MaxIndex_j(iview,:));
1986    TimeTable=get(handles.TimeTable,'Data');
1987    set(handles.TimeTable,'Data',TimeTable(iview,:));
1988    PairString=get(handles.PairString,'Data');
1989    set(handles.PairString,'Data',PairString(iview,:));
1990end
1991
1992%% Impose the whole input file index range if requested
1993if isfield(ParamOut,'WholeIndexRange')&&isequal(ParamOut.WholeIndexRange,'on')
1994    MinIndex_i=get(handles.MinIndex_i,'Data');
1995    MinIndex_j=get(handles.MinIndex_j,'Data');
1996    MaxIndex_i=get(handles.MaxIndex_i,'Data');
1997    MaxIndex_j=get(handles.MaxIndex_j,'Data');
1998    set(handles.num_first_i,'String',num2str(MinIndex_i(1)))% set first as the min index (for the first line)
1999    set(handles.num_last_i,'String',num2str(MaxIndex_i(1)))% set last as the max index (for the first line)
2000    set(handles.num_incr_i,'String','1')
2001    set(handles.num_first_j,'String',num2str(MinIndex_j(1)))% set first as the min index (for the first line)
2002    set(handles.num_last_j,'String',num2str(MaxIndex_j(1)))% set last as the max index (for the first line)
2003    set(handles.num_incr_j,'String','1')
2004else  % check index ranges
2005    first_i=1;last_i=1;first_j=1;last_j=1;
2006    if isfield(Param.IndexRange,'first_i')
2007        first_i=Param.IndexRange.first_i;
2008       % incr_i=Param.IndexRange.incr_i;
2009        last_i=Param.IndexRange.last_i;
2010    end
2011    if isfield(Param.IndexRange,'first_j')
2012        first_j=Param.IndexRange.first_j;
2013       % incr_j=Param.IndexRange.incr_j;
2014        last_j=Param.IndexRange.last_j;
2015    end
2016    if last_i < first_i || last_j < first_j , msgbox_uvmat('ERROR','last field number must be larger than the first one'),...
2017            set(handles.RUN, 'Enable','On'), set(handles.RUN,'BackgroundColor',[1 0 0]),return,end;
2018end
2019
2020%% NbSlice visibility
2021NbSliceVisible='off';%default
2022if isfield(ParamOut,'NbSlice') && isequal(ParamOut.NbSlice,'on')
2023    NbSliceVisible='on';
2024    set(handles.num_NbProcess,'String',get(handles.num_NbSlice,'String'))% the nbre of processes is imposed as the nbre of slices
2025else
2026    set(handles.num_NbProcess,'String','')% free nbre of processes
2027end
2028set(handles.num_NbSlice,'Visible',NbSliceVisible)
2029set(handles.NbSlice_title,'Visible',NbSliceVisible)
2030
2031%% Visibility of VelType and VelType_1 menus
2032VelTypeVisible='off';  %hidden by default
2033VelType_1Visible='off';
2034InputFieldsVisible='off';%visibility of the frame Fields
2035if isfield(ParamOut,'VelType')
2036    if strcmp( ParamOut.VelType,'one')||strcmp( ParamOut.VelType,'two')
2037        if nb_civ>=1
2038            VelTypeVisible='on';
2039            InputFieldsVisible='on';
2040        end
2041    end
2042    if strcmp( ParamOut.VelType,'two')
2043        if nb_civ>=2
2044            VelType_1Visible='on';
2045        end
2046    end
2047end
2048set(handles.VelType,'Visible',VelTypeVisible)
2049set(handles.VelType_text,'Visible',VelTypeVisible);
2050set(handles.VelType_1,'Visible',VelType_1Visible)
2051set(handles.VelType_text_1,'Visible',VelType_1Visible);
2052
2053%% Visibility of FieldName and FieldName_1 menus
2054FieldNameVisible='off';  %hidden by default
2055FieldName_1Visible='off';  %hidden by default
2056if isfield(ParamOut,'FieldName')
2057    if strcmp( ParamOut.FieldName,'one')||strcmp( ParamOut.FieldName,'two')
2058        if (nb_civ+nb_netcdf)>=1
2059            InputFieldsVisible='on';
2060            FieldNameVisible='on';
2061        end
2062    end
2063    if strcmp( ParamOut.FieldName,'two')
2064        if (nb_civ+nb_netcdf)>=1
2065            FieldName_1Visible='on';
2066        end
2067    end
2068end
2069set(handles.InputFields,'Visible',InputFieldsVisible)
2070set(handles.FieldName,'Visible',FieldNameVisible) % test for MenuBorser
2071set(handles.FieldName_1,'Visible',FieldName_1Visible)
2072
2073%% Visibility of FieldTransform menu
2074FieldTransformVisible='off';  %hidden by default
2075if isfield(ParamOut,'FieldTransform')
2076    FieldTransformVisible=ParamOut.FieldTransform; 
2077    TransformName_Callback([],[], handles)
2078end
2079set(handles.FieldTransform,'Visible',FieldTransformVisible)
2080if isfield(ParamOut,'TransformPath')
2081    set(handles.ActionExt,'UserData',ParamOut.TransformPath)
2082else
2083    set(handles.ActionExt,'UserData',[])
2084end
2085
2086%% Visibility of projection object
2087ProjObjectVisible='off';  %hidden by default
2088if isfield(ParamOut,'ProjObject')
2089    ProjObjectVisible=ParamOut.ProjObject;
2090end
2091set(handles.CheckObject,'Visible',ProjObjectVisible)
2092if ~get(handles.CheckObject,'Value')
2093    ProjObjectVisible='off';
2094end
2095set(handles.ProjObject,'Visible',ProjObjectVisible)
2096set(handles.DeleteObject,'Visible',ProjObjectVisible)
2097set(handles.ViewObject,'Visible',ProjObjectVisible)
2098
2099
2100%% Visibility of mask input
2101MaskVisible='off';  %hidden by default
2102if isfield(ParamOut,'Mask')
2103    MaskVisible=ParamOut.Mask;
2104end
2105%set(handles.Mask,'Visible',MaskVisible)
2106set(handles.CheckMask,'Visible',MaskVisible);
2107
2108%% definition of the directory containing the output files
2109OutputDirVisible='off';
2110if isfield(ParamOut,'OutputDirExt')&&~isempty(ParamOut.OutputDirExt)
2111    set(handles.OutputDirExt,'String',ParamOut.OutputDirExt)
2112    OutputDirVisible='on';
2113    SubDir=InputTable(1:end-1,2); %set of subdirectories sorted in alphabetical order
2114    SubDirOut=SubDir{1};
2115    if numel(SubDir)>1
2116        for ilist=2:numel(SubDir)
2117            SubDirOut=[SubDirOut '-' SubDir{ilist}];
2118        end
2119    end
2120    set(handles.OutputSubDir,'String',SubDirOut)
2121end
2122set(handles.OutputDirExt,'Visible',OutputDirVisible)
2123set(handles.OutputSubDir,'Visible',OutputDirVisible)
2124set(handles.OutputDir_title,'Visible',OutputDirVisible)
2125set(handles.RunMode,'Visible',OutputDirVisible)
2126set(handles.ActionExt,'Visible',OutputDirVisible)
2127set(handles.RunMode_title,'Visible',OutputDirVisible)
2128set(handles.ActionExt_title,'Visible',OutputDirVisible)
2129
2130
2131%% Expected nbre of output files
2132if isfield(ParamOut,'OutputFileMode')
2133StatusData.OutputFileMode=ParamOut.OutputFileMode;
2134set(handles.status,'UserData',StatusData)
2135end
2136
2137%% definition of an additional parameter set, determined by an ancillary GUI
2138if isfield(ParamOut,'ActionInput')
2139    set(handles.ActionInput,'Visible','on')
2140    set(handles.ActionInput_title,'Visible','on')
2141    set(handles.ActionInputView,'Visible','on')
2142    set(handles.ActionInputView,'Value',0)
2143    set(handles.ActionInput,'String',ActionName)
2144    ParamOut.ActionInput.Program=ActionName; % record the program in ActionInput
2145    SeriesData.ActionInput=ParamOut.ActionInput;
2146else
2147    set(handles.ActionInput,'Visible','off')
2148    set(handles.ActionInput_title,'Visible','off')
2149    set(handles.ActionInputView,'Visible','off')
2150    if isfield(SeriesData,'ActionInput')
2151    SeriesData=rmfield(SeriesData,'ActionInput');
2152    end
2153end   
2154set(handles.series,'UserData',SeriesData)
2155set(handles.ActionName,'BackgroundColor',[1 1 1])
2156
2157%------------------------------------------------------------------------
2158% --- Executes on button press in ActionInputView.
2159function ActionInputView_Callback(hObject, eventdata, handles)
2160%------------------------------------------------------------------------
2161if get(handles.ActionInputView,'Value')
2162ActionName_Callback(hObject, eventdata, handles)
2163end
2164
2165%------------------------------------------------------------------------
2166% --- Executes on selection change in FieldName.
2167function FieldName_Callback(hObject, eventdata, handles)
2168%------------------------------------------------------------------------
2169field_str=get(handles.FieldName,'String');
2170field_index=get(handles.FieldName,'Value');
2171field=field_str{field_index(1)};
2172if isequal(field,'get_field...')
2173    hget_field=findobj(allchild(0),'name','get_field');
2174    if ~isempty(hget_field)
2175        delete(hget_field)%delete opened versions of get_field
2176    end
2177    Param=read_GUI(handles.series);
2178    Param.InputTable=Param.InputTable(1,:);
2179    filecell=get_file_series(Param);
2180    if exist(filecell{1,1},'file')
2181        GetFieldData=get_field(filecell{1,1});
2182        FieldList={};
2183        XName=GetFieldData.XVarName;
2184        if GetFieldData.CheckVector
2185            UName=GetFieldData.PanelVectors.vector_x;
2186            VName=GetFieldData.PanelVectors.vector_y;
2187            XName=GetFieldData.XVarName;
2188            YName=GetFieldData.YVarName;
2189            CName=GetFieldData.PanelVectors.vec_color;
2190            [FieldList,VecColorList]=set_field_list(UName,VName,CName);
2191        elseif GetFieldData.CheckScalar
2192            AName=GetFieldData.PanelScalar.scalar;
2193            XName=GetFieldData.XVarName;
2194            YName=GetFieldData.YVarName;
2195            FieldList={AName};
2196        elseif GetFieldData.CheckPlot1D;
2197            YName=GetFieldData.CheckPlot1D.ordinate;
2198        end
2199        set(handles.Coord_x,'String',{XName})
2200        set(handles.Coord_y,'String',{YName})
2201        set(handles.FieldName,'Value',1)
2202        set(handles.FieldName,'String',[FieldList; {'get_field...'}]);
2203        %         set(handles.ColorScalar,'Value',1)
2204        %         set(handles.ColorScalar,'String',VecColorList);
2205        %         UvData.FileType{1}='netcdf';
2206        %         set(handles.uvmat,'UserData',UvData)
2207    end
2208    % elseif isequal(field,'more...')
2209    %     str=calc_field;
2210    %     [ind_answer,v] = listdlg('PromptString','Select a file:',...
2211    %                 'SelectionMode','single',...
2212    %                 'ListString',str);
2213    %        % edit the choice in the fields and actionname menu
2214    %      scalar=cell2mat(str(ind_answer));
2215    %      update_menu(handles.FieldName,scalar)
2216end
2217
2218%------------------------------------------------------------------------
2219% --- Executes on selection change in FieldName_1.
2220function FieldName_1_Callback(hObject, eventdata, handles)
2221%------------------------------------------------------------------------
2222field_str=get(handles.FieldName_1,'String');
2223field_index=get(handles.FieldName_1,'Value');
2224field=field_str{field_index};
2225if isequal(field,'get_field...')   
2226     hget_field=findobj(allchild(0),'name','get_field_1');
2227     if ~isempty(hget_field)
2228         delete(hget_field)
2229     end
2230     SeriesData=get(handles.series,'UserData');
2231     filename=SeriesData.CurrentInputFile_1;
2232     if exist(filename,'file')
2233        hget_field=get_field(filename);
2234        set(hget_field,'name','get_field_1')
2235     end
2236% elseif isequal(field,'more...')
2237%     str=calc_field;
2238%     [ind_answer,v] = listdlg('PromptString','Select a file:',...
2239%                 'SelectionMode','single',...
2240%                 'ListString',str);
2241%        % edit the choice in the fields and actionname menu
2242%      scalar=cell2mat(str(ind_answer));
2243%      update_menu(handles.FieldName_1,scalar)
2244end   
2245
2246
2247%%%%%%%%%%%%%
2248function [ind_remove]=find_pairs(dirpair,ind_i,last_i)
2249indsel=ind_i;
2250indiff=diff(ind_i); %test index increment to detect multiplets (several pairs with the same index ind_i) and holes in the series
2251indiff=[1 indiff last_i-ind_i(end)+1];%for testing gaps with the imposed bounds
2252if ~isempty(indiff)
2253    indiff2=diff(indiff);
2254    indiffp=[indiff2 1];
2255    indiffm=[1 indiff2];
2256    ind_multi_m=find((indiff==0)&(indiffm<0))-1;%indices of first members of multiplets
2257    ind_multi_p=find((indiff==0)&(indiffp>0));%indices of last members of multiplets
2258    %for each multiplet, select the most recent file
2259    ind_remove=[];
2260    for i=1:length(ind_multi_m)
2261        ind_pairs=ind_multi_m(i):ind_multi_p(i);
2262        for imulti=1:length(ind_pairs)
2263            datepair(imulti)=datenum(dirpair(ind_pairs(imulti)).date);%dates of creation
2264        end
2265        [datenew,indsort2]=sort(datepair); %sort the multiplet by creation date
2266        ind_s=indsort2(1:end-1);%
2267        ind_remove=[ind_remove ind_pairs(ind_s)];%remove these indices, leave the last one
2268    end
2269end
2270
2271%------------------------------------------------------------------------
2272% --- determine the list of index pairstring of processing file
2273function [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)
2274%------------------------------------------------------------------------
2275num_i1=num_i;% set of first image numbers by default
2276num_i2=num_i;
2277num_j1=num_j;
2278num_j2=num_j;
2279num_i_out=num_i;
2280num_j_out=num_j;
2281% if isequal (NomType,'_1-2_1') || isequal (NomType,'_1-2')
2282if isequal(mode,'series(Di)')
2283    num_i1_line=num_i+ind_shift(3);% set of first image numbers
2284    num_i2_line=num_i+ind_shift(4);
2285    % adjust the first and last field number
2286        indsel=find(num_i1_line >= 1);
2287    num_i_out=num_i(indsel);
2288    num_i1_line=num_i1_line(indsel);
2289    num_i2_line=num_i2_line(indsel);
2290    num_j1=meshgrid(num_j,ones(size(num_i1_line)));
2291    num_j2=meshgrid(num_j,ones(size(num_i1_line)));
2292    [xx,num_i1]=meshgrid(num_j,num_i1_line);
2293    [xx,num_i2]=meshgrid(num_j,num_i2_line);
2294elseif isequal (mode,'series(Dj)')||isequal (mode,'bursts')
2295    if isequal(mode,'bursts') %case of bursts (png_old or png_2D)
2296        num_j1=ind_shift(1)*ones(size(num_i));
2297        num_j2=ind_shift(2)*ones(size(num_i));
2298    else
2299        num_j1_col=num_j+ind_shift(1);% set of first image numbers
2300        num_j2_col=num_j+ind_shift(2);
2301        % adjust the first field number
2302        indsel=find((num_j1_col >= 1));   
2303        num_j_out=num_j(indsel);
2304        num_j1_col=num_j1_col(indsel);
2305        num_j2_col=num_j2_col(indsel);
2306        [num_i1,num_j1]=meshgrid(num_i,num_j1_col);
2307        [num_i2,num_j2]=meshgrid(num_i,num_j2_col);
2308    end   
2309end
2310
2311%------------------------------------------------------------------------
2312% --- Executes on button press in CheckObject.
2313%------------------------------------------------------------------------
2314function CheckObject_Callback(hObject, eventdata, handles)
2315
2316hset_object=findobj(allchild(0),'tag','set_object');%find the set_object interface handle
2317if get(handles.CheckObject,'Value')
2318    SeriesData=get(handles.series,'UserData');
2319    if isfield(SeriesData,'ProjObject') && ~isempty(SeriesData.ProjObject)
2320        set(handles.ViewObject,'Value',1)
2321        ViewObject_Callback(hObject, eventdata, handles)
2322    else
2323        if ishandle(hset_object)
2324            uistack(hset_object,'top')% show the GUI set_object if opened
2325        else
2326            %get the object file
2327            InputTable=get(handles.InputTable,'Data');
2328            defaultname=InputTable{1,1};
2329            if isempty(defaultname)
2330                defaultname={''};
2331            end
2332            [FileName, PathName] = uigetfile( ...
2333                {'*.xml;*.mat', ' (*.xml,*.mat)';
2334                '*.xml',  '.xml files '; ...
2335                '*.mat',  '.mat matlab files '}, ...
2336                'Pick an xml object file (or use uvmat to create it)',defaultname);
2337            fileinput=[PathName FileName];%complete file name
2338            sizf=size(fileinput);
2339            if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end
2340            %read the file
2341            data=xml2struct(fileinput);
2342            if ~isfield(data,'Type')
2343                msgbox_uvmat('ERROR',[fileinput ' is not an object xml file'])
2344                return
2345            end
2346            if ~isfield(data,'ProjMode')
2347                data.ProjMode='none';
2348            end
2349            hset_object=set_object(data);% call the set_object interface
2350        end
2351        ProjObject=read_GUI(hset_object);
2352        set(handles.ProjObject,'String',ProjObject.Name);%display the object name
2353        SeriesData=get(handles.series,'UserData');
2354        SeriesData.ProjObject=ProjObject;
2355        set(handles.series,'UserData',SeriesData);
2356    end
2357    set(handles.EditObject,'Visible','on');
2358    set(handles.DeleteObject,'Visible','on');
2359    set(handles.ViewObject,'Visible','on');
2360    set(handles.ProjObject,'Visible','on');
2361else
2362    set(handles.EditObject,'Visible','off');
2363    set(handles.DeleteObject,'Visible','off');
2364    set(handles.ViewObject,'Visible','off');
2365    if ~ishandle(hset_object)
2366    set(handles.ViewObject,'Value',0);
2367    end
2368    set(handles.ProjObject,'Visible','off');
2369end
2370
2371%------------------------------------------------------------------------
2372% --- Executes on button press in ViewObject.
2373%------------------------------------------------------------------------
2374function ViewObject_Callback(hObject, eventdata, handles)
2375
2376if get(handles.ViewObject,'Value')
2377    set(handles.EditObject,'Value',0)
2378        UserData=get(handles.series,'UserData');
2379    hset_object=set_object(UserData.ProjObject);
2380    set(hset_object,'Name','view_object_series')
2381else
2382    hset_object=findobj(allchild(0),'Tag','set_object');
2383    if ~isempty(hset_object)
2384        delete(hset_object)
2385    end
2386end
2387
2388%------------------------------------------------------------------------
2389% --- Executes on button press in EditObject.
2390%------------------------------------------------------------------------
2391function EditObject_Callback(hObject, eventdata, handles)
2392
2393if get(handles.EditObject,'Value')
2394    set(handles.ViewObject,'Value',0)
2395        UserData=get(handles.series,'UserData');
2396    hset_object=set_object(UserData.ProjObject);
2397    set(hset_object,'Name','edit_object_series')
2398    set(get(hset_object,'Children'),'Enable','on')
2399else
2400    hset_object=findobj(allchild(0),'Tag','set_object');
2401    if ~isempty(hset_object)
2402        delete(hset_object)
2403    end
2404end
2405
2406%------------------------------------------------------------------------
2407% --- Executes on button press in DeleteObject.
2408%------------------------------------------------------------------------
2409function DeleteObject_Callback(hObject, eventdata, handles)
2410
2411if get(handles.DeleteObject,'Value')
2412        SeriesData=get(handles.series,'UserData');
2413    SeriesData.ProjObject=[];
2414    set(handles.series,'UserData',SeriesData)
2415    set(handles.ProjObject,'String','')
2416    set(handles.CheckObject,'Value',0)
2417    set(handles.DeleteObject,'Visible','off')
2418    set(handles.ViewObject,'Visible','off')
2419    set(handles.DeleteObject,'Value',0)
2420end
2421
2422%--------------------------------------------------------------
2423function CheckMask_Callback(hObject, eventdata, handles)
2424if get(handles.CheckMask,'Value')
2425    InputTable=get(handles.InputTable,'Data');
2426    for iview=1:size(InputTable,1)
2427        RootPath=InputTable{iview,1};
2428        SubDir=InputTable{iview,2};
2429        MaskSubDir=regexprep(SubDir,'\..*','');%take the root part of SubDir, before the first dot '.'
2430        MaskName=fullfile(RootPath,[MaskSubDir '.mask'],'mask_1.png');
2431        if ~exist(MaskName,'file')
2432            msgbox_uvmat('WARNING',['mask file '  MaskName ' not found'])
2433            return
2434        end
2435    end
2436end
2437%--------------------------------------------------------------
2438
2439%-------------------------------------------------------------------
2440%'uv_ncbrowser': interactively calls the netcdf file browser 'get_field.m'
2441function ncbrowser_uvmat(hObject, eventdata)
2442%-------------------------------------------------------------------
2443     bla=get(gcbo,'String');
2444     ind=get(gcbo,'Value');
2445     filename=cell2mat(bla(ind));
2446      blank=find(filename==' ');
2447      filename=filename(1:blank-1);
2448     get_field(filename)
2449
2450% ------------------------------------------------------------------
2451function MenuHelp_Callback(hObject, eventdata, handles)
2452%-------------------------------------------------------------------
2453path_to_uvmat=which ('uvmat');% check the path of uvmat
2454pathelp=fileparts(path_to_uvmat);
2455helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
2456if isempty(dir(helpfile)), msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
2457else
2458    addpath (fullfile(pathelp,'uvmat_doc'))
2459    web([helpfile '#series'])
2460end
2461
2462%-------------------------------------------------------------------
2463% --- Executes on selection change in TransformName.
2464function TransformName_Callback(hObject, eventdata, handles)
2465%----------------------------------------------------------------------
2466TransformList=get(handles.TransformName,'String');
2467TransformIndex=get(handles.TransformName,'Value');
2468TransformName=TransformList{TransformIndex};
2469TransformPathList=get(handles.TransformName,'UserData');
2470nb_builtin_transform=4;
2471% ff=functions(list_transform{end});
2472if isequal(TransformName,'more...');
2473%     coord_fct='';
2474%     prompt = {'Enter the name of the transform function'};
2475%     dlg_title = 'user defined transform';
2476%     num_lines= 1;
2477    [FileName, PathName] = uigetfile( ...
2478       {'*.m', ' (*.m)';
2479        '*.m',  '.m files '; ...
2480        '*.*', 'All Files (*.*)'}, ...
2481        'Pick a transform function',get(handles.TransformPath,'String'));
2482    if isequal(FileName,0)
2483        return     %browser closed without choice
2484    end
2485    if isequal(PathName(end),'/')||isequal(PathName(end),'\')
2486        PathName(end)=[];
2487    end
2488    [TransformPath,TransformName,TransformExt]=fileparts(FileName);% removes extension .m
2489    if ~strcmp(TransformExt,'.m')
2490        msgbox_uvmat('ERROR','a Matlab function .m must be introduced');
2491        return
2492    end
2493     % insert the choice in the menu
2494    TransformIndex=find(strcmp(TransformName,TransformList),1);% look for the selected function in the menu Action
2495    if isempty(TransformIndex)%the input string does not exist in the menu
2496        TransformIndex= length(TransformList);
2497        TransformList=[TransformList(1:end-1);{TransformName};TransformList(end)];% the selected function is appended in the menu, before the last item 'more...'
2498        set(handles.TransformName,'String',TransformList)
2499        TransformPathList=[TransformPathList;{TransformPath}];
2500    end
2501   % save the new menu in the personal file 'uvmat_perso.mat'
2502   dir_perso=prefdir;%personal Matalb directory
2503   profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
2504   if exist(profil_perso,'file')
2505       for ilist=nb_builtin_transform+1:numel(TransformPathList)
2506           TransformListUser{ilist-nb_builtin_transform}=TransformList{ilist};
2507           TransformPathListUser{ilist-nb_builtin_transform}=TransformPathList{ilist};
2508       end
2509       save (profil_perso,'TransformPathListUser','TransformListUser','-append'); %store the root name for future opening of uvmat
2510   end
2511end
2512
2513%display the current function path
2514set(handles.TransformPath,'String',TransformPathList{TransformIndex}); %show the path to the senlected function
2515set(handles.TransformName,'UserData',TransformPathList);
2516
2517%------------------------------------------------------------------------
2518% --- fct activated by the upper bar menu ExportConfig
2519%------------------------------------------------------------------------
2520function MenuExportConfig_Callback(hObject, eventdata, handles)
2521
2522global Param
2523Param=read_GUI_series(handles);
2524evalin('base','global Param')%make CurData global in the workspace
2525display('current series config :')
2526evalin('base','Param') %display CurData in the workspace
2527commandwindow; %brings the Matlab command window to the front
2528
2529%------------------------------------------------------------------------
2530% --- fct activated by the upper bar menu InportConfig
2531%------------------------------------------------------------------------
2532function MenuImportConfig_Callback(hObject, eventdata, handles)
2533
2534InputTable=get(handles.InputTable,'Data');
2535[FileName, PathName] = uigetfile( ...
2536       {'*.xml', ' (*.xml)';
2537       '*.xml',  '.xml files '; ...
2538        '*.*',  'All Files (*.*)'}, ...
2539        'Pick a file',InputTable{1,1});
2540filexml=[PathName FileName];%complete file name
2541if isempty(filexml),return;end %abandon if no file is introduced by the browser
2542Param=xml2struct(filexml);
2543fill_GUI(Param,handles.series)
2544
2545%------------------------------------------------------------------------
2546% --- Executes when the GUI series is resized.
2547%------------------------------------------------------------------------
2548function series_ResizeFcn(hObject, eventdata, handles)
2549
2550%% input table
2551set(handles.InputTable,'Unit','pixel')
2552Pos=get(handles.InputTable,'Position');
2553set(handles.InputTable,'Unit','normalized')
2554ColumnWidth=round([0.5 0.14 0.14 0.14 0.08]*(Pos(3)-52));
2555ColumnWidth=num2cell(ColumnWidth);
2556set(handles.InputTable,'ColumnWidth',ColumnWidth)
2557
2558%% MinIndex_j and MaxIndex_i
2559unit=get(handles.MinIndex_i,'Unit');
2560set(handles.MinIndex_i,'Unit','pixel')
2561Pos=get(handles.MinIndex_i,'Position');
2562set(handles.MinIndex_i,'Unit',unit)
2563set(handles.MinIndex_i,'ColumnWidth',{Pos(3)-18})
2564set(handles.MaxIndex_i,'ColumnWidth',{Pos(3)-18})
2565set(handles.MinIndex_j,'ColumnWidth',{Pos(3)-18})
2566set(handles.MaxIndex_j,'ColumnWidth',{Pos(3)-18})
2567
2568%% TimeTable
2569set(handles.TimeTable,'Unit','pixel')
2570Pos=get(handles.TimeTable,'Position');
2571set(handles.TimeTable,'Unit','normalized')
2572% ColumnWidth=get(handles.TimeTable,'ColumnWidth');
2573ColumnWidth=num2cell(floor([0.25 0.25 0.25 0.25]*(Pos(3)-20)));
2574set(handles.TimeTable,'ColumnWidth',ColumnWidth)
2575
2576
2577%% PairString
2578set(handles.PairString,'Unit','pixel')
2579Pos=get(handles.PairString,'Position');
2580set(handles.PairString,'Unit','normalized')
2581set(handles.PairString,'ColumnWidth',{Pos(3)-5})
2582
2583
2584% --- Executes on button press in status.
2585function status_Callback(hObject, eventdata, handles)
2586
2587if get(handles.status,'Value')
2588    set(handles.status,'BackgroundColor',[1 1 0])
2589    drawnow
2590    %StatusData.time_ref=get(handles.RUN,'UserData');% get the time of launch
2591    Param=read_GUI(handles.series);
2592    RootPath=Param.InputTable{1,1};
2593    if ~isfield(Param,'OutputSubDir')   
2594        msgbox_uvmat('ERROR','no directory defined for output files')
2595        return
2596    end
2597    OutputSubDir=[Param.OutputSubDir Param.OutputDirExt];% subdirectory for output files
2598    OutputDir=fullfile(RootPath,OutputSubDir);
2599    uigetfile_uvmat('status_display',OutputDir)
2600   
2601%     hfig=findobj(allchild(0),'name','series_status');
2602%     if isempty(hfig)
2603%         ScreenSize=get(0,'ScreenSize');
2604%         hfig=figure('DeleteFcn',@stop_status,'Position',[ScreenSize(3)-600 ScreenSize(4)-640 560 600]);
2605%         set(hfig,'MenuBar','none')% suppress the menu bar
2606%         set(hfig,'NumberTitle','off')%suppress the fig number in the title
2607%         set(hfig,'name','series_status')
2608%         set(hfig,'tag','series_status')
2609%         uicontrol('Style','listbox','Units','normalized', 'Position',[0.05 0.09 0.9 0.71], 'Callback', @view_file,'tag','list','UserData',OutputDir);
2610%         uicontrol('Style','edit','Units','normalized', 'Position', [0.05 0.87 0.9 0.1],'tag','titlebox','Max',2,'String',OutputDir);
2611%         uicontrol('Style','frame','Units','normalized', 'Position', [0.05 0.81 0.9 0.05]);
2612%         uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.7 0.01 0.2 0.07],'String','Close','FontWeight','bold','FontUnits','points','FontSize',11,'Callback',@stop_status);
2613%         uicontrol('Style','pushbutton','Units','normalized', 'Position', [0.1 0.01 0.2 0.07],'String','Refresh','FontWeight','bold','FontUnits','points','FontSize',11,'Callback',@refresh_GUI);
2614%         %set(hrefresh,'UserData',StatusData)
2615%         BarPosition=[0.05 0.81 0.01 0.05];
2616%         uicontrol('Style','frame','Units','normalized', 'Position',BarPosition ,'BackgroundColor',[1 0 0],'tag','waitbar');
2617%         drawnow
2618%     end
2619%     refresh_GUI(hfig)
2620else
2621    %% delete current display fig if selection is off
2622    set(handles.status,'BackgroundColor',[0 1 0])
2623    hfig=findobj(allchild(0),'name','series_status');
2624    if ~isempty(hfig)
2625        delete(hfig)
2626    end
2627    return
2628end
2629
2630
2631%------------------------------------------------------------------------   
2632% launched by selecting a file on the list
2633function view_file(hObject, eventdata)
2634%------------------------------------------------------------------------
2635list=get(hObject,'String');
2636index=get(hObject,'Value');
2637rootroot=get(hObject,'UserData');
2638selectname=list{index};
2639ind_dot=regexp(selectname,'\.\.\.');
2640if ~isempty(ind_dot)
2641    selectname=selectname(1:ind_dot-1);
2642end
2643FullSelectName=fullfile(rootroot,selectname);
2644if exist(FullSelectName,'dir')% a directory has been selected
2645    ListFiles=dir(FullSelectName);
2646    ListDisplay=cell(numel(ListFiles),1);
2647    for ilist=2:numel(ListDisplay)% suppress the first line '.'
2648        ListDisplay{ilist-1}=ListFiles(ilist).name;
2649    end
2650    set(hObject,'Value',1)
2651    set(hObject,'String',ListDisplay)
2652    if strcmp(selectname,'..')
2653        FullSelectName=fileparts(fileparts(FullSelectName));
2654    end
2655    set(hObject,'UserData',FullSelectName)
2656    hfig=get(hObject,'parent');
2657    htitlebox=findobj(hfig,'tag','titlebox');   
2658    set(htitlebox,'String',FullSelectName)
2659elseif exist(FullSelectName,'file')%visualise the vel field if it exists
2660    FileType=get_file_type(FullSelectName);
2661    if strcmp(FileType,'txt')
2662        edit(FullSelectName)
2663    elseif strcmp(FileType,'xml')
2664        editxml(FullSelectName)
2665    else
2666        uvmat(FullSelectName)
2667    end
2668    set(gcbo,'Value',1)
2669end
2670
2671
2672%------------------------------------------------------------------------   
2673% launched by refreshing the status figure
2674function refresh_GUI(hfig)
2675%------------------------------------------------------------------------
2676htitlebox=findobj(hfig,'tag','titlebox');
2677hlist=findobj(hfig,'tag','list');
2678hseries=findobj(allchild(0),'tag','series');
2679hstatus=findobj(hseries,'tag','status');
2680StatusData=get(hstatus,'UserData');
2681OutputDir=get(htitlebox,'String');
2682if ischar(OutputDir),OutputDir={OutputDir};end
2683ListFiles=dir(OutputDir{1});
2684if numel(ListFiles)<1
2685    return
2686end
2687ListFiles(1)=[];%removes the first line ='.'
2688ListDisplay=cell(numel(ListFiles),1);
2689testrecent=0;
2690datnum=zeros(numel(ListDisplay),1);
2691for ilist=1:numel(ListDisplay)
2692    ListDisplay{ilist}=ListFiles(ilist).name;
2693      if ~ListFiles(ilist).isdir && isfield(ListFiles(ilist),'datenum')
2694            datnum(ilist)=ListFiles(ilist).datenum;%only available in recent matlab versions
2695            testrecent=1;
2696       end
2697end
2698set(hlist,'String',ListDisplay)
2699
2700%% Look at date of creation
2701ListDisplay=ListDisplay(datnum~=0);
2702datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
2703NbOutputFile=[];
2704if isempty(datnum)
2705    if testrecent
2706        message='no civ result created yet';
2707    else
2708        message='';
2709    end
2710else
2711    [first,indfirst]=min(datnum);
2712    [last,indlast]=max(datnum);
2713    NbOutputFile_str='?';
2714    NbOutputFile=[];
2715    if isfield(StatusData,'NbOutputFile')
2716        NbOutputFile=StatusData.NbOutputFile;
2717        NbOutputFile_str=num2str(NbOutputFile);
2718    end
2719    message={[num2str(numel(datnum)) ' file(s) done over ' NbOutputFile_str] ;['oldest modification:  ' ListDisplay{indfirst} ' : ' datestr(first)];...
2720        ['latest modification:  ' ListDisplay{indlast} ' : ' datestr(last)]};
2721end
2722set(htitlebox,'String', [OutputDir{1};message])
2723
2724%% update the waitbar
2725hwaitbar=findobj(hfig,'tag','waitbar');
2726if ~isempty(NbOutputFile)
2727    BarPosition=get(hwaitbar,'Position');
2728    BarPosition(3)=0.9*numel(datnum)/NbOutputFile;
2729    set(hwaitbar,'Position',BarPosition)
2730end
2731
2732%------------------------------------------------------------------------
2733% --- Executes on selection change in ActionExt.
2734%------------------------------------------------------------------------
2735function ActionExt_Callback(hObject, eventdata, handles)
2736
2737ActionExtList=get(handles.ActionExt,'String');
2738ActionExt=ActionExtList{get(handles.ActionExt,'Value')};
2739ActionList=get(handles.ActionName,'String');
2740ActionName=ActionList{get(handles.ActionName,'Value')};
2741TransformPath='';
2742if ~isempty(get(handles.ActionExt,'UserData'))
2743    TransformPath=get(handles.ActionExt,'UserData');
2744end
2745if strcmp(ActionExt,'.sh')
2746    set(handles.ActionExt,'BackgroundColor',[1 1 0])
2747    ActionFullName=fullfile(get(handles.ActionPath,'String'),[ActionName '.sh']);
2748    if ~exist(ActionFullName,'file')
2749        answer=msgbox_uvmat('INPUT_Y-N','compiled version has not been created: compile now?');
2750        if strcmp(answer,'Yes')
2751            set(handles.ActionExt,'BackgroundColor',[1 1 0])
2752            path_uvmat=fileparts(which('series'));
2753            currentdir=pwd;
2754            cd(get(handles.ActionPath,'String'))% go to the directory of Action
2755            %  addpath(get(handles.TransformPath,'String'))
2756            addpath(path_uvmat)% add the path to uvmat to run the fct 'compile'
2757           % addpath(fullfile(path_uvmat,'transform_field'))% add the path to uvmat to run the fct 'compile'
2758            compile(ActionName,TransformPath)
2759            cd(currentdir)
2760        end       
2761    else
2762        sh_file_info=dir(fullfile(get(handles.ActionPath,'String'),[ActionName '.sh']));
2763        m_file_info=dir(fullfile(get(handles.ActionPath,'String'),[ActionName '.m']));
2764        if isfield(m_file_info,'datenum') && m_file_info.datenum>sh_file_info.datenum
2765            set(handles.ActionExt,'BackgroundColor',[1 1 0])
2766            drawnow
2767            answer=msgbox_uvmat('INPUT_Y-N',[ActionName '.sh needs to be updated: recompile now?']);
2768            if strcmp(answer,'Yes')
2769                path_uvmat=fileparts(which('series'));
2770                currentdir=pwd;
2771                cd(get(handles.ActionPath,'String'))% go to the directory of Action
2772                %  addpath(get(handles.TransformPath,'String'))
2773                addpath(path_uvmat)% add the path to uvmat to run the fct 'compile'
2774                addpath(fullfile(path_uvmat,'transform_field'))% add the path to uvmat to run the fct 'compile'
2775                compile(ActionName,TransformPath)
2776                cd(currentdir)
2777            end
2778        end
2779    end
2780    set(handles.ActionExt,'BackgroundColor',[1 1 1])
2781end
2782
2783
2784
2785
2786function num_NbProcess_Callback(hObject, eventdata, handles)
2787
2788
2789function num_NbSlice_Callback(hObject, eventdata, handles)
2790NbSlice=str2num(get(handles.num_NbSlice,'String'));
2791set(handles.num_NbProcess,'String',num2str(NbSlice))
2792
2793%------------------------------------------------------------------------
2794% --- set the visibility of relevant velocity type menus:
2795function menu=set_veltype_display(Civ,FileType)
2796%------------------------------------------------------------------------
2797if ~exist('FileType','var')
2798    FileType='civx';
2799end
2800switch FileType
2801    case 'civx'
2802        menu={'civ1';'interp1';'filter1';'civ2';'interp2';'filter2'};
2803        if isequal(Civ,0)
2804            imax=0;
2805        elseif isequal(Civ,1) || isequal(Civ,2)
2806            imax=1;
2807        elseif isequal(Civ,3)
2808            imax=3;
2809        elseif isequal(Civ,4) || isequal(Civ,5)
2810            imax=4;
2811        elseif isequal(Civ,6) %patch2
2812            imax=6;
2813        end
2814    case 'civdata'
2815        menu={'civ1';'filter1';'civ2';'filter2'};
2816        if isequal(Civ,0)
2817            imax=0;
2818        elseif isequal(Civ,1) || isequal(Civ,2)
2819            imax=1;
2820        elseif isequal(Civ,3)
2821            imax=2;
2822        elseif isequal(Civ,4) || isequal(Civ,5)
2823            imax=3;
2824        elseif isequal(Civ,6) %patch2
2825            imax=4;
2826        end
2827end
2828menu=menu(1:imax);
Note: See TracBrowser for help on using the repository browser.