source: trunk/src/series.m @ 760

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

various improvements

File size: 125.0 KB
Line 
1%'series': master function associated to the GUI series.m for analysis field series 
2%------------------------------------------------------------------------
3% function varargout = series(varargin)
4% associated with the GUI series.fig
5%
6%INPUT
7% param: structure with input parameters (link with the GUI uvmat)
8%      .menu_coord_str: string for the TransformName (menu for coordinate transforms)
9%      .menu_coord_val: value for TransformName (menu for coordinate transforms)
10%      .FileName: input file name
11%      .FileName_1: second input file name
12%      .list_field: menu of input fields
13%      .index_fields: chosen index
14%      .civ1=0 or 1, .interp1,  ... : input civ field type
15%
16%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
17%  Copyright Joel Sommeria, 2008, LEGI / CNRS-UJF-INPG, sommeria@coriolis-legi.org.
18%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
19%     This file is part of the toolbox UVMAT.
20%
21%     UVMAT is free software; you can redistribute it and/or modify
22%     it under the terms of the GNU General Public License as published by
23%     the Free Software Foundation; either version 2 of the License, or
24%     (at your option) any later version.
25%
26%     UVMAT is distributed in the hope that it will be useful,
27%     but WITHOUT ANY WARRANTY; without even the implied warranty of
28%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
29%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
30%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
31
32%------------------------------------------------------------------------
33%------------------------------------------------------------------------
34%  I - MAIN FUNCTION series
35%------------------------------------------------------------------------
36%------------------------------------------------------------------------
37function varargout = series(varargin)
38
39% Begin initialization code - DO NOT EDIT
40gui_Singleton = 1;
41gui_State = struct('gui_Name',       mfilename, ...
42                   'gui_Singleton',  gui_Singleton, ...
43                   'gui_OpeningFcn', @series_OpeningFcn, ...
44                   'gui_OutputFcn',  @series_OutputFcn, ...
45                   'gui_LayoutFcn',  [] , ...
46                   'gui_Callback',   []);
47if nargin && ischar(varargin{1})
48    gui_State.gui_Callback = str2func(varargin{1});
49end
50
51if nargout
52    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
53else
54    gui_mainfcn(gui_State, varargin{:});
55end
56% End initialization code - DO NOT EDIT
57
58%--------------------------------------------------------------------------
59% --- Executes just before series is made visible.
60%--------------------------------------------------------------------------
61function series_OpeningFcn(hObject, eventdata, handles,Param)
62
63% Choose default command line output for series
64handles.output = hObject;
65% Update handles structure
66guidata(hObject, handles);
67
68%% initial settings
69% position and  size of the GUI at opening
70set(0,'Unit','points')
71ScreenSize=get(0,'ScreenSize');%size of the current screen, in points (1/72 inch)
72Width=900;% prefered width of the GUI in points (1/72 inch)
73Height=624;% prefered height of the GUI in points (1/72 inch)
74%adjust to screen size (reduced by a min margin)
75RescaleFactor=min((ScreenSize(3)-80)/Width,(ScreenSize(4)-80)/Height);
76if RescaleFactor>1
77    RescaleFactor=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    otherwise
1054        set(handles.FieldName,'Value',1) % set menu to 'image'
1055        set(handles.FieldName,'String',{'image'})
1056        set(handles.Coord_x,'Value',1);
1057        set(handles.Coord_x,'String',{'AX'});
1058        set(handles.Coord_y,'Value',1);
1059        set(handles.Coord_y,'String',{'AY'});
1060end
1061
1062%------------------------------------------------------------------------
1063function num_first_i_Callback(hObject, eventdata, handles)
1064%------------------------------------------------------------------------
1065num_last_i_Callback(hObject, eventdata, handles)
1066
1067%------------------------------------------------------------------------
1068function num_last_i_Callback(hObject, eventdata, handles)
1069%------------------------------------------------------------------------
1070SeriesData=get(handles.series,'UserData');
1071if ~isfield(SeriesData,'Time')
1072    SeriesData.Time{1}=[];
1073end
1074displ_time(handles);
1075
1076%------------------------------------------------------------------------
1077function num_first_j_Callback(hObject, eventdata, handles)
1078%------------------------------------------------------------------------
1079 num_last_j_Callback(hObject, eventdata, handles)
1080
1081%------------------------------------------------------------------------
1082function num_last_j_Callback(hObject, eventdata, handles)
1083%------------------------------------------------------------------------
1084first_j=str2num(get(handles.num_first_j,'String'));
1085last_j=str2num(get(handles.num_last_j,'String'));
1086ref_j=ceil((first_j+last_j)/2);
1087set(handles.num_ref_j,'String', num2str(ref_j))
1088num_ref_j_Callback(hObject, eventdata, handles)
1089SeriesData=get(handles.series,'UserData');
1090if ~isfield(SeriesData,'Time')
1091    SeriesData.Time{1}=[];
1092end
1093displ_time(handles);
1094
1095
1096%------------------------------------------------------------------------
1097% ---- find the times corresponding to the first and last indices of a series
1098function displ_time(handles)
1099%------------------------------------------------------------------------
1100SeriesData=get(handles.series,'UserData');%
1101PairString=get(handles.PairString,'Data');
1102ref_i_1=str2num(get(handles.num_first_i,'String'));%first reference index
1103ref_i_2=str2num(get(handles.num_last_i,'String'));%last reference index
1104ref_j_1=[];ref_j_2=[];
1105if strcmp(get(handles.num_first_j,'Visible'),'on')
1106ref_j_1=str2num(get(handles.num_first_j,'String'));
1107ref_j_2=str2num(get(handles.num_last_j,'String'));
1108end
1109[i1_1,i2_1,j1_1,j2_1] = get_file_index(ref_i_1,ref_j_1,PairString);
1110[i1_2,i2_2,j1_2,j2_2] = get_file_index(ref_i_2,ref_j_2,PairString);
1111TimeTable=get(handles.TimeTable,'Data');
1112
1113%Pairs=get(handles.PairString,'Data');
1114for iview=1:size(TimeTable,1)
1115    if size(SeriesData.Time,1)<iview
1116        break
1117    end
1118    TimeTable{iview,2}=[];
1119    TimeTable{iview,3}=[];
1120    if size(SeriesData.Time{iview},1)>=i2_2+1 && (isempty(ref_j_1)||size(SeriesData.Time{iview},2)>=j2_2+1)
1121        if isempty(ref_j_1)
1122            time_first=(SeriesData.Time{iview}(i1_1+1,2)+SeriesData.Time{iview}(i2_1+1,2))/2;
1123            time_last=(SeriesData.Time{iview}(i1_2+1,2)+SeriesData.Time{iview}(i2_2+1,2))/2;
1124        else
1125            time_first=(SeriesData.Time{iview}(i1_1+1,j1_1+1)+SeriesData.Time{iview}(i2_1+1,j2_1+1))/2;
1126            time_last=(SeriesData.Time{iview}(i1_2+1,j1_2+1)+SeriesData.Time{iview}(i2_2+1,j2_1+1))/2;
1127        end
1128        TimeTable{iview,2}=time_first; %TODO: take into account pairs
1129        TimeTable{iview,3}=time_last; %TODO: take into account pairs
1130    end
1131end
1132set(handles.TimeTable,'Data',TimeTable)
1133
1134%% set the waitbar position with respect to the min and max in the series
1135MinIndex_i=min(get(handles.MinIndex_i,'Data'));
1136MaxIndex_i=max(get(handles.MaxIndex_i,'Data'));
1137pos_first=(ref_i_1-MinIndex_i)/(MaxIndex_i-MinIndex_i+1);
1138pos_last=(ref_i_2-MinIndex_i+1)/(MaxIndex_i-MinIndex_i+1);
1139if isempty(pos_first), pos_first=0; end
1140if isempty(pos_last), pos_last=1; end
1141Position=get(handles.Waitbar,'Position');% position of the waitbar:= [ x,y, width, height]
1142Position_status=get(handles.FileStatus,'Position');
1143Position(1)=Position_status(1)+Position_status(3)*pos_first;
1144Position(3)=max(Position_status(3)*(pos_last-pos_first),0.001);% width must remain positive
1145set(handles.Waitbar,'Position',Position)
1146update_waitbar(handles.Waitbar,0)
1147
1148%------------------------------------------------------------------------
1149% --- Executes when selected cell(s) is changed in PairString.
1150function PairString_CellSelectionCallback(hObject, eventdata, handles)
1151%------------------------------------------------------------------------   
1152if numel(eventdata.Indices)>=1
1153set(handles.ListView,'Value',eventdata.Indices(1))% detect the selected raw index
1154ListView_Callback ([],[],handles) % update the list of available pairs
1155end
1156
1157%------------------------------------------------------------------------
1158%------------------------------------------------------------------------
1159%  III - FUNCTIONS ASSOCIATED TO THE FRAME SET PAIRS
1160%------------------------------------------------------------------------
1161%------------------------------------------------------------------------
1162% --- Executes on selection change in ListView.
1163function ListView_Callback(hObject, eventdata, handles)
1164%------------------------------------------------------------------------   
1165SeriesData=get(handles.series,'UserData');
1166i2_series=[];
1167j2_series=[];
1168iview=get(handles.ListView,'Value');
1169if ~isempty(SeriesData.i2_series{iview})
1170    i2_series=SeriesData.i2_series{iview};
1171end
1172if ~isempty(SeriesData.j2_series{iview})
1173    j2_series=SeriesData.j2_series{iview};
1174end
1175update_mode(handles,SeriesData.i1_series{iview},SeriesData.i2_series{iview},...
1176    SeriesData.j1_series{iview},SeriesData.j2_series{iview},SeriesData.Time{iview})
1177
1178%------------------------------------------------------------------------
1179% --- Executes on button press in mode.
1180function mode_Callback(hObject, eventdata, handles)
1181%------------------------------------------------------------------------       
1182SeriesData=get(handles.series,'UserData');
1183iview=get(handles.ListView,'Value');
1184mode_list=get(handles.mode,'String');
1185mode=mode_list{get(handles.mode,'Value')};
1186if isequal(mode,'bursts')
1187    enable_i(handles,'On')
1188    enable_j(handles,'Off') %do not display j index scanning in burst mode (j is fixed by the burst choice)
1189else
1190    enable_i(handles,'On')
1191    enable_j(handles,'Off')
1192end
1193fill_ListPair(handles,SeriesData.i1_series{iview},SeriesData.i2_series{iview},...
1194    SeriesData.j1_series{iview},SeriesData.j2_series{iview},SeriesData.Time{iview})
1195ListPairs_Callback([],[],handles)
1196
1197%-------------------------------------------------------------
1198% --- Executes on selection in ListPairs.
1199function ListPairs_Callback(hObject,eventdata,handles)
1200%------------------------------------------------------------
1201list_pair=get(handles.ListPairs,'String');%get the menu of image pairs
1202if isempty(list_pair)
1203    string='';
1204else
1205    string=list_pair{get(handles.ListPairs,'Value')};
1206    string=regexprep(string,',.*','');%removes time indication (after ',')
1207end
1208PairString=get(handles.PairString,'Data');
1209iview=get(handles.ListView,'Value');
1210PairString{iview,1}=string;
1211% report the selected pair string to the table PairString
1212set(handles.PairString,'Data',PairString)
1213
1214%------------------------------------------------------------------------
1215function num_ref_i_Callback(hObject, eventdata, handles)
1216%------------------------------------------------------------------------
1217mode_list=get(handles.mode,'String');
1218mode=mode_list{get(handles.mode,'Value')};
1219SeriesData=get(handles.series,'UserData');
1220iview=get(handles.ListView,'Value');
1221fill_ListPair(handles,SeriesData.i1_series{iview},SeriesData.i2_series{iview},...
1222    SeriesData.j1_series{iview},SeriesData.j2_series{iview},SeriesData.Time{iview});% update the menu of pairs depending on the available netcdf files
1223ListPairs_Callback([],[],handles)
1224
1225%------------------------------------------------------------------------
1226function num_ref_j_Callback(hObject, eventdata, handles)
1227%------------------------------------------------------------------------
1228num_ref_i_Callback(hObject, eventdata, handles)
1229
1230%------------------------------------------------------------------------
1231function update_mode(handles,i1_series,i2_series,j1_series,j2_series,time)
1232%------------------------------------------------------------------------   
1233% check_burst=0;
1234if isempty(j2_series)% no j pair
1235    if isempty(i2_series)
1236        set(handles.mode,'Value',1)
1237        set(handles.mode,'String',{''})% no pair menu to display
1238    else   
1239        set(handles.mode,'Value',1)
1240        set(handles.mode,'String',{'series(Di)'}) % pair menu with only option Di
1241    end
1242else %existence of j pairs
1243    pair_max=squeeze(max(i1_series,[],1)); %max on pair index
1244    j_max=max(pair_max,[],1);
1245    MaxIndex_i=max(find(j_max))-1;% max ref index i
1246    MinIndex_i=min(find(j_max))-1;% min ref index i
1247    i_max=max(pair_max,[],2);
1248    MaxIndex_j=max(find(i_max))-1;% max ref index i
1249    MinIndex_j=min(find(i_max))-1;% min ref index i
1250    if MaxIndex_j==MinIndex_j
1251        set(handles.mode,'Value',1);
1252        set(handles.mode,'String',{'bursts'})
1253%         check_burst=1;
1254    elseif MaxIndex_i==MinIndex_i
1255        set(handles.mode,'Value',1);
1256        set(handles.mode,'String',{'series(Dj)'})
1257    else
1258        set(handles.mode,'String',{'bursts';'series(Dj)'})
1259        if (MaxIndex_j-MinIndex_j)>10
1260            set(handles.mode,'Value',2);%set mode to series(Dj) if more than 10 j values
1261        else
1262            set(handles.mode,'Value',1);
1263%             check_burst=1;
1264        end
1265    end
1266end
1267fill_ListPair(handles,i1_series,i2_series,j1_series,j2_series,time)
1268ListPairs_Callback([],[],handles)
1269
1270%--------------------------------------------------------------
1271% determine the menu for pairstring depending on existing netcdf files
1272% with the reference indices num_ref_i and num_ref_j
1273%----------------------------------------------------------------
1274function fill_ListPair(handles,i1_series,i2_series,j1_series,j2_series,time)
1275
1276mode_list=get(handles.mode,'String');
1277mode=mode_list{get(handles.mode,'Value')};
1278ref_i=str2num(get(handles.num_ref_i,'String'));
1279if isempty(ref_i)
1280    ref_i=1;
1281end
1282if strcmp(get(handles.num_ref_j,'Visible'),'on')
1283    ref_j=str2num(get(handles.num_ref_j,'String'));
1284    if isempty(ref_j)
1285        ref_j=1;
1286    end
1287else
1288    ref_j=1;
1289end
1290TimeUnit=get(handles.TimeUnit,'String');
1291if length(TimeUnit)>=1
1292    dtunit=['m' TimeUnit];
1293else
1294    dtunit='e-03';
1295end
1296
1297displ_pair={};
1298if strcmp(mode,'series(Di)')
1299    if isempty(i2_series)
1300        msgbox_uvmat('ERROR','no i1-i2 pair available')
1301        return
1302    end
1303    diff_i=i2_series-i1_series;
1304    min_diff=min(diff_i(diff_i>0));
1305    max_diff=max(diff_i(diff_i>0));
1306    for ipair=min_diff:max_diff
1307        if numel(diff_i(diff_i==ipair))>0
1308            pair_string=['Di= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
1309            if ~isempty(time)
1310                if ref_i<=floor(ipair/2)
1311                    ref_i=floor(ipair/2)+1;% shift ref_i to get the first pair
1312                end
1313                Dt=time(ref_i+ceil(ipair/2),ref_j)-time(ref_i-floor(ipair/2),ref_j);
1314                pair_string=[pair_string ', Dt=' num2str(Dt) ' ' dtunit];
1315            end
1316            displ_pair=[displ_pair;{pair_string}];
1317        end
1318    end
1319    if ~isempty(displ_pair)
1320        displ_pair=[displ_pair;{'Di=*|*'}];
1321    end
1322elseif strcmp(mode,'series(Dj)')
1323    if isempty(j2_series)
1324        msgbox_uvmat('ERROR','no j1-j2 pair available')
1325        return
1326    end
1327    diff_j=j2_series-j1_series;
1328    min_diff=min(diff_j(diff_j>0));
1329    max_diff=max(diff_j(diff_j>0));
1330    for ipair=min_diff:max_diff
1331        if numel(diff_j(diff_j==ipair))>0
1332            pair_string=['Dj= ' num2str(-floor(ipair/2)) '|' num2str(ceil(ipair/2)) ];
1333            if ~isempty(time)
1334                if ref_j<=floor(ipair/2)
1335                    ref_j=floor(ipair/2)+1;% shift ref_i to get the first pair
1336                end
1337                Dt=time(ref_i,ref_j+ceil(ipair/2))-time(ref_i,ref_j-floor(ipair/2));
1338                pair_string=[pair_string ', Dt=' num2str(Dt) ' ' dtunit];
1339            end
1340            displ_pair=[displ_pair;{pair_string}];
1341        end
1342    end
1343    if ~isempty(displ_pair)
1344        displ_pair=[displ_pair;{'Dj=*|*'}];
1345    end
1346elseif strcmp(mode,'bursts')
1347    if isempty(j2_series)
1348        msgbox_uvmat('ERROR','no j1-j2 pair available')
1349        return
1350    end
1351    diff_j=j2_series-j1_series;
1352    min_j1=min(j1_series(j1_series>0));
1353    max_j1=max(j1_series(j1_series>0));
1354    min_j2=min(j2_series(j2_series>0));
1355    max_j2=max(j2_series(j2_series>0));
1356    for pair1=min_j1:min(max_j1,min_j1+20)
1357        for pair2=min_j2:min(max_j2,min_j2+20)
1358        if numel(j1_series(j1_series==pair1))>0 && numel(j2_series(j2_series==pair2))>0
1359            displ_pair=[displ_pair;{['j= ' num2str(pair1) '-' num2str(pair2)]}];
1360        end
1361        end
1362    end
1363    if ~isempty(displ_pair)
1364        displ_pair=[displ_pair;{'j=*-*'}];
1365    end
1366end
1367set(handles.num_ref_i,'String',num2str(ref_i)) % update ref_i and ref_j
1368set(handles.num_ref_j,'String',num2str(ref_j))
1369
1370%% display list of pairstring
1371displ_pair_list=get(handles.ListPairs,'String');
1372NewVal=[];
1373if ~isempty(displ_pair_list)
1374Val=get(handles.ListPairs,'Value');
1375NewVal=find(strcmp(displ_pair_list{Val},displ_pair),1);% look at the previous display in the new menu displ_pï¿œir
1376end
1377if ~isempty(NewVal)
1378    set(handles.ListPairs,'Value',NewVal)
1379else
1380    set(handles.ListPairs,'Value',1)
1381end
1382set(handles.ListPairs,'String',displ_pair)
1383
1384%-------------------------------------
1385function enable_i(handles,state)
1386set(handles.i_txt,'Visible',state)
1387set(handles.num_first_i,'Visible',state)
1388set(handles.num_last_i,'Visible',state)
1389set(handles.num_incr_i,'Visible',state)
1390set(handles.num_ref_i,'Visible',state)
1391set(handles.ref_i_text,'Visible',state)
1392
1393%-----------------------------------
1394function enable_j(handles,state)
1395set(handles.j_txt,'Visible',state)
1396set(handles.num_first_j,'Visible',state)
1397set(handles.num_last_j,'Visible',state)
1398set(handles.num_incr_j,'Visible',state)
1399set(handles.num_ref_j,'Visible',state)
1400set(handles.ref_j_text,'Visible',state)
1401set(handles.MinIndex_j,'Visible',state)
1402set(handles.MaxIndex_j,'Visible',state)
1403
1404
1405%%%%%%%%%%%%%%%%%%%%
1406%%  MAIN ActionName FUNCTIONS
1407%%%%%%%%%%%%%%%%%%%%
1408%------------------------------------------------------------------------
1409% --- Executes on button press in RUN.
1410%------------------------------------------------------------------------
1411function RUN_Callback(hObject, eventdata, handles)
1412
1413%% settings of the button RUN
1414set(handles.RUN,'BusyAction','queue');% activation of STOP button will set BusyAction to 'cancel'
1415set(handles.RUN, 'Enable','Off')% avoid further RUN action until the current one is finished
1416set(handles.RUN,'BackgroundColor',[1 1 0])%show activation of RUN by yellow color
1417drawnow
1418set(handles.status,'Value',0)% desable status display if relevant
1419status_Callback(hObject, eventdata, handles)
1420
1421%% read the data on the GUI series
1422Param=read_GUI_series(handles);%displayed parameters
1423SeriesData=get(handles.series,'UserData');%hidden parameters
1424
1425%% create the output data directory if needed
1426if isfield(Param,'OutputSubDir')
1427    SubDirOut=[get(handles.OutputSubDir,'String') Param.OutputDirExt];
1428    SubDirOutNew=SubDirOut;
1429    detect=exist(fullfile(Param.InputTable{1,1},SubDirOutNew),'dir');% test if  the dir  already exist
1430    check_create=1; %need to create the result directory by default
1431    while detect
1432        answer=msgbox_uvmat('INPUT_Y-N',['use existing ouput directory: ' fullfile(Param.InputTable{1,1},SubDirOutNew) ', possibly delete previous data']);
1433        if strcmp(answer,'Cancel')
1434            errormsg='Cancel';
1435            return
1436        elseif strcmp(answer,'Yes')
1437            detect=0;
1438            check_create=0;
1439        else
1440            r=regexp(SubDirOutNew,'(?<root>.*\D)(?<num1>\d+)$','names');%detect whether name ends by a number
1441            if isempty(r)
1442                r(1).root=[SubDirOutNew '_'];
1443                r(1).num1='0';
1444            end
1445            SubDirOutNew=[r(1).root num2str(str2num(r(1).num1)+1)];%increment the index by 1 or put 1
1446            detect=exist(fullfile(Param.InputTable{1,1},SubDirOutNew),'dir');% test if  the dir  already exists
1447            check_create=1;
1448        end
1449    end
1450    Param.OutputDirExt=regexprep(SubDirOutNew,Param.OutputSubDir,'');
1451    Param.OutputRootFile=Param.InputTable{1,3};% the first sorted RootFile taken for output
1452    set(handles.OutputDirExt,'String',Param.OutputDirExt)
1453    OutputDir=fullfile(Param.InputTable{1,1},[Param.OutputSubDir Param.OutputDirExt]);% full name (with path) of output directory
1454    if check_create    % create output directory if it does not exist
1455        [tild,msg1]=mkdir(OutputDir);
1456        if ~strcmp(msg1,'')
1457            msgbox_uvmat('ERROR',['cannot create ' OutputDir ': ' msg1]);%error message for directory creation
1458            return
1459        end
1460        [success,msg] = fileattrib(OutputDir,'+w','g','s');% allow writing access for the group of users, recursively in the folder 
1461        if success==0
1462            msgbox_uvmat('WARNING',{['unable to set group write access to ' OutputDir ':']; msg1});%error message for directory creation
1463            return
1464        end
1465    end
1466    OutputNomType=nomtype2pair(Param.InputTable{1,4});% nomenclature for output files
1467    DirXml=fullfile(OutputDir,'0_XML');
1468    if ~exist(DirXml,'dir')
1469        [tild,msg1]=mkdir(DirXml);
1470        if ~strcmp(msg1,'')
1471            msgbox_uvmat('ERROR',['cannot create ' DirXml ': ' msg1]);%error message for directory creation
1472            return
1473        end
1474                [success,msg] = fileattrib(DirXml,'+w','g','s');% allow writing access for the group of users, recursively in the folder 
1475        if success==0
1476            msgbox_uvmat('WARNING',{['unable to set group write access to ' DirXml ':']; msg1});%error message for directory creation
1477            return
1478        end
1479    end
1480end
1481
1482%% select the Action mode, 'local', 'background' or 'cluster' (if available)
1483RunMode='local';%default (needed for first opening of the GUI series)
1484if isfield(Param.Action,'RunMode')
1485    RunMode=Param.Action.RunMode;
1486end
1487ActionExt='.m';%default
1488if isfield(Param.Action,'ActionExt')
1489    ActionExt=Param.Action.ActionExt;% '.m' or '.sh' (compiled)
1490end
1491ActionName=Param.Action.ActionName;
1492ActionPath=Param.Action.ActionPath;
1493path_series=fileparts(which('series'));
1494
1495%% create the Action fct handle if RunMode option = 'local'
1496if strcmp(RunMode,'local')
1497    if ~isequal(ActionPath,path_series)
1498        eval(['spath=which(''' ActionName ''');']) %spath = current path of the selected function ACTION
1499        if ~exist(ActionPath,'dir')
1500            msgbox_uvmat('ERROR',['The prescribed function path ' ActionPath ' does not exist']);
1501            return
1502        end
1503        if ~isequal(spath,ActionPath)
1504            addpath(ActionPath)% add the prescribed path if not the current one
1505        end
1506    end
1507    eval(['h_fun=@' ActionName ';'])%create a function handle for ACTION
1508    if ~isequal(ActionPath,path_series)
1509        rmpath(ActionPath)% add the prescribed path if not the current one
1510    end
1511end
1512
1513%% Get RunTime code from the file PARAM.xml (needed to run compiled functions)
1514errormsg='';%default error message
1515xmlfile=fullfile(path_series,'PARAM.xml');
1516test_batch=0;%default: ,no batch mode available
1517if ~exist(xmlfile,'file')
1518    [success,message]=copyfile(fullfile(path_series,'PARAM.xml.default'),xmlfile);
1519end
1520RunTime='';
1521if strcmp(ActionExt,'.sh')
1522    if exist(xmlfile,'file')
1523        s=xml2struct(xmlfile);
1524        if strcmp(RunMode,'cluster_oar') && isfield(s,'BatchParam')
1525            if isfield(s.BatchParam,'RunTime')
1526                RunTime=s.BatchParam.RunTime;
1527            end
1528            if isfield(s.BatchParam,'NbCore')
1529                NbCore=s.BatchParam.NbCore;
1530            end
1531        elseif (strcmp(RunMode,'background')||strcmp(RunMode,'local')) && isfield(s,'RunParam')
1532            if isfield(s.RunParam,'RunTime')
1533                RunTime=s.RunParam.RunTime;
1534            end
1535            if isfield(s.RunParam,'NbCore')
1536                NbCore=s.RunParam.NbCore;
1537            end
1538        end
1539    end
1540    if isempty(RunTime) && strcmp(RunMode,'cluster_oar')
1541        msgbox_uvmat('ERROR','RunTime name not found in PARAM.xml, compiled version .sh cannot run on cluster')
1542        return
1543    end
1544end
1545
1546%% set nbre of cluster cores and processes
1547switch RunMode
1548    case {'local','background'}
1549        NbCore=1;% no need to split the calculation
1550    case 'cluster_oar'
1551        if strcmp(Param.Action.ActionExt,'.m')% case of Matlab function (uncompiled)
1552            NbCore=1;% one core used only (limitation of Matlab licences)
1553            msgbox_uvmat('WARNING','Number of cores =1: select the compiled version civ_matlab.sh for multi-core processing');
1554            extra_oar='';
1555        else
1556            answer=inputdlg({'Number of cores (max 36)','extra oar options'},'oarsub parameter',1,{'12',''});
1557            NbCore=str2double(answer{1});
1558            extra_oar=answer{2};
1559        end
1560end
1561if ~isfield(Param.IndexRange,'NbSlice')
1562    Param.IndexRange.NbSlice=[];
1563end
1564if isempty(Param.IndexRange.NbSlice)
1565    NbProcess=NbCore;% choose one process per core
1566else
1567    NbProcess=Param.IndexRange.NbSlice;% the nbre of run processes is equal to the number of slices
1568    NbCore=min(NbCore,NbProcess);% at least one process per core
1569end
1570       
1571%% get the set of reference field indices
1572first_i=1;
1573last_i=1;
1574incr_i=1;
1575first_j=1;
1576last_j=1;
1577incr_j=1;
1578if isfield(Param.IndexRange,'first_i')
1579    first_i=Param.IndexRange.first_i;
1580    incr_i=Param.IndexRange.incr_i;
1581    last_i=Param.IndexRange.last_i;
1582end
1583if isfield(Param.IndexRange,'first_j')
1584    first_j=Param.IndexRange.first_j;
1585    last_j=Param.IndexRange.last_j;
1586    incr_j=Param.IndexRange.incr_j;
1587end
1588if last_i < first_i || last_j < first_j
1589    msgbox_uvmat('ERROR', 'series/Run_Callback:last field index must be larger or equal to the first one')
1590    set(handles.RUN, 'Enable','On'),
1591    set(handles.RUN,'BackgroundColor',[1 0 0])
1592    return
1593end
1594%incr_i must be defined, =1 by default, if NbSlice is active
1595if isempty(incr_i)&& ~isempty(Param.IndexRange.NbSlice)
1596    incr_i=1;
1597    set(handles.num_incr_i,'String','1')
1598end
1599if isempty(incr_i)
1600    if isempty(incr_j)
1601        [ref_j,ref_i]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1602        ref_j=ref_j(ref_j>=first_j & ref_j<=last_j);
1603        ref_i=ref_i(ref_i>=first_i & ref_i<=last_i);
1604        ref_j=ref_j-1;
1605        ref_i=ref_i-1;
1606    else
1607        ref_j=first_j:incr_j:last_j;
1608        [tild,ref_i]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1609        ref_i=ref_i-1;
1610        ref_i=ref_i(ref_i>=first_i & ref_i<=last_i);
1611    end
1612else
1613    ref_i=first_i:incr_i:last_i;
1614    if isempty(incr_j)
1615    [ref_j,tild]=find(squeeze(SeriesData.i1_series{1}(1,:,:)));
1616    ref_j=ref_j-1;
1617    ref_j=ref_j(ref_j>=first_j & ref_j<=last_j);
1618    else
1619        ref_j=first_j:incr_j:last_j;
1620    end
1621end
1622BlockLength=ceil(numel(ref_i)/NbProcess);
1623nbfield_j=numel(ref_j);
1624
1625%% record nbre of output files and starting time for computation for status
1626StatusData=get(handles.status,'UserData');
1627if isfield(StatusData,'OutputFileMode')
1628    switch StatusData.OutputFileMode
1629        case 'NbInput'
1630            StatusData.NbOutputFile=numel(ref_i)*nbfield_j;
1631        case 'NbInput_i'
1632            StatusData.NbOutputFile=numel(ref_i);
1633        case 'NbSlice'   
1634            StatusData.NbOutputFile=str2num(get(handles.num_NbSlice,'String'));
1635    end
1636end
1637StatusData.TimeStart=now;
1638set(handles.status,'UserData',StatusData)
1639
1640%% direct processing on the current Matlab session
1641if strcmp (RunMode,'local')
1642    for iprocess=1:NbProcess
1643        if isempty(Param.IndexRange.NbSlice)
1644            %Param.IndexRange.first_i=first_i+(iprocess-1)*BlockLength*incr_i;
1645            Param.IndexRange.first_i=ref_i(1+(iprocess-1)*BlockLength);
1646            if Param.IndexRange.first_i>last_i
1647                break
1648            end
1649            Param.IndexRange.last_i=min(ref_i(iprocess*BlockLength),last_i);
1650            %Param.IndexRange.last_i=min(first_i+(iprocess)*BlockLength*incr_i-1,last_i);
1651        else %multislices (then incr_i is not empty)
1652             Param.IndexRange.first_i= first_i+incr_i*(iprocess-1);
1653             Param.IndexRange.incr_i=incr_i*Param.IndexRange.NbSlice;
1654        end
1655        if isfield(Param,'OutputSubDir')
1656        t=struct2xml(Param);
1657        t=set(t,1,'name','Series');
1658        filexml=fullfile_uvmat(DirXml,'',Param.InputTable{1,3},'.xml',OutputNomType,...
1659            Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1660        save(t,filexml);
1661        end
1662        switch ActionExt
1663            case '.m'
1664                h_fun(Param);
1665            case '.sh'
1666                switch computer
1667                    case {'PCWIN','PCWIN64'} %Windows system
1668                        filexml=regexprep(filexml,'\\','\\\\');% add '\' so that '\' are left as characters
1669                        system([fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml]);% TODO: adapt to DOS system
1670                    case {'GLNX86','GLNXA64','MACI64'}%Linux  system
1671                        system([fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml]);
1672                end
1673        end
1674    end
1675elseif strcmp(get(handles.OutputDirExt,'Visible'),'off')
1676    msgbox_uvmat('ERROR',['no output file for Action ' ActionName ', use run mode = local']);% a output dir is needed for background option
1677    return
1678else
1679    %% processing on a different session of the same computer (background) or cluster, create executable files
1680    batch_file_list=cell(NbProcess,1);% initiate the list of executable files
1681    DirBat=fullfile(OutputDir,'0_EXE');
1682    switch computer
1683        case {'PCWIN','PCWIN64'} %Windows system
1684            ExeExt='.bat';
1685        case {'GLNX86','GLNXA64','MACI64'}%Linux  system
1686           ExeExt='.sh';
1687    end
1688    %create subdirectory for executable files
1689    if ~exist(DirBat,'dir')
1690        [tild,msg1]=mkdir(DirBat);
1691        if ~strcmp(msg1,'')
1692            msgbox_uvmat('ERROR',['cannot create ' DirBat ': ' msg1]);%error message for directory creation
1693            return
1694        end
1695    end
1696    %create subdirectory for log files
1697    DirLog=fullfile(OutputDir,'0_LOG');
1698    if ~exist(DirLog,'dir')
1699        [tild,msg1]=mkdir(DirLog);
1700        if ~strcmp(msg1,'')
1701            msgbox_uvmat('ERROR',['cannot create ' DirLog ': ' msg1]);%error message for directory creation
1702            return
1703        end
1704    end
1705    for iprocess=1:NbProcess
1706        if isempty(Param.IndexRange.NbSlice)% process by blocks of i index
1707            Param.IndexRange.first_i=first_i+(iprocess-1)*BlockLength*incr_i;
1708            if Param.IndexRange.first_i>last_i
1709                NbProcess=iprocess-1;
1710                break% leave the loop, we are at the end of the calculation
1711            end
1712            Param.IndexRange.last_i=min(last_i,first_i+(iprocess)*BlockLength*incr_i-1);
1713        else% process by slices of i index if NbSlice is defined, computation in a single process if NbSlice =1
1714            Param.IndexRange.first_i= first_i+iprocess-1;
1715            Param.IndexRange.incr_i=incr_i*Param.IndexRange.NbSlice;
1716        end
1717       
1718        % create, fill and save the xml parameter file
1719        t=struct2xml(Param);
1720        t=set(t,1,'name','Series');
1721        filexml=fullfile_uvmat(DirXml,'',Param.InputTable{1,3},'.xml',OutputNomType,...
1722            Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1723        save(t,filexml);% save the parameter file
1724       
1725        %create the executable file
1726         filebat=fullfile_uvmat(DirBat,'',Param.InputTable{1,3},ExeExt,OutputNomType,...
1727           Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1728        batch_file_list{iprocess}=filebat;
1729        [fid,message]=fopen(filebat,'w');% create the executable file
1730        if isequal(fid,-1)
1731            msgbox_uvmat('ERROR', ['creation of .bat file: ' message]);
1732            return
1733        end
1734       
1735        % set the log file name
1736        filelog=fullfile_uvmat(DirLog,'',Param.InputTable{1,3},'.log',OutputNomType,...
1737            Param.IndexRange.first_i,Param.IndexRange.last_i,first_j,last_j);
1738       
1739        % fill and save the executable file
1740        switch ActionExt
1741            case '.m'% Matlab function
1742                switch computer
1743                    case {'GLNX86','GLNXA64','MACI64'}
1744                        cmd=[...
1745                            '#!/bin/bash \n'...
1746                            '. /etc/sysprofile \n'...
1747                            'matlab -nodisplay -nosplash -nojvm -logfile ''' filelog ''' <<END_MATLAB \n'...
1748                            'addpath(''' path_series '''); \n'...
1749                            'addpath(''' Param.Action.ActionPath '''); \n'...
1750                            '' Param.Action.ActionName  '( ''' filexml '''); \n'...
1751                            'exit \n'...
1752                            'END_MATLAB \n'];
1753                        fprintf(fid,cmd);%fill the executable file with the  char string cmd
1754                        fclose(fid);% close the executable file
1755                        system(['chmod +x ' filebat]);% set the file to executable
1756                    case {'PCWIN','PCWIN64'}
1757                        text_matlabscript=['matlab -automation -logfile ' regexprep(filelog,'\\','\\\\')...
1758                            ' -r "addpath(''' regexprep(path_series,'\\','\\\\') ''');'...
1759                            'addpath(''' regexprep(Param.Action.ActionPath,'\\','\\\\') ''');'...
1760                            '' Param.Action.ActionName  '( ''' regexprep(filexml,'\\','\\\\') ''');exit"'];
1761                        fprintf(fid,text_matlabscript);%fill the executable file with the  char string cmd
1762                        fclose(fid);% close the executable file
1763                end
1764            case '.sh' % compiled Matlab function
1765                switch computer
1766                    case {'GLNX86','GLNXA64','MACI64'}
1767                        cmd=['#!/bin/bash \n '...
1768                            '#$ -cwd \n '...
1769                            'hostname && date \n '...
1770                            'umask 002 \n'...
1771                            fullfile(ActionPath,[ActionName '.sh']) ' ' RunTime ' ' filexml];%allow writting access to created files for user group
1772                        fprintf(fid,cmd);%fill the executable file with the  char string cmd
1773                        fclose(fid);% close the executable file
1774                        system(['chmod +x ' filebat]);% set the file to executable
1775                       
1776                    case {'PCWIN','PCWIN64'}    %       TODO: adapt to Windows system
1777                        %                                 cmd=['matlab -automation -logfile ' regexprep(filelog,'\\','\\\\')...
1778                        %                                     ' -r "addpath(''' regexprep(path_series,'\\','\\\\') ''');'...
1779                        %                                     'addpath(''' regexprep(Param.Action.ActionPath,'\\','\\\\') ''');'...
1780                        %                                     '' Param.Action.ActionName  '( ''' regexprep(filexml,'\\','\\\\') ''');exit"'];
1781                        fprintf(fid,cmd);
1782                        fclose(fid);
1783                        %                               dos([filebat ' &']);
1784                end
1785        end
1786    end
1787end
1788
1789%% launch the executable files for background or cluster processing
1790switch RunMode
1791    case 'background'
1792        for iprocess=1:NbProcess
1793            system([batch_file_list{iprocess} ' &'])% directly execute the command file for each process
1794            msgbox_uvmat('CONFIRMATION',[ActionName 'launched in background: press STATUS to see results'])
1795        end
1796    case 'cluster_oar' % option 'oar-parexec' used
1797        %create subdirectory for oar command and log files
1798        DirOAR=fullfile(OutputDir,'0_OAR');
1799        if exist(DirOAR,'dir')% delete the content of the dir 0_OAR to allow new input
1800            curdir=pwd;
1801            cd(DirOAR)
1802            delete('*')
1803            cd(curdir)
1804        else
1805            [tild,msg1]=mkdir(DirOAR);
1806            if ~strcmp(msg1,'')
1807                msgbox_uvmat('ERROR',['cannot create ' DirOAR ': ' msg1]);%error message for directory creation
1808                return
1809            end
1810        end
1811        max_walltime=3600*12; % 12h max total calculation
1812        walltime_onejob=600;%seconds, max estimated time for asingle file index value
1813        filename_joblist=fullfile(DirOAR,'job_list.txt');%create name of the global executable file
1814        fid=fopen(filename_joblist,'w');
1815        for p=1:length(batch_file_list)
1816            fprintf(fid,[batch_file_list{p} '\n']);% list of exe files
1817        end
1818        fclose(fid);
1819        system(['chmod +x ' filename_joblist]);% set the file to executable
1820        oar_command=['oarsub -n CIVX '...
1821            '-t idempotent --checkpoint ' num2str(walltime_onejob+60) ' '...
1822            '-l /core=' num2str(NbCore) ','...
1823            'walltime=' datestr(min(1.05*walltime_onejob/86400*max(NbProcess*BlockLength*nbfield_j,NbCore)/NbCore,max_walltime/86400),13) ' '...
1824            '-E ' regexprep(filename_joblist,'\.txt\>','.stderr') ' '...
1825            '-O ' regexprep(filename_joblist,'\.txt\>','.stdout') ' '...
1826            extra_oar ' '...
1827            '"oar-parexec -s -f ' filename_joblist ' '...
1828            '-l ' filename_joblist '.log"\n'];
1829        filename_oarcommand=fullfile(DirOAR,'oar_command');
1830        fid=fopen(filename_oarcommand,'w');
1831        fprintf(fid,oar_command);
1832        fclose(fid);
1833        fprintf(oar_command);% display in command line
1834        system(oar_command); 
1835        msgbox_uvmat('CONFIRMATION',[ActionName ' launched in cluster: press STATUS to see results'])
1836end
1837
1838%% reset the GUI series
1839update_waitbar(handles.Waitbar,1); % put the waitbar to end position to indicate launching is finished
1840set(handles.RUN, 'Enable','On')
1841set(handles.RUN,'BackgroundColor',[1 0 0])
1842set(handles.RUN, 'Value',0)
1843
1844%------------------------------------------------------------------------
1845function STOP_Callback(hObject, eventdata, handles)
1846%------------------------------------------------------------------------
1847set(handles.RUN, 'BusyAction','cancel')
1848set(handles.RUN,'BackgroundColor',[1 0 0])
1849set(handles.RUN,'enable','on')
1850set(handles.RUN, 'Value',0)
1851
1852
1853%------------------------------------------------------------------------
1854% --- read parameters from the GUI series
1855%------------------------------------------------------------------------
1856function Param=read_GUI_series(handles)
1857
1858%% read raw parameters from the GUI series
1859Param=read_GUI(handles.series);
1860
1861%% clean the output structure by removing unused information
1862if isfield(Param,'Pairs')
1863    Param=rmfield(Param,'Pairs'); %info Pairs not needed for output
1864end
1865Param.IndexRange=rmfield(Param.IndexRange,'TimeTable');
1866empty_line=false(size(Param.InputTable,1),1);
1867for iline=1:size(Param.InputTable,1)
1868    empty_line(iline)=isempty(cell2mat(Param.InputTable(iline,1:3)));
1869end
1870Param.InputTable(empty_line,:)=[];
1871
1872%------------------------------------------------------------------------
1873% --- Executes on selection change in ActionName.
1874function ActionName_Callback(hObject, eventdata, handles)
1875%------------------------------------------------------------------------
1876
1877%% stop any ongoing series processing
1878if isequal(get(handles.RUN,'Value'),1)
1879    answer= msgbox_uvmat('INPUT_Y-N','stop current Action process?');
1880    if strcmp(answer,'Yes')
1881        STOP_Callback(hObject, eventdata, handles)
1882    else
1883        return
1884    end
1885end
1886set(handles.ActionName,'BackgroundColor',[1 1 0])
1887huigetfile=findobj(allchild(0),'tag','status_display');
1888if ~isempty(huigetfile)
1889    delete(huigetfile)
1890end
1891drawnow
1892
1893%% get Action name and path
1894nb_builtin_ACTION=4; %nbre of functions initially proposed in the menu ActionName (as defined in the Opening fct of series)
1895ActionList=get(handles.ActionName,'String');% list menu fields
1896ActionIndex=get(handles.ActionName,'Value');
1897if ~isequal(ActionIndex,1)% if we are not just opening series
1898    InputTable=get(handles.InputTable,'Data');
1899    if isempty(InputTable{1,4})
1900        msgbox_uvmat('ERROR','no input file available: use Open in the menu bar')
1901        return
1902    end
1903end
1904ActionName= ActionList{get(handles.ActionName,'Value')}; % selected function name
1905ActionPathList=get(handles.ActionName,'UserData');%list of recorded paths to functions of the list ActionName
1906
1907%% add a new function to the menu if 'more...' has been selected in the menu ActionName
1908if isequal(ActionName,'more...')
1909    [FileName, PathName] = uigetfile( ...
1910        {'*.m', ' (*.m)';
1911        '*.m',  '.m files '; ...
1912        '*.*', 'All Files (*.*)'}, ...
1913        'Pick a series processing function ',get(handles.ActionPath,'String'));
1914    if length(FileName)<2
1915        return
1916    end
1917    [ActionPath,ActionName,ActionExt]=fileparts(FileName);
1918   
1919    % insert the choice in the menu ActionName
1920    ActionIndex=find(strcmp(ActionName,ActionList),1);% look for the selected function in the menu Action
1921    if isempty(ActionIndex)%the input string does not exist in the menu
1922        ActionIndex= length(ActionList);
1923        ActionList=[ActionList(1:end-1);{ActionName};ActionList(end)];% the selected function is appended in the menu, before the last item 'more...'
1924        set(handles.ActionName,'String',ActionList)
1925    end
1926   
1927    % record the file extension and extend the path list if it is a new extension
1928    ActionExtList=get(handles.ActionExt,'String');
1929    ActionExtIndex=find(strcmp(ActionExt,ActionExtList), 1);
1930    if isempty(ActionExtIndex)
1931        set(handles.ActionExt,'String',[ActionExtList;{ActionExt}])
1932        ActionExtIndex=numel(ActionExtList)+1;
1933        ActionPathNew=cell(size(ActionPathList,1),1);%new column of ActionPath
1934        ActionPathList=[ActionPathList ActionPathNew];
1935    end
1936    set(handles.ActionName,'UserData',ActionPathList);
1937
1938    % remove old Action options in the menu (keeping a menu length <nb_builtin_ACTION+5)
1939    if length(ActionList)>nb_builtin_ACTION+5; %nb_builtin=nbre of functions always remaining in the initial menu
1940        nbremove=length(ActionList)-nb_builtin_ACTION-5;
1941        ActionList(nb_builtin_ACTION+1:end-5)=[];
1942        ActionPathList(nb_builtin_ACTION+1:end-4,:)=[];
1943        ActionIndex=ActionIndex-nbremove;
1944    end
1945   
1946    % record action menu, choice and path
1947    set(handles.ActionName,'Value',ActionIndex)
1948    set(handles.ActionName,'String',ActionList)
1949    set(handles.ActionExt,'Value',ActionExtIndex)
1950    ActionPathList{ActionIndex,ActionExtIndex}=PathName;
1951       
1952    %record the user defined menu additions in personal file profil_perso
1953    dir_perso=prefdir;
1954    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
1955    if nb_builtin_ACTION+1<=numel(ActionList)-1
1956        ActionListUser=ActionList(nb_builtin_ACTION+1:numel(ActionList)-1);
1957        ActionPathListUser=ActionPathList(nb_builtin_ACTION+1:numel(ActionList)-1,:);
1958        ActionExtListUser={};
1959        if numel(ActionExtList)>2
1960            ActionExtListUser=ActionExtList(3:end);
1961        end
1962        if exist(profil_perso,'file')
1963            save(profil_perso,'ActionListUser','ActionPathListUser','ActionExtListUser','-append')
1964        else
1965            save(profil_perso,'ActionListUser','ActionPathListUser','ActionExtListUser','-V6')
1966        end
1967    end
1968end
1969
1970%% check the current ActionPath to the selected function
1971ActionPath=ActionPathList{ActionIndex};%current recorded path
1972set(handles.ActionPath,'String',ActionPath); %show the path to the senlected function
1973
1974%% reinitialise the waitbar
1975update_waitbar(handles.Waitbar,0)
1976
1977%% create the function handle for Action
1978path_series=which('series');
1979if ~isequal(ActionPath,path_series)
1980    eval(['spath=which(''' ActionName ''');']) %spath = current path of the selected function ACTION
1981    if ~exist(ActionPath,'dir')
1982        errormsg=['The prescribed function path ' ActionPath ' does not exist'];
1983        return
1984    end
1985    if ~isequal(spath,ActionPath)
1986        addpath(ActionPath)% add the prescribed path if not the current one
1987    end
1988end
1989eval(['h_fun=@' ActionName ';'])%create a function handle for ACTION
1990if ~isequal(ActionPath,path_series)
1991        rmpath(ActionPath)% add the prescribed path if not the current one   
1992end
1993
1994%% Activate the Action fct
1995Param=read_GUI_series(handles);% read the parameters from the GUI series
1996ParamOut=h_fun(Param);%run the selected Action function to get the relevant input
1997
1998%% Put the first line of the selected Action fct as tooltip help
1999try
2000    [fid,errormsg] =fopen([ActionName '.m']);
2001    InputText=textscan(fid,'%s',1,'delimiter','\n');
2002    fclose(fid);
2003    set(handles.ActionName,'ToolTipString',InputText{1}{1})% put the first line of the selected function as tooltip help
2004end
2005
2006%% Detect the types of input files
2007SeriesData=get(handles.series,'UserData');% info on the input file series
2008iview_civ=[];nb_netcdf=0;
2009if ~isempty(SeriesData)&&isfield(SeriesData,'FileType')
2010    iview_civ=find(strcmp('civx',SeriesData.FileType)|strcmp('civdata',SeriesData.FileType));
2011    nb_netcdf=numel(find(strcmp('netcdf',SeriesData.FileType)));
2012end
2013if numel(iview_civ)>=1 && ~isempty(iview_civ(1))
2014    menu=set_veltype_display(SeriesData.FileInfo{iview_civ(1)}.CivStage,SeriesData.FileType{iview_civ(1)});
2015    set(handles.VelType,'String',[{'*'};menu])
2016    if numel(iview_civ)>=2
2017        menu=set_veltype_display(SeriesData.FileInfo{iview_civ(2)}.CivStage,SeriesData.FileType{iview_civ(2)});
2018        set(handles.VelType_1,'String',[{'*'};menu])
2019    end
2020end       
2021
2022%% Check whether alphabetical sorting of input Subdir is allowed by the Action fct  (for multiples series entries)
2023if isfield(ParamOut,'AllowInputSort')&&isequal(ParamOut.AllowInputSort,'on')&& size(Param.InputTable,1)>1
2024    [tild,iview]=sort(InputTable(:,2)); %subdirectories sorted in alphabetical order
2025    set(handles.InputTable,'Data',InputTable(iview,:));
2026    MinIndex_i=get(handles.MinIndex_i,'Data');
2027    MinIndex_j=get(handles.MinIndex_j,'Data');
2028    MaxIndex_i=get(handles.MaxIndex_i,'Data');
2029    MaxIndex_j=get(handles.MaxIndex_j,'Data');
2030    set(handles.MinIndex_i,'Data',MinIndex_i(iview,:));
2031    set(handles.MinIndex_j,'Data',MinIndex_j(iview,:));
2032    set(handles.MaxIndex_i,'Data',MaxIndex_i(iview,:));
2033    set(handles.MaxIndex_j,'Data',MaxIndex_j(iview,:));
2034    TimeTable=get(handles.TimeTable,'Data');
2035    set(handles.TimeTable,'Data',TimeTable(iview,:));
2036    PairString=get(handles.PairString,'Data');
2037    set(handles.PairString,'Data',PairString(iview,:));
2038end
2039
2040%% Impose the whole input file index range if requested
2041if isfield(ParamOut,'WholeIndexRange')&&isequal(ParamOut.WholeIndexRange,'on')
2042    MinIndex_i=get(handles.MinIndex_i,'Data');
2043    MinIndex_j=get(handles.MinIndex_j,'Data');
2044    MaxIndex_i=get(handles.MaxIndex_i,'Data');
2045    MaxIndex_j=get(handles.MaxIndex_j,'Data');
2046    set(handles.num_first_i,'String',num2str(MinIndex_i(1)))% set first as the min index (for the first line)
2047    set(handles.num_last_i,'String',num2str(MaxIndex_i(1)))% set last as the max index (for the first line)
2048    set(handles.num_incr_i,'String','1')
2049    set(handles.num_first_j,'String',num2str(MinIndex_j(1)))% set first as the min index (for the first line)
2050    set(handles.num_last_j,'String',num2str(MaxIndex_j(1)))% set last as the max index (for the first line)
2051    set(handles.num_incr_j,'String','1')
2052else  % check index ranges
2053    first_i=1;last_i=1;first_j=1;last_j=1;
2054    if isfield(Param.IndexRange,'first_i')
2055        first_i=Param.IndexRange.first_i;
2056       % incr_i=Param.IndexRange.incr_i;
2057        last_i=Param.IndexRange.last_i;
2058    end
2059    if isfield(Param.IndexRange,'first_j')
2060        first_j=Param.IndexRange.first_j;
2061       % incr_j=Param.IndexRange.incr_j;
2062        last_j=Param.IndexRange.last_j;
2063    end
2064    if last_i < first_i || last_j < first_j , msgbox_uvmat('ERROR','last field number must be larger than the first one'),...
2065            set(handles.RUN, 'Enable','On'), set(handles.RUN,'BackgroundColor',[1 0 0]),return,end;
2066end
2067
2068%% desable j index if if set by the civ_input GUI
2069if isfield(ParamOut,'Desable_j_index')&&isequal(ParamOut.Desable_j_index,'on')
2070    set(handles.num_first_j,'Enable','off')
2071    set(handles.num_last_j,'Enable','off')
2072    set(handles.num_incr_j,'Enable','off')
2073    set(handles.num_incr_j,'String','')
2074else
2075   set(handles.num_first_j,'Enable','on')
2076    set(handles.num_last_j,'Enable','on')
2077    set(handles.num_incr_j,'Enable','on')
2078end
2079
2080%% NbSlice visibility
2081NbSliceVisible='off';%default
2082if isfield(ParamOut,'NbSlice') && isequal(ParamOut.NbSlice,'on')
2083    NbSliceVisible='on';
2084    set(handles.num_NbProcess,'String',get(handles.num_NbSlice,'String'))% the nbre of processes is imposed as the nbre of slices
2085else
2086    set(handles.num_NbProcess,'String','')% free nbre of processes
2087end
2088set(handles.num_NbSlice,'Visible',NbSliceVisible)
2089set(handles.NbSlice_title,'Visible',NbSliceVisible)
2090
2091%% Visibility of VelType and VelType_1 menus
2092VelTypeVisible='off';  %hidden by default
2093VelType_1Visible='off';
2094InputFieldsVisible='off';%visibility of the frame Fields
2095if isfield(ParamOut,'VelType')
2096    if strcmp( ParamOut.VelType,'on')||strcmp(ParamOut.VelType,'one')||strcmp( ParamOut.VelType,'two')
2097        if numel(iview_civ)>=1
2098            VelTypeVisible='on';
2099            InputFieldsVisible='on';
2100        end
2101    end
2102    if strcmp( ParamOut.VelType,'two')
2103        if numel(iview_civ)>=2
2104            VelType_1Visible='on';
2105        end
2106    end
2107end
2108set(handles.VelType,'Visible',VelTypeVisible)
2109set(handles.VelType_text,'Visible',VelTypeVisible);
2110set(handles.VelType_1,'Visible',VelType_1Visible)
2111set(handles.VelType_text_1,'Visible',VelType_1Visible);
2112
2113%% Visibility of FieldName and FieldName_1 menus
2114FieldNameVisible='off';  %hidden by default
2115FieldName_1Visible='off';  %hidden by default
2116if isfield(ParamOut,'FieldName')
2117    if strcmp( ParamOut.FieldName,'on') || strcmp(ParamOut.FieldName,'one')||strcmp( ParamOut.FieldName,'two')
2118        if (numel(iview_civ)+nb_netcdf)>=1
2119            InputFieldsVisible='on';
2120            FieldNameVisible='on';
2121        end
2122    end
2123    if strcmp( ParamOut.FieldName,'two')
2124        if (numel(iview_civ)+nb_netcdf)>=1
2125            FieldName_1Visible='on';
2126        end
2127    end
2128end
2129set(handles.InputFields,'Visible',InputFieldsVisible)
2130set(handles.FieldName,'Visible',FieldNameVisible) % test for MenuBorser
2131set(handles.FieldName_1,'Visible',FieldName_1Visible)
2132
2133%% Visibility of FieldTransform menu
2134FieldTransformVisible='off';  %hidden by default
2135if isfield(ParamOut,'FieldTransform')
2136    FieldTransformVisible=ParamOut.FieldTransform; 
2137    TransformName_Callback([],[], handles)
2138end
2139set(handles.FieldTransform,'Visible',FieldTransformVisible)
2140if isfield(ParamOut,'TransformPath')
2141    set(handles.ActionExt,'UserData',ParamOut.TransformPath)
2142else
2143    set(handles.ActionExt,'UserData',[])
2144end
2145
2146%% Visibility of projection object
2147ProjObjectVisible='off';  %hidden by default
2148if isfield(ParamOut,'ProjObject')
2149    ProjObjectVisible=ParamOut.ProjObject;
2150end
2151set(handles.CheckObject,'Visible',ProjObjectVisible)
2152if ~get(handles.CheckObject,'Value')
2153    ProjObjectVisible='off';
2154end
2155set(handles.ProjObject,'Visible',ProjObjectVisible)
2156set(handles.DeleteObject,'Visible',ProjObjectVisible)
2157set(handles.ViewObject,'Visible',ProjObjectVisible)
2158set(handles.EditObject,'Visible',ProjObjectVisible)
2159
2160%% Visibility of mask input
2161MaskVisible='off';  %hidden by default
2162if isfield(ParamOut,'Mask')
2163    MaskVisible=ParamOut.Mask;
2164end
2165%set(handles.Mask,'Visible',MaskVisible)
2166set(handles.CheckMask,'Visible',MaskVisible);
2167
2168%% definition of the directory containing the output files
2169OutputDirVisible='off';
2170if isfield(ParamOut,'OutputDirExt')&&~isempty(ParamOut.OutputDirExt)
2171    OutputSubDirMode='all';%default
2172    if isfield(ParamOut,'OutputSubDirMode')
2173        OutputSubDirMode=ParamOut.OutputSubDirMode;
2174    end
2175    set(handles.OutputDirExt,'String',ParamOut.OutputDirExt)
2176    OutputDirVisible='on';
2177    SubDir=InputTable(1:end,2); %set of subdirectories sorted in alphabetical order
2178    if strcmp(OutputSubDirMode,'last')
2179        SubDirOut=SubDir{end};
2180    else
2181        SubDirOut=SubDir{1};
2182        if ~strcmp(OutputSubDirMode,'first')  && numel(SubDir)>1
2183            for ilist=2:numel(SubDir)
2184                SubDirOut=[SubDirOut '-' SubDir{ilist}];
2185            end
2186        end
2187    end
2188    set(handles.OutputSubDir,'String',SubDirOut)
2189end
2190set(handles.OutputDirExt,'Visible',OutputDirVisible)
2191set(handles.OutputSubDir,'Visible',OutputDirVisible)
2192set(handles.OutputDir_title,'Visible',OutputDirVisible)
2193set(handles.RunMode,'Visible',OutputDirVisible)
2194set(handles.ActionExt,'Visible',OutputDirVisible)
2195set(handles.RunMode_title,'Visible',OutputDirVisible)
2196set(handles.ActionExt_title,'Visible',OutputDirVisible)
2197
2198
2199%% Expected nbre of output files
2200if isfield(ParamOut,'OutputFileMode')
2201    StatusData.OutputFileMode=ParamOut.OutputFileMode;
2202    set(handles.status,'UserData',StatusData)
2203end
2204
2205%% definition of an additional parameter set, determined by an ancillary GUI
2206if isfield(ParamOut,'ActionInput')
2207%     set(handles.ActionInput,'Visible','on')
2208%     set(handles.ActionInput_title,'Visible','on')
2209    set(handles.ActionInput,'Visible','on')
2210 %   set(handles.ActionInput,'Value',0)
2211%     set(handles.ActionInput,'String',ActionName)
2212    ParamOut.ActionInput.Program=ActionName; % record the program in ActionInput
2213    SeriesData.ActionInput=ParamOut.ActionInput;
2214else
2215%     set(handles.ActionInput,'Visible','off')
2216%     set(handles.ActionInput_title,'Visible','off')
2217    set(handles.ActionInput,'Visible','off')
2218    if isfield(SeriesData,'ActionInput')
2219    SeriesData=rmfield(SeriesData,'ActionInput');
2220    end
2221end   
2222set(handles.series,'UserData',SeriesData)
2223set(handles.ActionName,'BackgroundColor',[1 1 1])
2224
2225%------------------------------------------------------------------------
2226% --- Executes on button press in ActionInput.
2227function ActionInput_Callback(hObject, eventdata, handles)
2228%------------------------------------------------------------------------
2229% if get(handles.ActionInput,'Value')
2230ActionName_Callback(hObject, eventdata, handles)
2231% end
2232
2233%------------------------------------------------------------------------
2234% --- Executes on selection change in FieldName.
2235function FieldName_Callback(hObject, eventdata, handles)
2236%------------------------------------------------------------------------
2237field_str=get(handles.FieldName,'String');
2238field_index=get(handles.FieldName,'Value');
2239field=field_str{field_index(1)};
2240if isequal(field,'get_field...')
2241    hget_field=findobj(allchild(0),'name','get_field');
2242    if ~isempty(hget_field)
2243        delete(hget_field)%delete opened versions of get_field
2244    end
2245    Param=read_GUI(handles.series);
2246    Param.InputTable=Param.InputTable(1,:);
2247     % check the existence of the first file in the series
2248    first_j=[];
2249    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
2250    last_j=[];
2251    if isfield(Param.IndexRange,'last_j'); last_j=Param.IndexRange.last_j; end
2252    PairString='';
2253    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
2254    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
2255    FirstFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
2256        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
2257%     filecell=get_file_series(Param);
2258%     
2259    if exist(FirstFileName,'file')
2260        ParamIn.SeriesInput=1;
2261        GetFieldData=get_field(FirstFileName,ParamIn);
2262        FieldList={};
2263        switch GetFieldData.FieldOption
2264            case 'vectors'
2265                UName=GetFieldData.PanelVectors.vector_x;
2266                VName=GetFieldData.PanelVectors.vector_y;
2267                YName={GetFieldData.Coordinates.Coord_y};
2268                CName=GetFieldData.PanelVectors.vec_color;
2269                FieldList={['vec(' UName ',' VName ')'];...
2270                    ['norm(' UName ',' VName ')'];...
2271                    UName;VName};
2272                VecColorList={['norm(' UName ',' VName ')'];...
2273                    UName;VName};
2274                if ~isempty(CName)
2275                    VecColorList=[{CName};VecColorList];
2276                end
2277            case 'scalar'
2278                FieldList=GetFieldData.PanelScalar.scalar;
2279                YName={GetFieldData.Coordinates.Coord_y};
2280                if ischar(FieldList)
2281                FieldList={FieldList};
2282                end
2283            case '1D plot'
2284                YName=GetFieldData.PanelOrdinate.ordinate;
2285%             case 'civdata...'%reinitiate input, return to automatic civ data reading
2286%                 display_file_name(handles,FileName,1)
2287        end
2288        if ~strcmp(GetFieldData.FieldOption,'civdata...')
2289            XName=GetFieldData.Coordinates.Coord_x;
2290            TimeNameStr=GetFieldData.Time.SwitchVarIndexTime;
2291            switch TimeNameStr
2292                case 'file index'
2293                    set(handles.TimeName,'String','');
2294                case 'attribute'
2295                    set(handles.TimeName,'String',['att:' GetFieldData.Time.TimeName]);
2296                case 'variable'
2297                    set(handles.TimeName,'String',['var:' GetFieldData.Time.TimeName])
2298                    set(handles.NomType,'String','*')
2299                    set(handles.RootFile,'String',[get(handles.RootFile,'String') get(handles.FileIndex,'String')])% A VERIFIER !!!!!!
2300                    set(handles.FileIndex,'String','')
2301                    ParamIn.TimeVarName=GetFieldData.Time.TimeName;
2302                case 'matrix_index'
2303                    set(handles.TimeName,'String',['dim:' GetFieldData.Time.TimeName]);
2304                    set(handles.NomType,'String','*')
2305                    set(handles.RootFile,'String',[get(handles.RootFile,'String') get(handles.FileIndex,'String')])
2306                    set(handles.FileIndex,'String','')
2307                    ParamIn.TimeDimName=GetFieldData.Time.TimeName;
2308            end
2309            set(handles.Coord_x,'String',{XName})
2310            set(handles.Coord_y,'String',YName)
2311            set(handles.FieldName,'Value',1)
2312            set(handles.FieldName,'String',[FieldList; {'get_field...'}]);
2313        end
2314    end
2315end
2316
2317%------------------------------------------------------------------------
2318% --- Executes on selection change in FieldName_1.
2319function FieldName_1_Callback(hObject, eventdata, handles)
2320%------------------------------------------------------------------------
2321field_str=get(handles.FieldName_1,'String');
2322field_index=get(handles.FieldName_1,'Value');
2323field=field_str{field_index};
2324if isequal(field,'get_field...')   
2325     hget_field=findobj(allchild(0),'name','get_field_1');
2326     if ~isempty(hget_field)
2327         delete(hget_field)
2328     end
2329     SeriesData=get(handles.series,'UserData');
2330     filename=SeriesData.CurrentInputFile_1;
2331     if exist(filename,'file')
2332        hget_field=get_field(filename);
2333        set(hget_field,'name','get_field_1')
2334     end
2335% elseif isequal(field,'more...')
2336%     str=calc_field;
2337%     [ind_answer,v] = listdlg('PromptString','Select a file:',...
2338%                 'SelectionMode','single',...
2339%                 'ListString',str);
2340%        % edit the choice in the fields and actionname menu
2341%      scalar=cell2mat(str(ind_answer));
2342%      update_menu(handles.FieldName_1,scalar)
2343end   
2344
2345
2346%%%%%%%%%%%%%
2347function [ind_remove]=find_pairs(dirpair,ind_i,last_i)
2348indsel=ind_i;
2349indiff=diff(ind_i); %test index increment to detect multiplets (several pairs with the same index ind_i) and holes in the series
2350indiff=[1 indiff last_i-ind_i(end)+1];%for testing gaps with the imposed bounds
2351if ~isempty(indiff)
2352    indiff2=diff(indiff);
2353    indiffp=[indiff2 1];
2354    indiffm=[1 indiff2];
2355    ind_multi_m=find((indiff==0)&(indiffm<0))-1;%indices of first members of multiplets
2356    ind_multi_p=find((indiff==0)&(indiffp>0));%indices of last members of multiplets
2357    %for each multiplet, select the most recent file
2358    ind_remove=[];
2359    for i=1:length(ind_multi_m)
2360        ind_pairs=ind_multi_m(i):ind_multi_p(i);
2361        for imulti=1:length(ind_pairs)
2362            datepair(imulti)=datenum(dirpair(ind_pairs(imulti)).date);%dates of creation
2363        end
2364        [datenew,indsort2]=sort(datepair); %sort the multiplet by creation date
2365        ind_s=indsort2(1:end-1);%
2366        ind_remove=[ind_remove ind_pairs(ind_s)];%remove these indices, leave the last one
2367    end
2368end
2369
2370%------------------------------------------------------------------------
2371% --- determine the list of index pairstring of processing file
2372function [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)
2373%------------------------------------------------------------------------
2374num_i1=num_i;% set of first image numbers by default
2375num_i2=num_i;
2376num_j1=num_j;
2377num_j2=num_j;
2378num_i_out=num_i;
2379num_j_out=num_j;
2380% if isequal (NomType,'_1-2_1') || isequal (NomType,'_1-2')
2381if isequal(mode,'series(Di)')
2382    num_i1_line=num_i+ind_shift(3);% set of first image numbers
2383    num_i2_line=num_i+ind_shift(4);
2384    % adjust the first and last field number
2385        indsel=find(num_i1_line >= 1);
2386    num_i_out=num_i(indsel);
2387    num_i1_line=num_i1_line(indsel);
2388    num_i2_line=num_i2_line(indsel);
2389    num_j1=meshgrid(num_j,ones(size(num_i1_line)));
2390    num_j2=meshgrid(num_j,ones(size(num_i1_line)));
2391    [xx,num_i1]=meshgrid(num_j,num_i1_line);
2392    [xx,num_i2]=meshgrid(num_j,num_i2_line);
2393elseif isequal (mode,'series(Dj)')||isequal (mode,'bursts')
2394    if isequal(mode,'bursts') %case of bursts (png_old or png_2D)
2395        num_j1=ind_shift(1)*ones(size(num_i));
2396        num_j2=ind_shift(2)*ones(size(num_i));
2397    else
2398        num_j1_col=num_j+ind_shift(1);% set of first image numbers
2399        num_j2_col=num_j+ind_shift(2);
2400        % adjust the first field number
2401        indsel=find((num_j1_col >= 1));   
2402        num_j_out=num_j(indsel);
2403        num_j1_col=num_j1_col(indsel);
2404        num_j2_col=num_j2_col(indsel);
2405        [num_i1,num_j1]=meshgrid(num_i,num_j1_col);
2406        [num_i2,num_j2]=meshgrid(num_i,num_j2_col);
2407    end   
2408end
2409
2410%------------------------------------------------------------------------
2411% --- Executes on button press in CheckObject.
2412function CheckObject_Callback(hObject, eventdata, handles)
2413%------------------------------------------------------------------------
2414hset_object=findobj(allchild(0),'tag','set_object');%find the set_object interface handle
2415if get(handles.CheckObject,'Value')
2416    SeriesData=get(handles.series,'UserData');
2417    if isfield(SeriesData,'ProjObject') && ~isempty(SeriesData.ProjObject)
2418        set(handles.ViewObject,'Value',1)
2419        ViewObject_Callback(hObject, eventdata, handles)
2420    else
2421        if ishandle(hset_object)
2422            uistack(hset_object,'top')% show the GUI set_object if opened
2423        else
2424            %get the object file
2425            InputTable=get(handles.InputTable,'Data');
2426            defaultname=InputTable{1,1};
2427            if isempty(defaultname)
2428                defaultname={''};
2429            end
2430            fileinput=uigetfile_uvmat('pick a xml object file (or use uvmat to create it)',defaultname,'.xml');
2431            if isempty(fileinput)% exit if no object file is selected
2432                set(handles.CheckObject,'Value',0)
2433                return
2434            end
2435            %read the file
2436            data=xml2struct(fileinput);
2437            if ~isfield(data,'Type')
2438                msgbox_uvmat('ERROR',[fileinput ' is not an object xml file'])
2439                set(handles.CheckObject,'Value',0)
2440                return
2441            end
2442            if ~isfield(data,'ProjMode')
2443                data.ProjMode='none';
2444            end
2445            hset_object=set_object(data);% call the set_object interface
2446            set(hset_object,'Name','set_object_series')% name to distinguish from set_object used with uvmat
2447        end
2448        ProjObject=read_GUI(hset_object);
2449        set(handles.ProjObject,'String',ProjObject.Name);%display the object name
2450        SeriesData=get(handles.series,'UserData');
2451        SeriesData.ProjObject=ProjObject;
2452        set(handles.series,'UserData',SeriesData);
2453    end
2454    set(handles.EditObject,'Visible','on');
2455    set(handles.DeleteObject,'Visible','on');
2456    set(handles.ViewObject,'Visible','on');
2457    set(handles.ProjObject,'Visible','on');
2458else
2459    set(handles.EditObject,'Visible','off');
2460    set(handles.DeleteObject,'Visible','off');
2461    set(handles.ViewObject,'Visible','off');
2462    if ~ishandle(hset_object)
2463        set(handles.ViewObject,'Value',0);
2464    end
2465    set(handles.ProjObject,'Visible','off');
2466end
2467
2468%------------------------------------------------------------------------
2469% --- Executes on button press in ViewObject.
2470%------------------------------------------------------------------------
2471function ViewObject_Callback(hObject, eventdata, handles)
2472
2473UserData=get(handles.series,'UserData');
2474hset_object=findobj(allchild(0),'Tag','set_object');
2475if ~isempty(hset_object)
2476    delete(hset_object)% refresh set_object if already opened
2477end
2478hset_object=set_object(UserData.ProjObject);
2479set(hset_object,'Name','view_object_series')
2480
2481
2482%------------------------------------------------------------------------
2483% --- Executes on button press in EditObject.
2484function EditObject_Callback(hObject, eventdata, handles)
2485%------------------------------------------------------------------------
2486if get(handles.EditObject,'Value')
2487    set(handles.ViewObject,'Value',0)
2488        UserData=get(handles.series,'UserData');
2489    hset_object=set_object(UserData.ProjObject);
2490    set(hset_object,'Name','edit_object_series')
2491    set(get(hset_object,'Children'),'Enable','on')
2492else
2493    hset_object=findobj(allchild(0),'Tag','set_object');
2494    if ~isempty(hset_object)
2495        set(get(hset_object,'Children'),'Enable','off')
2496    end
2497end
2498
2499%------------------------------------------------------------------------
2500% --- Executes on button press in DeleteObject.
2501function DeleteObject_Callback(hObject, eventdata, handles)
2502%------------------------------------------------------------------------
2503SeriesData=get(handles.series,'UserData');
2504SeriesData.ProjObject=[];
2505set(handles.series,'UserData',SeriesData)
2506set(handles.ProjObject,'String','')
2507set(handles.ProjObject,'Visible','off')
2508set(handles.CheckObject,'Value',0)
2509set(handles.ViewObject,'Visible','off')
2510set(handles.EditObject,'Visible','off')
2511hset_object=findobj(allchild(0),'name','set_object_series');
2512if ~isempty(hset_object)
2513    delete(hset_object)
2514end
2515set(handles.DeleteObject,'Visible','off')
2516
2517%------------------------------------------------------------------------
2518% --- Executed when CheckMask is activated
2519%------------------------------------------------------------------------
2520function CheckMask_Callback(hObject, eventdata, handles)
2521
2522if get(handles.CheckMask,'Value')
2523    InputTable=get(handles.InputTable,'Data');
2524    nbview=size(InputTable,1);
2525    MaskTable=cell(nbview,1);%default
2526    ListMask=cell(nbview,1);%default
2527    MaskData=get(handles.MaskTable,'Data');
2528    MaskData(size(MaskData,1):nbview,1)=cell(size(MaskData,1):nbview,1);%complement if undefined lines
2529    for iview=1:nbview
2530        ListMask{iview,1}=num2str(iview);
2531        RootPath=InputTable{iview,1};
2532        if ~isempty(RootPath)
2533            if isempty(MaskData{iview})
2534                SubDir=InputTable{iview,2};
2535                MaskPath=fullfile(RootPath,[regexprep(SubDir,'\..*','') '.mask']);%take the root part of SubDir, before the first dot '.'
2536                if exist(MaskPath,'dir')
2537                    ListStruct=dir(MaskPath);%look for a mask file
2538                    ListCells=struct2cell(ListStruct);% transform dir struct to a cell arrray
2539                    check_dir=cell2mat(ListCells(4,:));% =1 for directories, =0 for files
2540                    ListFiles=ListCells(1,:);%list of file and dri names
2541                    ListFiles=ListFiles(~check_dir);%list of file names (excluding dir)
2542                    mdetect=0;
2543                    if ~isempty(ListFiles)
2544                        for ifile=1:numel(ListFiles)
2545                            [tild,tild,MaskFile{ifile},i1_series,i2_series,j1_series,j2_series,MaskNomType,MaskFileType]=find_file_series(MaskPath,ListFiles{ifile},0);
2546                            if strcmp(MaskFileType,'image') && isempty(i2_series) && isempty(j2_series)
2547                                mdetect=1;
2548                                MaskName=ListFiles{ifile};
2549                            end
2550                            if ~strcmp(MaskFile{ifile},MaskFile{1})
2551                                mdetect=0;% cancel detection test in case of multiple masks, use the brower for selection
2552                                break
2553                            end
2554                        end
2555                    end
2556                    if mdetect==1
2557                        MaskName=fullfile(MaskPath,'mask_1.png');
2558                    else
2559                        MaskName=uigetfile_uvmat('select a mask file:',MaskPath,'image');
2560                    end
2561                else
2562                    MaskName=uigetfile_uvmat('select a mask file:',RootPath,'image');
2563                end
2564                MaskTable{iview,1}=MaskName ;
2565                ListMask{iview,1}=num2str(iview);
2566            end
2567        end
2568    end
2569    set(handles.MaskTable,'Data',MaskTable)
2570    set(handles.MaskTable,'Visible','on')
2571    set(handles.MaskBrowse,'Visible','on')
2572    set(handles.ListMask,'Visible','on')
2573    set(handles.ListMask,'String',ListMask)
2574    set(handles.ListMask,'Value',1)
2575else
2576    set(handles.MaskTable,'Visible','off')
2577    set(handles.MaskBrowse,'Visible','off')
2578    set(handles.ListMask,'Visible','off')
2579end
2580
2581%------------------------------------------------------------------------
2582% --- Executes on button press in MaskBrowse.
2583%------------------------------------------------------------------------
2584function MaskBrowse_Callback(hObject, eventdata, handles)
2585
2586InputTable=get(handles.InputTable,'Data');
2587iview=get(handles.ListMask,'Value');
2588RootPath=InputTable{iview,1};
2589MaskName=uigetfile_uvmat('select a mask file:',RootPath,'image');
2590if ~isempty(MaskName)
2591    MaskTable=get(handles.MaskTable,'Data');
2592    MaskTable{iview,1}=MaskName ;
2593    set(handles.MaskTable,'Data',MaskTable)
2594end
2595
2596%------------------------------------------------------------------------
2597% --- Executes when selected cell(s) is changed in MaskTable.
2598%------------------------------------------------------------------------
2599function MaskTable_CellSelectionCallback(hObject, eventdata, handles)
2600
2601if numel(eventdata.Indices)>=1
2602set(handles.ListMask,'Value',eventdata.Indices(1))
2603end
2604
2605%-------------------------------------------------------------------
2606function MenuHelp_Callback(hObject, eventdata, handles)
2607%-------------------------------------------------------------------
2608path_to_uvmat=which ('uvmat');% check the path of uvmat
2609pathelp=fileparts(path_to_uvmat);
2610helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
2611if isempty(dir(helpfile)), msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
2612else
2613    addpath (fullfile(pathelp,'uvmat_doc'))
2614    web([helpfile '#series'])
2615end
2616
2617%-------------------------------------------------------------------
2618% --- Executes on selection change in TransformName.
2619function TransformName_Callback(hObject, eventdata, handles)
2620%----------------------------------------------------------------------
2621TransformList=get(handles.TransformName,'String');
2622TransformIndex=get(handles.TransformName,'Value');
2623TransformName=TransformList{TransformIndex};
2624TransformPathList=get(handles.TransformName,'UserData');
2625nb_builtin_transform=4;
2626if isequal(TransformName,'more...');     
2627    FileName=uigetfile_uvmat('Pick a transform function',get(handles.TransformPath,'String'),'.m');
2628    if isempty(FileName)
2629        return     %browser closed without choice
2630    end
2631    [TransformPath,TransformName,TransformExt]=fileparts(FileName);% removes extension .m
2632    if ~strcmp(TransformExt,'.m')
2633        msgbox_uvmat('ERROR','a Matlab function .m must be introduced');
2634        return
2635    end
2636     % insert the choice in the menu
2637    TransformIndex=find(strcmp(TransformName,TransformList),1);% look for the selected function in the menu Action
2638    if isempty(TransformIndex)%the input string does not exist in the menu
2639        TransformIndex= length(TransformList);
2640        TransformList=[TransformList(1:end-1);{TransformName};TransformList(end)];% the selected function is appended in the menu, before the last item 'more...'
2641        set(handles.TransformName,'String',TransformList)
2642        TransformPathList=[TransformPathList;{TransformPath}];
2643    else% the input function already exist, we update its path (possibly new)
2644        TransformPathList{TransformIndex}=TransformPath;%
2645        set(handles.TransformName,'Value',TransformIndex)
2646    end
2647   % save the new menu in the personal file 'uvmat_perso.mat'
2648   dir_perso=prefdir;%personal Matalb directory
2649   profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
2650   if exist(profil_perso,'file')
2651       for ilist=nb_builtin_transform+1:numel(TransformPathList)
2652           TransformListUser{ilist-nb_builtin_transform}=TransformList{ilist};
2653           TransformPathListUser{ilist-nb_builtin_transform}=TransformPathList{ilist};
2654       end
2655       TransformPathListUser=TransformPathListUser';
2656       TransformListUser=TransformListUser';
2657       save (profil_perso,'TransformPathListUser','TransformListUser','-append'); %store the root name for future opening of uvmat
2658   end
2659end
2660
2661%display the current function path
2662set(handles.TransformPath,'String',TransformPathList{TransformIndex}); %show the path to the senlected function
2663set(handles.TransformName,'UserData',TransformPathList);
2664
2665%------------------------------------------------------------------------
2666% --- fct activated by the upper bar menu ExportConfig
2667%------------------------------------------------------------------------
2668function MenuExportConfig_Callback(hObject, eventdata, handles)
2669
2670global Param
2671Param=read_GUI_series(handles);
2672evalin('base','global Param')%make CurData global in the workspace
2673display('current series config :')
2674evalin('base','Param') %display CurData in the workspace
2675commandwindow; %brings the Matlab command window to the front
2676
2677%------------------------------------------------------------------------
2678% --- fct activated by the upper bar menu InportConfig: import
2679%     menu settings from an xml file (stored in /0_XML for each run)
2680%------------------------------------------------------------------------
2681function MenuImportConfig_Callback(hObject, eventdata, handles)
2682% SeriesData=get(handles.series,'UserData');
2683% if isfield(SeriesData,'RefFile')
2684%     oldfile=SeriesData.RefFile{1};
2685% end
2686%% use a strating file name for browserr
2687InputTable=get(handles.InputTable,'Data');
2688oldfile=InputTable{1,1};
2689if isempty(oldfile)
2690    % use a file name stored in prefdir
2691    dir_perso=prefdir;
2692    profil_perso=fullfile(dir_perso,'uvmat_perso.mat');
2693    if exist(profil_perso,'file')
2694        h=load (profil_perso);
2695        if isfield(h,'RootPath') && ischar(h.RootPath)
2696            oldfile=h.RootPath;
2697        end
2698    end
2699end
2700filexml=uigetfile_uvmat('pick a xml parameter file',oldfile,'.xml');% get the xml file containing processing parameters
2701%proceed only if a file has been introduced by the browser
2702if ~isempty(filexml)
2703    Param=xml2struct(filexml);% read the input xml file as a Matlab structure
2704    % ask to stop current Action if button RUN is in action (another process is already running)
2705    if isequal(get(handles.RUN,'Value'),1)
2706        answer= msgbox_uvmat('INPUT_Y-N','stop current Action process?');
2707        if strcmp(answer,'Yes')
2708            STOP_Callback(hObject, eventdata, handles)
2709        else
2710            return
2711        end
2712    end
2713    Param.Action.RUN=0; %desactivate the input RUN=1
2714    fill_GUI(Param,handles.series)% fill the elements of the GUI series with the input parameters
2715    SeriesData=get(handles.series,'UserData');
2716    if isfield(Param,'ActionInput')%  introduce  parameters specific to an Action fct, for instance PIV parameters
2717        set(handles.ActionInput,'Visible','on')
2718        set(handles.ActionInput,'Value',0)
2719        SeriesData.ActionInput=Param.ActionInput;
2720    end
2721    if isfield(Param,'ProjObject') %introduce projection object if relevant
2722        SeriesData.ProjObject=Param.ProjObject;
2723    end
2724    set(handles.series,'UserData',SeriesData)
2725    if isfield(Param,'CheckObject') && isequal(Param.CheckObject,1)
2726        set(handles.ProjObject,'String',Param.ProjObject.Name)
2727        set(handles.ViewObject,'Visible','on')
2728        set(handles.EditObject,'Visible','on')
2729        set(handles.DeleteObject,'Visible','on')
2730    else     
2731        set(handles.ProjObject,'String','')
2732        set(handles.ProjObject,'Visible','off')
2733        set(handles.ViewObject,'Visible','off')
2734        set(handles.EditObject,'Visible','off')
2735        set(handles.DeleteObject,'Visible','off')     
2736    end     
2737    set(handles.REFRESH,'BackgroundColor',[1 0 1]); %paint REFRESH button in magenta to indicate that it should be activated
2738end
2739
2740%------------------------------------------------------------------------
2741% --- Executes when the GUI series is resized.
2742%------------------------------------------------------------------------
2743function series_ResizeFcn(hObject, eventdata, handles)
2744
2745%% input table
2746set(handles.InputTable,'Unit','pixel')
2747Pos=get(handles.InputTable,'Position');
2748set(handles.InputTable,'Unit','normalized')
2749ColumnWidth=round([0.5 0.14 0.14 0.14 0.08]*(Pos(3)-52));
2750ColumnWidth=num2cell(ColumnWidth);
2751set(handles.InputTable,'ColumnWidth',ColumnWidth)
2752
2753%% MinIndex_j and MaxIndex_i
2754unit=get(handles.MinIndex_i,'Unit');
2755set(handles.MinIndex_i,'Unit','pixel')
2756Pos=get(handles.MinIndex_i,'Position');
2757set(handles.MinIndex_i,'Unit',unit)
2758set(handles.MinIndex_i,'ColumnWidth',{Pos(3)-18})
2759set(handles.MaxIndex_i,'ColumnWidth',{Pos(3)-18})
2760set(handles.MinIndex_j,'ColumnWidth',{Pos(3)-18})
2761set(handles.MaxIndex_j,'ColumnWidth',{Pos(3)-18})
2762
2763%% TimeTable
2764set(handles.TimeTable,'Unit','pixel')
2765Pos=get(handles.TimeTable,'Position');
2766set(handles.TimeTable,'Unit','normalized')
2767% ColumnWidth=get(handles.TimeTable,'ColumnWidth');
2768ColumnWidth=num2cell(floor([0.25 0.25 0.25 0.25]*(Pos(3)-20)));
2769set(handles.TimeTable,'ColumnWidth',ColumnWidth)
2770
2771
2772%% PairString
2773set(handles.PairString,'Unit','pixel')
2774Pos=get(handles.PairString,'Position');
2775set(handles.PairString,'Unit','normalized')
2776set(handles.PairString,'ColumnWidth',{Pos(3)-5})
2777
2778%% MaskTable
2779set(handles.MaskTable,'Unit','pixel')
2780Pos=get(handles.MaskTable,'Position');
2781set(handles.MaskTable,'Unit','normalized')
2782set(handles.MaskTable,'ColumnWidth',{Pos(3)-5})
2783
2784%------------------------------------------------------------------------
2785% --- Executes on button press in status.
2786%------------------------------------------------------------------------
2787function status_Callback(hObject, eventdata, handles)
2788
2789if get(handles.status,'Value')
2790    set(handles.status,'BackgroundColor',[1 1 0])
2791    drawnow
2792    Param=read_GUI(handles.series);
2793    RootPath=Param.InputTable{1,1};
2794    if ~isfield(Param,'OutputSubDir')   
2795        msgbox_uvmat('ERROR','no directory defined for output files')
2796        return
2797    end
2798    OutputSubDir=[Param.OutputSubDir Param.OutputDirExt];% subdirectory for output files
2799    OutputDir=fullfile(RootPath,OutputSubDir);
2800    if exist(OutputDir,'dir')
2801        uigetfile_uvmat('status_display',OutputDir)
2802    else
2803        msgbox_uvmat('ERROR','output folder not created yet: calculation did not start')
2804        set(handles.status,'BackgroundColor',[0 1 0])
2805    end
2806else
2807    %% delete current display fig if selection is off
2808    set(handles.status,'BackgroundColor',[0 1 0])
2809    hfig=findobj(allchild(0),'name','status_display');
2810    if ~isempty(hfig)
2811        delete(hfig)
2812    end
2813    return
2814end
2815
2816
2817%------------------------------------------------------------------------   
2818% launched by selecting a file on the list
2819%------------------------------------------------------------------------
2820function view_file(hObject, eventdata)
2821
2822list=get(hObject,'String');
2823index=get(hObject,'Value');
2824rootroot=get(hObject,'UserData');
2825selectname=list{index};
2826ind_dot=regexp(selectname,'\.\.\.');
2827if ~isempty(ind_dot)
2828    selectname=selectname(1:ind_dot-1);
2829end
2830FullSelectName=fullfile(rootroot,selectname);
2831if exist(FullSelectName,'dir')% a directory has been selected
2832    ListFiles=dir(FullSelectName);
2833    ListDisplay=cell(numel(ListFiles),1);
2834    for ilist=2:numel(ListDisplay)% suppress the first line '.'
2835        ListDisplay{ilist-1}=ListFiles(ilist).name;
2836    end
2837    set(hObject,'Value',1)
2838    set(hObject,'String',ListDisplay)
2839    if strcmp(selectname,'..')
2840        FullSelectName=fileparts(fileparts(FullSelectName));
2841    end
2842    set(hObject,'UserData',FullSelectName)
2843    hfig=get(hObject,'parent');
2844    htitlebox=findobj(hfig,'tag','titlebox');   
2845    set(htitlebox,'String',FullSelectName)
2846elseif exist(FullSelectName,'file')%visualise the vel field if it exists
2847    FileType=get_file_type(FullSelectName);
2848    if strcmp(FileType,'txt')
2849        edit(FullSelectName)
2850    elseif strcmp(FileType,'xml')
2851        editxml(FullSelectName)
2852    else
2853        uvmat(FullSelectName)
2854    end
2855    set(gcbo,'Value',1)
2856end
2857
2858
2859%------------------------------------------------------------------------   
2860% launched by refreshing the status figure
2861%------------------------------------------------------------------------
2862function refresh_GUI(hfig)
2863
2864htitlebox=findobj(hfig,'tag','titlebox');
2865hlist=findobj(hfig,'tag','list');
2866hseries=findobj(allchild(0),'tag','series');
2867hstatus=findobj(hseries,'tag','status');
2868StatusData=get(hstatus,'UserData');
2869OutputDir=get(htitlebox,'String');
2870if ischar(OutputDir),OutputDir={OutputDir};end
2871ListFiles=dir(OutputDir{1});
2872if numel(ListFiles)<1
2873    return
2874end
2875ListFiles(1)=[];%removes the first line ='.'
2876ListDisplay=cell(numel(ListFiles),1);
2877testrecent=0;
2878datnum=zeros(numel(ListDisplay),1);
2879for ilist=1:numel(ListDisplay)
2880    ListDisplay{ilist}=ListFiles(ilist).name;
2881      if ~ListFiles(ilist).isdir && isfield(ListFiles(ilist),'datenum')
2882            datnum(ilist)=ListFiles(ilist).datenum;%only available in recent matlab versions
2883            testrecent=1;
2884       end
2885end
2886set(hlist,'String',ListDisplay)
2887
2888%% Look at date of creation
2889ListDisplay=ListDisplay(datnum~=0);
2890datnum=datnum(datnum~=0);%keep the non zero values corresponding to existing files
2891NbOutputFile=[];
2892if isempty(datnum)
2893    if testrecent
2894        message='no civ result created yet';
2895    else
2896        message='';
2897    end
2898else
2899    [first,indfirst]=min(datnum);
2900    [last,indlast]=max(datnum);
2901    NbOutputFile_str='?';
2902    NbOutputFile=[];
2903    if isfield(StatusData,'NbOutputFile')
2904        NbOutputFile=StatusData.NbOutputFile;
2905        NbOutputFile_str=num2str(NbOutputFile);
2906    end
2907    message={[num2str(numel(datnum)) ' file(s) done over ' NbOutputFile_str] ;['oldest modification:  ' ListDisplay{indfirst} ' : ' datestr(first)];...
2908        ['latest modification:  ' ListDisplay{indlast} ' : ' datestr(last)]};
2909end
2910set(htitlebox,'String', [OutputDir{1};message])
2911
2912%% update the waitbar
2913hwaitbar=findobj(hfig,'tag','waitbar');
2914if ~isempty(NbOutputFile)
2915    BarPosition=get(hwaitbar,'Position');
2916    BarPosition(3)=0.9*numel(datnum)/NbOutputFile;
2917    set(hwaitbar,'Position',BarPosition)
2918end
2919
2920%------------------------------------------------------------------------
2921% --- Executes on selection change in ActionExt.
2922%------------------------------------------------------------------------
2923function ActionExt_Callback(hObject, eventdata, handles)
2924
2925ActionExtList=get(handles.ActionExt,'String');
2926ActionExt=ActionExtList{get(handles.ActionExt,'Value')};
2927ActionList=get(handles.ActionName,'String');
2928ActionName=ActionList{get(handles.ActionName,'Value')};
2929TransformPath='';
2930if ~isempty(get(handles.ActionExt,'UserData'))
2931    TransformPath=get(handles.ActionExt,'UserData');
2932end
2933if strcmp(ActionExt,'.sh')
2934    set(handles.series,'Pointer','watch') % set the mouse pointer to 'watch'
2935    set(handles.ActionExt,'BackgroundColor',[1 1 0])
2936    ActionFullName=fullfile(get(handles.ActionPath,'String'),[ActionName '.sh']);
2937    if ~exist(ActionFullName,'file')
2938        answer=msgbox_uvmat('INPUT_Y-N','compiled version has not been created: compile now?');
2939        if strcmp(answer,'Yes')
2940            set(handles.ActionExt,'BackgroundColor',[1 1 0])
2941            path_uvmat=fileparts(which('series'));
2942            currentdir=pwd;
2943            cd(get(handles.ActionPath,'String'))% go to the directory of Action
2944            %  addpath(get(handles.TransformPath,'String'))
2945            addpath(path_uvmat)% add the path to uvmat to run the fct 'compile'
2946           % addpath(fullfile(path_uvmat,'transform_field'))% add the path to uvmat to run the fct 'compile'
2947            compile(ActionName,TransformPath)
2948            cd(currentdir)
2949        end       
2950    else
2951        sh_file_info=dir(fullfile(get(handles.ActionPath,'String'),[ActionName '.sh']));
2952        m_file_info=dir(fullfile(get(handles.ActionPath,'String'),[ActionName '.m']));
2953        if isfield(m_file_info,'datenum') && m_file_info.datenum>sh_file_info.datenum
2954            set(handles.ActionExt,'BackgroundColor',[1 1 0])
2955            drawnow
2956            answer=msgbox_uvmat('INPUT_Y-N',[ActionName '.sh needs to be updated: recompile now?']);
2957            if strcmp(answer,'Yes')
2958                path_uvmat=fileparts(which('series'));
2959                currentdir=pwd;
2960                cd(get(handles.ActionPath,'String'))% go to the directory of Action
2961                %  addpath(get(handles.TransformPath,'String'))
2962                addpath(path_uvmat)% add the path to uvmat to run the fct 'compile'
2963                addpath(fullfile(path_uvmat,'transform_field'))% add the path to uvmat to run the fct 'compile'
2964                compile(ActionName,TransformPath)
2965                cd(currentdir)
2966            end
2967        end
2968    end
2969    set(handles.ActionExt,'BackgroundColor',[1 1 1])
2970     set(handles.series,'Pointer','arrow') % set the mouse pointer to 'watch
2971end
2972
2973
2974
2975
2976function num_NbProcess_Callback(hObject, eventdata, handles)
2977
2978
2979function num_NbSlice_Callback(hObject, eventdata, handles)
2980NbSlice=str2num(get(handles.num_NbSlice,'String'));
2981set(handles.num_NbProcess,'String',num2str(NbSlice))
2982
2983%------------------------------------------------------------------------
2984% --- set the visibility of relevant velocity type menus:
2985function menu=set_veltype_display(Civ,FileType)
2986%------------------------------------------------------------------------
2987if ~exist('FileType','var')
2988    FileType='civx';
2989end
2990switch FileType
2991    case 'civx'
2992        menu={'civ1';'interp1';'filter1';'civ2';'interp2';'filter2'};
2993        if isequal(Civ,0)
2994            imax=0;
2995        elseif isequal(Civ,1) || isequal(Civ,2)
2996            imax=1;
2997        elseif isequal(Civ,3)
2998            imax=3;
2999        elseif isequal(Civ,4) || isequal(Civ,5)
3000            imax=4;
3001        elseif isequal(Civ,6) %patch2
3002            imax=6;
3003        end
3004    case 'civdata'
3005        menu={'civ1';'filter1';'civ2';'filter2'};
3006        if isequal(Civ,0)
3007            imax=0;
3008        elseif isequal(Civ,1) || isequal(Civ,2)
3009            imax=1;
3010        elseif isequal(Civ,3)
3011            imax=2;
3012        elseif isequal(Civ,4) || isequal(Civ,5)
3013            imax=3;
3014        elseif isequal(Civ,6) %patch2
3015            imax=4;
3016        end
3017end
3018menu=menu(1:imax);
3019
3020
3021% --- Executes on mouse motion over figure - except title and menu.
3022function series_WindowButtonMotionFcn(hObject, eventdata, handles)
3023set(hObject,'Pointer','arrow');
Note: See TracBrowser for help on using the repository browser.