source: trunk/src/series.m @ 660

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

various bugs corrected

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