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

Last change on this file since 767 was 751, checked in by sommeria, 11 years ago

add aver_synchro (field analysis at different frequencies) and turb_stat

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