source: trunk/src/series.m @ 719

Last change on this file since 719 was 719, checked in by sommeria, 11 years ago

corrrections to series

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