source: trunk/src/series.m @ 605

Last change on this file since 605 was 605, checked in by sommeria, 12 years ago

bugs corrected to get an advancement bar with status

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