source: trunk/src/series.m @ 851

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

various

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