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

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

merge_proj updated to account for new format in field transform (variable nbre of input parma)

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