source: trunk/src/series.m @ 672

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

various bugs corrected

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