source: trunk/src/series.m @ 714

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

various improvements

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