source: trunk/src/series.m @ 861

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

bug_corrections

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