source: trunk/src/series.m @ 711

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

various improvements

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