source: trunk/src/series.m @ 772

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

manip corrections and cleaning

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