source: trunk/src/series.m @ 844

Last change on this file since 844 was 844, checked in by sommeria, 9 years ago

various bugs repaired

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