source: trunk/src/series.m @ 758

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

a few bug repairs

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