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

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

adpat uvmat to reading data from rdvision

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