source: trunk/src/series.m @ 769

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

corrections to be able to process image correlation in series

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