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

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

various bug corrections. Steps further for civ_series (still development needed)

File size: 18.0 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
45if isstruct(Param) && isequal(Param.Action.RUN,0)
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.ProjObject='on';...%can use projection object(option 'off'/'on',
53        ParamOut.Mask='off';...%can use mask option   (option 'off'/'on', 'off' by default)
54        ParamOut.OutputDirExt='.tseries';%set the output dir extension
55    return
56end
57
58%%%%%%%%%%%% STANDARD PART  %%%%%%%%%%%%
59%% read input parameters from an xml file if input is a file name (batch mode)
60checkrun=1;
61if ischar(Param)
62    Param=xml2struct(Param);% read Param as input file (batch case)
63    checkrun=0;
64end
65
66ParamOut=Param; %default output
67OutputDir=[Param.OutputSubDir Param.OutputDirExt];
68
69%% root input file(s) and type
70RootPath=Param.InputTable(:,1);
71RootFile=Param.InputTable(:,3);
72SubDir=Param.InputTable(:,2);
73NomType=Param.InputTable(:,4);
74FileExt=Param.InputTable(:,5);
75[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
76%%%%%%%%%%%%
77% The cell array filecell is the list of input file names, while
78% filecell{iview,fileindex}:
79%        iview: line in the table corresponding to a given file series
80%        fileindex: file index within  the file series,
81% 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
82% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
83%%%%%%%%%%%%
84NbSlice=1;%default
85if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
86    NbSlice=Param.IndexRange.NbSlice;
87end
88nbview=numel(i1_series);%number of input file series (lines in InputTable)
89nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
90nbfield_i=size(i1_series{1},2); %nb of fields for the i index
91nbfield=nbfield_j*nbfield_i; %total number of fields
92nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
93nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
94
95%determine the file type on each line from the first input file
96ImageTypeOptions={'image','multimage','mmreader','video'};
97NcTypeOptions={'netcdf','civx','civdata'};
98for iview=1:nbview
99    if ~exist(filecell{iview,1}','file')
100        displ_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
101        return
102    end
103    [FileType{iview},FileInfo{iview},MovieObject{iview}]=get_file_type(filecell{iview,1});
104    CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
105    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
106    if ~isempty(j1_series{iview})
107        frame_index{iview}=j1_series{iview};
108    else
109        frame_index{iview}=i1_series{iview};
110    end
111end
112
113%% calibration data and timing: read the ImaDoc files
114[XmlData,NbSlice_calib,time,errormsg]=read_multimadoc(RootPath,SubDir,RootFile,FileExt,i1_series,i2_series,j1_series,j2_series);
115if size(time,1)>1
116    diff_time=max(max(diff(time)));
117    if diff_time>0
118        displ_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time)],checkrun)
119    end
120    time=time(1,:);% choose the time data from the first sequence
121end
122
123%% coordinate transform or other user defined transform
124transform_fct=[];%default
125if isfield(Param,'FieldTransform')&&~isempty(Param.FieldTransform.TransformName)
126    addpath(Param.FieldTransform.TransformPath)
127    transform_fct=str2func(Param.FieldTransform.TransformName);
128    rmpath(Param.FieldTransform.TransformPath)
129end
130
131%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
132% EDIT FROM HERE
133
134%% check the validity of  ctinput file types
135if CheckImage{1}
136    FileExtOut='.png'; % write result as .png images for image inputs
137elseif CheckNc{1}
138    FileExtOut='.nc';% write result as .nc files for netcdf inputs
139else
140    displ_uvmat('ERROR',['invalid file type input ' FileType{1}],checkrun)
141    return
142end
143if nbview==2 && ~isequal(CheckImage{1},CheckImage{2})
144    displ_uvmat('ERROR','input must be two image series or two netcdf file series',checkrun)
145    return
146end
147NomTypeOut='_1-2_1';% output file index will indicate the first and last ref index in the series
148if checkrun==1
149    return % stop here for input checks
150end
151
152%% Set field names and velocity types
153InputFields{1}=[];%default (case of images)
154if isfield(Param,'InputFields')
155    InputFields{1}=Param.InputFields;
156end
157if nbview==2
158    InputFields{2}=[];%default (case of images)
159    if isfield(Param,'InputFields')
160        InputFields{2}=Param.InputFields{1};%default
161        if isfield(Param.InputFields,'FieldName_1')
162            InputFields{2}.FieldName=Param.InputFields.FieldName_1;
163            if isfield(Param.InputFields,'VelType_1')
164                InputFields{2}.VelType=Param.InputFields.VelType_1;
165            end
166        end
167    end
168end
169
170%% Initiate output fields
171%initiate the output structure as a copy of the first input one (reproduce fields)
172[DataOut,tild,errormsg] = read_field(filecell{1,1},FileType{1},InputFields{1},1);
173if ~isempty(errormsg)
174    displ_uvmat('ERROR',['error reading ' filecell{1,1} ': ' errormsg],checkrun)
175    return
176end
177time_1=[];
178if isfield(DataOut,'Time')
179    time_1=DataOut.Time(1);
180end
181if CheckNc{iview}
182    if isempty(strcmp('Conventions',DataOut.ListGlobalAttribute))
183        DataOut.ListGlobalAttribute=['Conventions' DataOut.ListGlobalAttribute];
184    end
185    DataOut.Conventions='uvmat';
186    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {Param.Action}];
187    ActionKey='Action';
188    while isfield(DataOut,ActionKey)
189        ActionKey=[ActionKey '_1'];
190    end
191    DataOut.(ActionKey)=Param.Action;
192    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {ActionKey}];
193    if isfield(DataOut,'Time')
194        DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {'Time','Time_end'}];
195    end
196end
197
198nbmissing=0; %number of undetected files
199% for i_slice=1:NbSlice
200%index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
201nbfile=0;
202nbmissing=0;
203
204%%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
205for index=1:nbfield
206    if checkrun
207        stopstate=get(Param.RUNHandle,'BusyAction');
208        update_waitbar(Param.WaitbarHandle,index/nbfield)
209    else
210        stopstate='queue';
211    end
212    if ~isequal(stopstate,'queue')% enable STOP command
213        break
214    end
215    Data=cell(1,nbview);%initiate the set Data;
216    nbtime=0;
217    dt=[];
218    %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
219    for iview=1:nbview
220        % reading input file(s)
221        [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},InputFields{iview},frame_index{iview}(index));
222        if ~isempty(errormsg)
223            errormsg=['time_series / read_field / ' errormsg];
224            display(errormsg)
225            break
226        end
227        if ~isempty(NbSlice_calib)
228            Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
229        end
230    end
231    if isempty(errormsg)
232        Field=Data{1}; % default input field structure
233        % coordinate transform (or other user defined transform)
234        if ~isempty(transform_fct)
235            switch nargin(transform_fct)
236                case 4
237                    if length(Data)==2
238                        Field=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
239                    else
240                        Field=transform_fct(Data{1},XmlData{1});
241                    end
242                case 3
243                    if length(Data)==2
244                        Field=transform_fct(Data{1},XmlData{1},Data{2});
245                    else
246                        Field=transform_fct(Data{1},XmlData{1});
247                    end
248                case 2
249                    Field=transform_fct(Data{1},XmlData{1});
250                case 1
251                    Field=transform_fct(Data{1});
252            end
253        end
254       
255        % calculate tps coefficients if needed
256        if isfield(Param.ProjObject,'ProjMode')&& strcmp(Param.ProjObject.ProjMode,'interp_tps')
257            Field=tps_coeff_field(Field,check_proj_tps);
258        end
259       
260        %field projection on an object
261        if Param.CheckObject
262            [Field,errormsg]=proj_field(Field,Param.ProjObject);
263            if ~isempty(errormsg)
264                msgbox_uvmat('ERROR',['time_series / proj_field / ' errormsg])
265                return
266            end
267        end
268        nbfile=nbfile+1;
269       
270        % initiate the time series at the first iteration
271        if nbfile==1
272            % stop program if the first field reading is in error
273            if ~isempty(errormsg)
274                displ_uvmat('ERROR',['time_series / sub_field / ' errormsg],checkrun)
275                return
276            end
277            DataOut=Field;%default
278            DataOut.NbDim=Field.NbDim+1; %add the time dimension for plots
279            nbvar=length(Field.ListVarName);
280            if nbvar==0
281                displ_uvmat('ERROR','no input variable selected',checkrun)
282                return
283            end
284            testsum=2*ones(1,nbvar);%initiate flag for action on each variable
285            if isfield(Field,'VarAttribute') % look for coordinate and flag variables
286                for ivar=1:nbvar
287                    if length(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'Role')
288                        var_role=Field.VarAttribute{ivar}.Role;%'role' of the variable
289                        if isequal(var_role,'errorflag')
290                            displ_uvmat('ERROR','do not handle error flags in time series',checkrun)
291                            return
292                        end
293                        if isequal(var_role,'warnflag')
294                            testsum(ivar)=0;  % not recorded variable
295                            eval(['DataOut=rmfield(DataOut,''' Field.ListVarName{ivar} ''');']);%remove variable
296                        end
297                        if isequal(var_role,'coord_x')| isequal(var_role,'coord_y')|...
298                                isequal(var_role,'coord_z')|isequal(var_role,'coord')
299                            testsum(ivar)=1; %constant coordinates, record without time evolution
300                        end
301                    end
302                    % check whether the variable ivar is a dimension variable
303                    DimCell=Field.VarDimName{ivar};
304                    if ischar(DimCell)
305                        DimCell={DimCell};
306                    end
307                    if numel(DimCell)==1 && isequal(Field.ListVarName{ivar},DimCell{1})%detect dimension variables
308                        testsum(ivar)=1;
309                    end
310                end
311            end
312            for ivar=1:nbvar
313                if testsum(ivar)==2
314                    eval(['DataOut.' Field.ListVarName{ivar} '=[];'])
315                end
316            end
317            DataOut.ListVarName=[{'Time'} DataOut.ListVarName];
318        end
319       
320        % add data to the current field
321        for ivar=1:length(Field.ListVarName)
322            VarName=Field.ListVarName{ivar};
323            VarVal=Field.(VarName);
324            if testsum(ivar)==2% test for recorded variable
325                if isempty(errormsg)
326                    if isequal(Param.ProjObject.ProjMode,'inside')% take the average in the domain for 'inside' mode
327                        if isempty(VarVal)
328                            displ_uvmat('ERROR',['empty result at frame index ' num2str(i1_series{iview}(index))],checkrun)
329                            return
330                        end
331                        VarVal=mean(VarVal,1);
332                    end
333                    VarVal=shiftdim(VarVal,-1); %shift dimension
334                    DataOut.(VarName)=cat(1,DataOut.(VarName),VarVal);%concanete the current field to the time series
335                else
336                    DataOut.(VarName)=cat(1,DataOut.(VarName),0);% put each variable to 0 in case of input reading error
337                end
338            elseif testsum(ivar)==1% variable representing fixed coordinates
339                VarInit=DataOut.(VarName);
340                if isempty(errormsg) && ~isequal(VarVal,VarInit)
341                    displ_uvmat('ERROR',['time series requires constant coordinates ' VarName],checkrun)
342                    return
343                end
344            end
345        end
346       
347        % record the time:
348        if isempty(time)% time not set by xml filer(s)
349            if isfield(Data{1},'Time')
350                DataOut.Time(nbfile,1)=Field.Time;
351            else
352                DataOut.Time(nbfile,1)=index;%default
353            end
354        else % time from ImaDoc prevails  TODO: correct
355            DataOut.Time(nbfile,1)=time(index);%
356        end
357       
358        % record the number of missing input fields
359        if ~isempty(errormsg)
360            nbmissing=nbmissing+1;
361            display(['index=' num2str(index) ':' errormsg])
362        end
363    end
364   
365end
366%%%%%%% END OF LOOP WITHIN A SLICE
367
368%remove time for global attributes if exists
369Time_index=find(strcmp('Time',DataOut.ListGlobalAttribute));
370if ~isempty(Time_index)
371    DataOut.ListGlobalAttribute(Time_index)=[];
372end
373DataOut.Conventions='uvmat';
374for ivar=1:numel(DataOut.ListVarName)
375    VarName=DataOut.ListVarName{ivar};
376    eval(['DataOut.' VarName '=squeeze(DataOut.' VarName ');']) %remove singletons
377end
378
379% add time dimension
380for ivar=1:length(Field.ListVarName)
381    DimCell=Field.VarDimName(ivar);
382    if testsum(ivar)==2%variable used as time series
383        DataOut.VarDimName{ivar}=[{'Time'} DimCell];
384    elseif testsum(ivar)==1
385        DataOut.VarDimName{ivar}=DimCell;
386    end
387end
388indexremove=find(~testsum);
389if ~isempty(indexremove)
390    DataOut.ListVarName(1+indexremove)=[];
391    DataOut.VarDimName(indexremove)=[];
392    if isfield(DataOut,'Role') && ~isempty(DataOut.Role{1})%generaliser aus autres attributs
393        DataOut.Role(1+indexremove)=[];
394    end
395end
396
397%shift variable attributes
398if isfield(DataOut,'VarAttribute')
399    DataOut.VarAttribute=[{[]} DataOut.VarAttribute];
400end
401DataOut.VarDimName=[{'Time'} DataOut.VarDimName];
402DataOut.Action=Param.Action;%name of the processing programme
403test_time=diff(DataOut.Time)>0;% test that the readed time is increasing (not constant)
404if ~test_time
405    DataOut.Time=1:filecounter;
406end
407
408% display nbmissing
409if ~isequal(nbmissing,0)
410    displ_uvmat('WARNING',[num2str(nbmissing) ' files skipped: missing files or bad input, see command window display'],checkrun)
411end
412
413%name of result file
414OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(1),i1_series{1}(end),i_slice,[]);
415errormsg=struct2nc(OutputFile,DataOut); %save result file
416if isempty(errormsg)
417    display([OutputFile ' written'])
418else
419    displ_uvmat('ERROR',['error in Series/struct2nc: ' errormsg],checkrun)
420end
421
422
423%% plot the time series (the last one in case of multislices)
424if checkrun
425    figure
426    haxes=axes;
427    plot_field(DataOut,haxes)
428   
429    %% display the result file using the GUI get_field
430    hget_field=findobj(allchild(0),'name','get_field');
431    if ~isempty(hget_field)
432        delete(hget_field)
433    end
434    get_field(OutputFile,DataOut)
435end
436
437
Note: See TracBrowser for help on using the repository browser.