source: trunk/src/series.m @ 639

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

introduction of mask on projection: fct mask_proj

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