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

Last change on this file since 768 was 768, checked in by sommeria, 10 years ago

bug corrected for civ2 with dt2 non equal to Dt1
cleaning of time_series

File size: 20.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 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'};
115FileType=cell(1,nbview);
116FileInfo=cell(1,nbview);
117MovieObject=cell(1,nbview);
118CheckImage=cell(1,nbview);
119CheckNc=cell(1,nbview);
120frame_index=cell(1,nbview);
121for iview=1:nbview
122    if ~exist(filecell{iview,1}','file')
123        disp_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
124        return
125    end
126    [FileType{iview},FileInfo{iview},MovieObject{iview}]=get_file_type(filecell{iview,1});
127    if strcmp(FileType{iview},'civdata')||strcmp(FileType{iview},'civx')
128        if ~isfield(Param.InputFields,'VelType')
129            FileType{iview}='netcdf';% civ data read as usual netcdf files
130        end
131    end
132    CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
133    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
134    if isempty(j1_series{iview})
135        frame_index{iview}=i1_series{iview};
136    else
137        frame_index{iview}=j1_series{iview};
138    end
139end
140
141%% calibration data and timing: read the ImaDoc files
142[XmlData,NbSlice_calib,time,errormsg]=read_multimadoc(RootPath,SubDir,RootFile,FileExt,i1_series,i2_series,j1_series,j2_series);
143if ~isempty(errormsg)
144    disp_uvmat('ERROR',['error in reading xmlfile: ' errormsg],checkrun)
145    return
146end
147if size(time,1)>1
148    diff_time=max(max(diff(time)));
149    if diff_time>0
150        disp_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time)],checkrun)
151    end
152    time=time(1,:);% choose the time data from the first sequence
153end
154
155%% coordinate transform or other user defined transform
156transform_fct=[];%default
157if isfield(Param,'FieldTransform')&&~isempty(Param.FieldTransform.TransformName)
158    addpath(Param.FieldTransform.TransformPath)
159    transform_fct=str2func(Param.FieldTransform.TransformName);
160    rmpath(Param.FieldTransform.TransformPath)
161end
162
163%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
164% EDIT FROM HERE
165
166%% check the validity of  the input file types
167if ~CheckImage{1}&&~CheckNc{1}
168    disp_uvmat('ERROR',['invalid file type input ' FileType{1}],checkrun)
169    return
170end
171if nbview==2 && ~isequal(CheckImage{1},CheckImage{2})
172    disp_uvmat('ERROR','input must be two image series or two netcdf file series',checkrun)
173    return
174end
175
176%% settings for the output file
177FileExtOut='.nc';% write result as .nc files for netcdf inputs
178NomTypeOut=nomtype2pair(NomType{1});% determine the index nomenclature type for the output file
179first_i=i1_series{1}(1);
180last_i=i1_series{1}(end);
181if isempty(j1_series{1})% if there is no second index j
182    first_j=1;last_j=1;
183else
184    first_j=j1_series{1}(1);
185    last_j=j1_series{1}(end);
186end
187
188%% Set field names and velocity types
189InputFields{1}=[];%default (case of images)
190if isfield(Param,'InputFields')
191    InputFields{1}=Param.InputFields;
192end
193if nbview==2
194    InputFields{2}=[];%default (case of images)
195    if isfield(Param,'InputFields')
196        InputFields{2}=Param.InputFields{1};%default
197        if isfield(Param.InputFields,'FieldName_1')
198            InputFields{2}.FieldName=Param.InputFields.FieldName_1;
199            if isfield(Param.InputFields,'VelType_1')
200                InputFields{2}.VelType=Param.InputFields.VelType_1;
201            end
202        end
203    end
204end
205
206%% Initiate output fields
207%initiate the output structure as a copy of the first input one (reproduce fields)
208[DataOut,tild,errormsg] = read_field(filecell{1,1},FileType{1},InputFields{1},1);
209if ~isempty(errormsg)
210    disp_uvmat('ERROR',['error reading ' filecell{1,1} ': ' errormsg],checkrun)
211    return
212end
213time_1=[];
214if isfield(DataOut,'Time')
215    time_1=DataOut.Time(1);
216end
217if CheckNc{iview}
218    if isempty(strcmp('Conventions',DataOut.ListGlobalAttribute))
219        DataOut.ListGlobalAttribute=['Conventions' DataOut.ListGlobalAttribute];
220    end
221    DataOut.Conventions='uvmat';
222    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {Param.Action}];
223    ActionKey='Action';
224    while isfield(DataOut,ActionKey)
225        ActionKey=[ActionKey '_1'];
226    end
227    DataOut.(ActionKey)=Param.Action;
228    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {ActionKey}];
229    if isfield(DataOut,'Time')
230        DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {'Time','Time_end'}];
231    end
232end
233
234nbmissing=0; %number of undetected files
235% for i_slice=1:NbSlice
236%index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
237nbfile=0;
238nbmissing=0;
239
240%%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
241for index=1:nbfield
242            update_waitbar(WaitbarHandle,index/nbfield)
243    if ~isempty(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
244        disp('program stopped by user')
245        break % leave the loop if stop is ordered
246    end
247    Data=cell(1,nbview);%initiate the set Data;
248    nbtime=0;
249    dt=[];
250    %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
251    for iview=1:nbview
252        % reading input file(s)
253        [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},InputFields{iview},frame_index{iview}(index));
254        if ~isempty(errormsg)
255            errormsg=['time_series / read_field / ' errormsg];
256            display(errormsg)
257            break
258        end
259        if ~isempty(NbSlice_calib)
260            Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
261        end
262    end
263    if isempty(errormsg)
264        Field=Data{1}; % default input field structure
265        % coordinate transform (or other user defined transform)
266        if ~isempty(transform_fct)
267            switch nargin(transform_fct)
268                case 4
269                    if length(Data)==2
270                        Field=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
271                    else
272                        Field=transform_fct(Data{1},XmlData{1});
273                    end
274                case 3
275                    if length(Data)==2
276                        Field=transform_fct(Data{1},XmlData{1},Data{2});
277                    else
278                        Field=transform_fct(Data{1},XmlData{1});
279                    end
280                case 2
281                    Field=transform_fct(Data{1},XmlData{1});
282                case 1
283                    Field=transform_fct(Data{1});
284            end
285        end
286       
287        %field projection on an object
288        if Param.CheckObject
289            % calculate tps coefficients if needed
290            if isfield(Param.ProjObject,'ProjMode')&& strcmp(Param.ProjObject.ProjMode,'interp_tps')
291                Field=tps_coeff_field(Field,check_proj_tps);
292            end
293            [Field,errormsg]=proj_field(Field,Param.ProjObject);
294            if ~isempty(errormsg)
295                msgbox_uvmat('ERROR',['time_series / proj_field / ' errormsg])
296                return
297            end
298        end
299        nbfile=nbfile+1;
300       
301        % initiate the time series at the first iteration
302        if nbfile==1
303            % stop program if the first field reading is in error
304            if ~isempty(errormsg)
305                disp_uvmat('ERROR',['time_series / sub_field / ' errormsg],checkrun)
306                return
307            end
308            DataOut=Field;%default
309%             DataOut.NbDim=Field.NbDim+1; %add the time dimension for plots
310            nbvar=length(Field.ListVarName);
311            if nbvar==0
312                disp_uvmat('ERROR','no input variable selected',checkrun)
313                return
314            end
315            testsum=2*ones(1,nbvar);%initiate flag for action on each variable
316            if isfield(Field,'VarAttribute') % look for coordinate and flag variables
317                for ivar=1:nbvar
318                    if length(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'Role')
319                        var_role=Field.VarAttribute{ivar}.Role;%'role' of the variable
320                        if isequal(var_role,'errorflag')
321                            disp_uvmat('ERROR','do not handle error flags in time series',checkrun)
322                            return
323                        end
324                        if isequal(var_role,'warnflag')
325                            testsum(ivar)=0;  % not recorded variable
326                            eval(['DataOut=rmfield(DataOut,''' Field.ListVarName{ivar} ''');']);%remove variable
327                        end
328                        if strcmp(var_role,'coord_x')||strcmp(var_role,'coord_y')||strcmp(var_role,'coord_z')||strcmp(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 Param.CheckObject && strcmp(Param.ProjObject.ProjMode,'inside')% take the average in the domain for 'inside' projection mode
357                        if isempty(VarVal)
358                            disp_uvmat('ERROR',['empty result at frame index ' num2str(i1_series{iview}(index))],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                VarInit=DataOut.(VarName);
370                if isempty(errormsg) && ~isequal(VarVal,VarInit)
371                    disp_uvmat('ERROR',['time series requires constant coordinates ' VarName ': use projection mode interp'],checkrun)
372                    return
373                end
374            end
375        end
376       
377        % record the time:
378        if isempty(time)% time not set by xml filer(s)
379            if isfield(Data{1},'Time')
380                DataOut.Time(nbfile,1)=Field.Time;
381            else
382                DataOut.Time(nbfile,1)=index;%default
383            end
384        else % time from ImaDoc prevails  TODO: correct
385            DataOut.Time(nbfile,1)=time(index);%
386        end
387       
388        % record the number of missing input fields
389        if ~isempty(errormsg)
390            nbmissing=nbmissing+1;
391            display(['index=' num2str(index) ':' errormsg])
392        end
393    end
394   
395end
396%%%%%%% END OF LOOP WITHIN A SLICE
397
398%remove time for global attributes if exists
399Time_index=find(strcmp('Time',DataOut.ListGlobalAttribute));
400if ~isempty(Time_index)
401    DataOut.ListGlobalAttribute(Time_index)=[];
402end
403DataOut.Conventions='uvmat';
404for ivar=1:numel(DataOut.ListVarName)
405    VarName=DataOut.ListVarName{ivar};
406    eval(['DataOut.' VarName '=squeeze(DataOut.' VarName ');']) %remove singletons
407end
408
409% add time dimension
410for ivar=1:length(Field.ListVarName)
411    DimCell=Field.VarDimName{ivar};
412    if ischar(DimCell),DimCell={DimCell};end
413    if testsum(ivar)==2% variable for which time series is calculated
414        DataOut.VarDimName{ivar}=[{'Time'} DimCell];
415    elseif testsum(ivar)==1 % variable represneting a fixed coordinate
416        DataOut.VarDimName{ivar}=DimCell;
417    end
418end
419indexremove=find(~testsum);
420if ~isempty(indexremove)
421    DataOut.ListVarName(1+indexremove)=[];
422    DataOut.VarDimName(indexremove)=[];
423    if isfield(DataOut,'Role') && ~isempty(DataOut.Role{1})%generaliser aus autres attributs
424        DataOut.Role(1+indexremove)=[];
425    end
426end
427
428%shift variable attributes
429if isfield(DataOut,'VarAttribute')
430    DataOut.VarAttribute=[{[]} DataOut.VarAttribute];
431end
432DataOut.VarDimName=[{'Time'} DataOut.VarDimName];
433DataOut.Action=Param.Action;%name of the processing programme
434test_time=diff(DataOut.Time)>0;% test that the readed time is increasing (not constant)
435if ~test_time
436    DataOut.Time=1:nbfield;
437end
438
439% display nbmissing
440if ~isequal(nbmissing,0)
441    disp_uvmat('WARNING',[num2str(nbmissing) ' files skipped: missing files or bad input, see command window display'],checkrun)
442end
443
444%% name of result file
445OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,first_i,last_i,first_j,last_j);
446errormsg=struct2nc(OutputFile,DataOut); %save result file
447if isempty(errormsg)
448    display([OutputFile ' written'])
449else
450    disp_uvmat('ERROR',['error in Series/struct2nc: ' errormsg],checkrun)
451end
452
453%% plot the time series (the last one in case of multislices)
454if checkrun
455    figure
456    haxes=axes;
457    plot_field(DataOut,haxes)
458   
459    %% display the result file using the GUI get_field
460    hget_field=findobj(allchild(0),'name','get_field');
461    if ~isempty(hget_field)
462        delete(hget_field)
463    end
464    get_field(OutputFile,DataOut)
465end
466
467
Note: See TracBrowser for help on using the repository browser.