source: trunk/src/series/time_series.m @ 474

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

functions adpated to mode background

File size: 20.9 KB
Line 
1%'time_series': extract a time series, used with series.fig
2% this function can be used as a template for applying a global operation on a series of input fields
3%------------------------------------------------------------------------
4% function GUI_input=time_series(Param)
5%
6%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
7%
8% This function is used in four modes by the GUI series:
9%           1) config GUI: with no input argument, the function determine the suitable GUI configuration
10%           2) interactive input: the function is used to interactively introduce input parameters, and then stops
11%           3) RUN: the function itself runs, when an appropriate input  structure Param has been introduced.
12%           4) BATCH: the function itself proceeds in BATCH mode, using an xml file 'Param' as input.
13%
14% This function is used in four modes by the GUI series:
15%           1) config GUI: with no input argument, the function determine the suitable GUI configuration
16%           2) interactive input: the function is used to interactively introduce input parameters, and then stops
17%           3) RUN: the function itself runs, when an appropriate input  structure Param has been introduced.
18%           4) BATCH: the function itself proceeds in BATCH mode, using an xml file 'Param' as input.
19%
20%OUTPUT
21% GUI_input=list of options in the GUI series.fig needed for the function
22%
23%INPUT:
24% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
25% In batch mode, Param is the name of the corresponding xml file containing the same information
26% In the absence of input (as activated when the current Action is selected
27% in series), the function ouput GUI_input set the activation of the needed GUI elements
28%
29% Param contains the elements:(use the menu bar command 'export/GUI config' in series to see the current structure Param)
30%    .InputTable: cell of input file names, (several lines for multiple input)
31%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
32%    .OutputSubDir: name of the subdirectory for data outputs
33%    .OutputDirExt: directory extension for data outputs
34%    .Action: .ActionName: name of the current activated function
35%             .ActionPath:   path of the current activated function
36%    .IndexRange: set the file or frame indices on which the action must be performed
37%    .FieldTransform: .TransformName: name of the selected transform function
38%                     .TransformPath:   path  of the selected transform function
39%                     .TransformHandle: corresponding function handle
40%    .InputFields: sub structure describing the input fields withfields
41%              .FieldName: name of the field
42%              .VelType: velocity type
43%              .FieldName_1: name of the second field in case of two input series
44%              .VelType_1: velocity type of the second field in case of two input series
45%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
46%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
47%
48function ParamOut=time_series(Param)
49
50%% set the input elements needed on the GUI series when the action is selected in the menu ActionName
51if ~exist('Param','var') % case with no input parameter
52    ParamOut={'AllowInputSort';'off';...% allow alphabetic sorting of the list of input files (options 'off'/'on', 'off' by default)
53        'WholeIndexRange';'off';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
54        'NbSlice';'on'; ...%nbre of slices ('off' by default)
55        'VelType';'two';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
56        'FieldName';'two';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
57        'FieldTransform'; 'on';...%can use a transform function
58        'ProjObject';'on';...%can use projection object(option 'off'/'on',
59        'Mask';'off';...%can use mask option   (option 'off'/'on', 'off' by default)
60        'OutputDirExt';'.tseries';...%set the output dir extension
61               ''};
62        return
63end
64
65%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
66%% select different modes,  RUN, parameter input, BATCH
67% BATCH  case: read the xml file for batch case
68if ischar(Param)
69        Param=xml2struct(Param);
70        checkrun=0;
71% RUN case: parameters introduced as the input structure Param
72else
73    hseries=guidata(Param.hseries);%handles of the GUI series
74    WaitbarPos=get(hseries.waitbar_frame,'Position');%position of the waitbar on the GUI series
75    if isfield(Param,'Specific')&& strcmp(Param.Specific,'?')
76        checkrun=1;% will only search interactive input parameters (preparation of BATCH mode)
77    else
78        checkrun=2; % indicate the RUN option is used
79    end
80end
81ParamOut=Param; %default output
82OutputDir=[Param.OutputSubDir Param.OutputDirExt];
83
84%% root input file(s) and type
85RootPath=Param.InputTable(:,1);
86RootFile=Param.InputTable(:,3);
87SubDir=Param.InputTable(:,2);
88NomType=Param.InputTable(:,4);
89FileExt=Param.InputTable(:,5);
90
91% get the set of input file names (cell array filecell), and the lists of
92% input file or frame indices i1_series,i2_series,j1_series,j2_series
93[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
94% filecell{iview,fileindex}: cell array representing the list of file names
95%        iview: line in the table corresponding to a given file series
96%        fileindex: file index within  the file series,
97% i1_series(iview,ref_j,ref_i)... are the corresponding arrays of indices i1,i2,j1,j2, depending on the input line iview and the two reference indices ref_i,ref_j
98% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
99% set of frame indices used for movie or multimage input
100% numbers of slices and file indices
101
102NbSlice=1;%default
103if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
104    NbSlice=Param.IndexRange.NbSlice;
105end
106nbview=numel(i1_series);%number of input file series (lines in InputTable)
107nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
108nbfield_i=size(i1_series{1},2); %nb of fields for the i index
109nbfield=nbfield_j*nbfield_i; %total number of fields
110nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
111nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
112
113%determine the file type on each line from the first input file
114ImageTypeOptions={'image','multimage','mmreader','video'};
115NcTypeOptions={'netcdf','civx','civdata'};
116for iview=1:nbview
117    if ~exist(filecell{iview,1}','file')
118        displ_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
119        return
120    end
121    [FileType{iview},FileInfo{iview},MovieObject{iview}]=get_file_type(filecell{iview,1});
122    CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
123    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
124    if ~isempty(j1_series{iview})
125        frame_index{iview}=j1_series{iview};
126    else
127        frame_index{iview}=i1_series{iview};
128    end
129end
130
131%% calibration data and timing: read the ImaDoc files
132[XmlData,NbSlice_calib,time,errormsg]=read_multimadoc(RootPath,SubDir,RootFile,FileExt,i1_series,i2_series,j1_series,j2_series);
133if size(time,1)>1
134    diff_time=max(max(diff(time)));
135    if diff_time>0
136        displ_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time)],checkrun)
137    end   
138end
139
140%% coordinate transform or other user defined transform
141transform_fct='';%default
142if isfield(Param,'FieldTransform')
143    addpath(Param.FieldTransform.TransformPath)
144    transform_fct=str2func(Param.FieldTransform.TransformName);
145    rmpath(Param.FieldTransform.TransformPath)
146end
147
148%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
149 % EDIT FROM HERE
150
151%% check the validity of  input file types
152if CheckImage{1}
153    FileExtOut='.png'; % write result as .png images for image inputs
154elseif CheckNc{1}
155    FileExtOut='.nc';% write result as .nc files for netcdf inputs
156else
157    displ_uvmat('ERROR',['invalid file type input ' FileType{1}],checkrun)
158    return
159end
160if nbview==2 && ~isequal(CheckImage{1},CheckImage{2})
161        displ_uvmat('ERROR','input must be two image series or two netcdf file series',checkrun)
162    return
163end
164NomTypeOut='_1-2_1';% output file index will indicate the first and last ref index in the series
165% if NbSlice~=nbfield_j
166%     answer=_uvmat('INPUT_Y-N',['will not average slice by slice: for so cancel and set NbSlice= ' num2str(nbfield_j)]);
167%     if ~strcmp(answer,'Yes')
168%         return
169%     end
170% end
171
172%% Set field names and velocity types
173InputFields{1}=[];%default (case of images)
174if isfield(Param,'InputFields')
175    InputFields{1}=Param.InputFields;
176end
177if nbview==2
178    InputFields{2}=[];%default (case of images)
179    if isfield(Param,'InputFields')
180        InputFields{2}=Param.InputFields{1};%default
181        if isfield(Param.InputFields,'FieldName_1')
182            InputFields{2}.FieldName=Param.InputFields.FieldName_1;
183            if isfield(Param.InputFields,'VelType_1')
184                InputFields{2}.VelType=Param.InputFields.VelType_1;
185            end
186        end
187    end
188end
189%%% TO UPDATE
190if isequal(InputFields{1},'get_field...')
191    hget_field=findobj(allchild(0),'name','get_field');%find the get_field... GUI
192    if numel(hget_field)>1
193        delete(hget_field(2:end)) % delete multiple occurerence of the GUI get_fioeld
194    elseif isempty(hget_field)
195        filename=filecell{1,1};
196      % filename=name_generator(filebase{1},i1_series{1}(1),j1_series{1}(1),FileExt{1},NomType{1},1,i2_series{1}(1),num_j2{1}(1),SubDir{1});
197       idetect(iview)=exist(filename,'file');
198       hget_field=get_field(filename);
199       return
200    end
201    SubField=read_get_field(hget_field); %read the names of the variables to plot in the get_field GUI
202    if isempty(SubField)
203        delete(hget_field)
204        filename=filecell{1,1};
205       %filename=name_generator(filebase{1},i1_series{1}(1),j1_series{1}(1),FileExt{1},NomType{1},1,i2_series{1}(1),j2_series{1}(1),SubDir{1});
206        hget_field=get_field(filename);
207        SubField=read_get_field(hget_field); %read the names of the variables to plot in the get_field GUI
208    end
209end
210%%%%%%%
211
212%% Initiate output fields
213%initiate the output structure as a copy of the first input one (reproduce fields)
214[DataOut,tild,errormsg] = read_field(filecell{1,1},FileType{1},InputFields{1},1);
215if ~isempty(errormsg)
216    displ_uvmat('ERROR',['error reading ' filecell{1,1} ': ' errormsg],checkrun)
217    return
218end
219time_1=[];
220if isfield(DataOut,'Time')
221    time_1=DataOut.Time(1);
222end
223if CheckNc{iview}
224    if isempty(strcmp('Conventions',DataOut.ListGlobalAttribute))
225        DataOut.ListGlobalAttribute=['Conventions' DataOut.ListGlobalAttribute];
226    end
227    DataOut.Conventions='uvmat';
228    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {Param.Action}];
229    ActionKey='Action';
230    while isfield(DataOut,ActionKey)
231        ActionKey=[ActionKey '_1'];
232    end
233    DataOut.(ActionKey)=Param.Action;
234    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {ActionKey}];
235    if isfield(DataOut,'Time')
236        DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {'Time','Time_end'}];
237    end
238end
239
240%% LOOP ON SLICES
241nbmissing=0; %number of undetected files
242for i_slice=1:NbSlice
243    index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
244    nbfiles=0;
245    nbmissing=0;
246   
247    %%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
248    for index=index_slice       
249        if checkrun
250            update_waitbar(hseries.waitbar_frame,WaitbarPos,index/(nbfield))
251            stopstate=get(hseries.RUN,'BusyAction');
252        else
253            stopstate='queue';
254        end
255       
256        %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
257        Data=cell(1,nbview);%initiate the set Data
258        nbtime=0;
259        dt=[];
260        if isequal(stopstate,'queue')% enable STOP command
261            % loop on views (in case of multiple input series)
262            for iview=1:nbview
263                % reading input file(s)
264                [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},Param.InputFields,frame_index{iview}(index));
265                if ~isempty(errormsg)
266                    errormsg=['time_series/read_field/' errormsg];
267                    display(errormsg)
268                    break
269                end
270                timeread(iview)=0;
271                if isfield(Data{iview},'Time')
272                    timeread(iview)=Data{iview}.Time;
273                    nbtime=nbtime+1;
274                end
275                if ~isempty(NbSlice_calib)
276                    Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
277                end
278            end
279            % coordinate transform (or other user defined transform)
280            if ~isempty(transform_fct)
281                if nbview==2
282                    [Data{1},Data{2}]=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
283                    if isempty(Data{2})
284                        Data(2)=[];
285                    end
286                else
287                    Data{1}=transform_fct(Data{1},XmlData{1});
288                end
289            end
290            if length(Data)==2
291                [Field,errormsg]=sub_field(Data{1},Data{2}); %substract the two fields
292            else
293                Field=Data{1};
294            end
295            if Param.CheckObject
296                [Field,errormsg]=proj_field(Field,Param.ProjObject);
297            end
298            nbtime=nbtime+1;
299           
300            % initiate the time series at the first iteration
301            if nbtime==1
302                % stop program if the first field reading is in error
303                if ~isempty(errormsg)
304                    displ_uvmat('ERROR',['error in time_series/sub_field:' errormsg],checkrun)
305                    return
306                end
307                DataOut=Field;%default
308                DataOut.NbDim=Field.NbDim+1; %add the time dimension for plots
309                nbvar=length(Field.ListVarName);
310                if nbvar==0
311                    displ_uvmat('ERROR','no input variable selected in get_field',checkrun)
312                    return
313                end
314                testsum=2*ones(1,nbvar);%initiate flag for action on each variable
315                if isfield(Field,'VarAttribute') % look for coordinate and flag variables
316                    for ivar=1:nbvar
317                        if length(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'Role')
318                            var_role=Field.VarAttribute{ivar}.Role;%'role' of the variable
319                            if isequal(var_role,'errorflag')
320                                displ_uvmat('ERROR','do not handle error flags in time series',checkrun)
321                                return
322                            end
323                            if isequal(var_role,'warnflag')
324                                testsum(ivar)=0;  % not recorded variable
325                                eval(['DataOut=rmfield(DataOut,''' Field.ListVarName{ivar} ''');']);%remove variable
326                            end
327                            if isequal(var_role,'coord_x')| isequal(var_role,'coord_y')|...
328                                    isequal(var_role,'coord_z')|isequal(var_role,'coord')
329                                testsum(ivar)=1; %constant coordinates, record without time evolution
330                            end
331                        end
332                        % check whether the variable ivar is a dimension variable
333                        DimCell=Field.VarDimName{ivar};
334                        if ischar(DimCell)
335                            DimCell={DimCell};
336                        end
337                        if numel(DimCell)==1 && isequal(Field.ListVarName{ivar},DimCell{1})%detect dimension variables
338                            testsum(ivar)=1;
339                        end
340                    end
341                end
342                for ivar=1:nbvar
343                    if testsum(ivar)==2
344                        eval(['DataOut.' Field.ListVarName{ivar} '=[];'])
345                    end
346                end
347                DataOut.ListVarName=[{'Time'} DataOut.ListVarName];
348            end
349           
350            % add data to the current field
351            for ivar=1:length(Field.ListVarName)
352                VarName=Field.ListVarName{ivar};
353                VarVal=Field.(VarName);
354                if testsum(ivar)==2% test for recorded variable
355                    if isempty(errormsg)
356                        if isequal(Param.ProjObject.ProjMode,'inside')% take the average in the domain for 'inside' mode
357                            if isempty(VarVal)
358                                displ_uvmat('ERROR',['empty result at frame index ' num2str(i1_series{iview}(ifile))],checkrun)
359                                return
360                            end
361                            VarVal=mean(VarVal,1);
362                        end
363                        VarVal=shiftdim(VarVal,-1); %shift dimension
364                        DataOut.(VarName)=cat(1,DataOut.(VarName),VarVal);%concanete the current field to the time series
365                    else
366                        DataOut.(VarName)=cat(1,DataOut.(VarName),0);% put each variable to 0 in case of input reading error
367                    end
368                elseif testsum(ivar)==1% variable representing fixed coordinates
369                    eval(['VarInit=DataOut.' VarName ';']);
370                    if isempty(errormsg) && ~isequal(VarVal,VarInit)
371                        displ_uvmat('ERROR',['time series requires constant coordinates ' VarName],checkrun)
372                        return
373                    end
374                end
375            end
376           
377            % record the time:
378            if isempty(time)% time read in ncfiles
379                if isfield(Field,'Time')
380                    DataOut.Time(filecounter,1)=Field.Time;
381                else
382                    DataOut.Time(filecounter,1)=ifile;%default
383                end
384            else % time from ImaDoc prevails  TODO: correct
385                %  DataOut.Time(filecounter,1)=time{1}(i1_series{1})(ifile),j1_series{1}(ifile))+time(end,i2_series{end}(ifile),j2_series{end}(ifile)))/2;
386                DataOut.Time(filecounter,1)=i1_series{1}(ifile);% TODO : generalise
387            end
388           
389            % record the number of missing input fields
390            if ~isempty(errormsg)
391                nbmissing=nbmissing+1;
392                display(['ifile=' num2str(ifile) ':' errormsg])
393            end
394        end
395    end
396    %%%%%%% END OF LOOP WITHIN A SLICE
397   
398    %remove time for global attributes if exists
399    Time_index=find(strcmp('Time',DataOut.ListGlobalAttribute));
400    if ~isempty(Time_index)
401        DataOut.ListGlobalAttribute(Time_index)=[];
402    end
403    DataOut.Conventions='uvmat';
404    for ivar=1:numel(DataOut.ListVarName)
405        VarName=DataOut.ListVarName{ivar};
406        eval(['DataOut.' VarName '=squeeze(DataOut.' VarName ');']) %remove singletons
407    end
408   
409    % add time dimension
410    for ivar=1:length(Field.ListVarName)
411        DimCell=Field.VarDimName(ivar);
412        if testsum(ivar)==2%variable used as time series
413            DataOut.VarDimName{ivar}=[{'Time'} DimCell];
414        elseif testsum(ivar)==1
415            DataOut.VarDimName{ivar}=DimCell;
416        end
417    end
418    indexremove=find(~testsum);
419    if ~isempty(indexremove)
420        DataOut.ListVarName(1+indexremove)=[];
421        DataOut.VarDimName(indexremove)=[];
422        if isfield(DataOut,'Role') && ~isempty(DataOut.Role{1})%generaliser aus autres attributs
423            DataOut.Role(1+indexremove)=[];
424        end
425    end
426   
427    %shift variable attributes
428    if isfield(DataOut,'VarAttribute')
429        DataOut.VarAttribute=[{[]} DataOut.VarAttribute];
430    end
431    DataOut.VarDimName=[{'Time'} DataOut.VarDimName];
432    DataOut.Action=Param.Action;%name of the processing programme
433    test_time=diff(DataOut.Time)>0;% test that the readed time is increasing (not constant)
434    if ~test_time
435        DataOut.Time=[1:filecounter];
436    end
437   
438    % display nbmissing
439    if ~isequal(nbmissing,0)
440        displ_uvmat('WARNING',[num2str(nbmissing) ' files skipped: missing files or bad input, see command window display'],checkrun)
441    end
442   
443    %name of result file
444    OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(1),i1_series{1}(end),i_slice,[]);
445    errormsg=struct2nc(OutputFile,DataOut); %save result file
446    if isempty(errormsg)
447        display([OutputFile ' written'])
448    else
449        displ_uvmat('ERROR',['error in Series/struct2nc: ' errormsg],checkrun)
450    end
451end
452
453%% plot the time series (the last one in case of multislices)
454figure
455haxes=axes;
456if checkrun
457plot_field(DataOut,haxes)
458end
459
460%% display the result file using the GUI get_field
461hget_field=findobj(allchild(0),'name','get_field');
462if ~isempty(hget_field)
463    delete(hget_field)
464end
465get_field(OutputFile,DataOut)
466   
467
468
Note: See TracBrowser for help on using the repository browser.