source: trunk/src/series.m @ 793

Last change on this file since 793 was 793, checked in by sommeria, 10 years ago

correction in series: inputTable

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