source: trunk/src/series/aver_stat.m @ 869

Last change on this file since 869 was 869, checked in by sommeria, 6 years ago

bug_repaired

File size: 16.8 KB
Line 
1%'aver_stat': calculate field average over a time series
2%------------------------------------------------------------------------
3% function ParamOut=aver_stat(Param)
4%
5%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
6%
7%OUTPUT
8% ParamOut: sets options in the GUI series.fig needed for the function
9%
10%INPUT:
11% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
12% In batch mode, Param is the name of the corresponding xml file containing the same information
13% when Param.Action.RUN=0 (as activated when the current Action is selected
14% in series), the function ouput paramOut set the activation of the needed GUI elements
15%
16% Param contains the elements:(use the menu bar command 'export/GUI config' in series to
17% see the current structure Param)
18%    .InputTable: cell of input file names, (several lines for multiple input)
19%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
20%    .OutputSubDir: name of the subdirectory for data outputs
21%    .OutputDirExt: directory extension for data outputs
22%    .Action: .ActionName: name of the current activated function
23%             .ActionPath:   path of the current activated function
24%             .ActionExt: fct extension ('.m', Matlab fct, '.sh', compiled   Matlab fct
25%             .RUN =0 for GUI input, =1 for function activation
26%             .RunMode='local','background', 'cluster': type of function  use
27%             
28%    .IndexRange: set the file or frame indices on which the action must be performed
29%    .FieldTransform: .TransformName: name of the selected transform function
30%                     .TransformPath:   path  of the selected transform function
31%    .InputFields: sub structure describing the input fields withfields
32%              .FieldName: name(s) of the field
33%              .VelType: velocity type
34%              .FieldName_1: name of the second field in case of two input series
35%              .VelType_1: velocity type of the second field in case of two input series
36%              .Coord_y: name of y coordinate variable
37%              .Coord_x: name of x coordinate variable
38%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
39%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40
41%=======================================================================
42% Copyright 2008-2014, LEGI UMR 5519 / CNRS UJF G-INP, Grenoble, France
43%   http://www.legi.grenoble-inp.fr
44%   Joel.Sommeria - Joel.Sommeria (A) legi.cnrs.fr
45%
46%     This file is part of the toolbox UVMAT.
47%
48%     UVMAT is free software; you can redistribute it and/or modify
49%     it under the terms of the GNU General Public License as published
50%     by the Free Software Foundation; either version 2 of the license,
51%     or (at your option) any later version.
52%
53%     UVMAT is distributed in the hope that it will be useful,
54%     but WITHOUT ANY WARRANTY; without even the implied warranty of
55%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
56%     GNU General Public License (see LICENSE.txt) for more details.
57%=======================================================================
58
59function ParamOut=aver_stat(Param)
60
61%% set the input elements needed on the GUI series when the action is selected in the menu ActionName
62if isstruct(Param) && isequal(Param.Action.RUN,0)% function activated from the GUI series but not RUN
63    ParamOut.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
64    ParamOut.WholeIndexRange='off';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
65    ParamOut.NbSlice='on'; %nbre of slices ('off' by default)
66    ParamOut.VelType='two';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
67    ParamOut.FieldName='two';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
68    ParamOut.FieldTransform = 'on';%can use a transform function
69    ParamOut.ProjObject='on';%can use projection object(option 'off'/'on',
70    ParamOut.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
71    ParamOut.OutputDirExt='.stat';%set the output dir extension
72    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
73    % check the existence of the first file in the series
74    first_j=[];
75    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
76    last_j=[];
77    if isfield(Param.IndexRange,'last_j'); last_j=Param.IndexRange.last_j; end
78    PairString='';
79    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
80    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
81    FirstFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
82        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
83    if ~exist(FirstFileName,'file')
84        msgbox_uvmat('WARNING',['the first input file ' FirstFileName ' does not exist'])
85    else
86        [i1,i2,j1,j2] = get_file_index(Param.IndexRange.last_i,last_j,PairString);
87        LastFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
88        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
89        if ~exist(FirstFileName,'file')
90             msgbox_uvmat('WARNING',['the last input file ' LastFileName ' does not exist'])
91        end
92    end
93    return
94end
95
96%%%%%%%%%%%%  STANDARD PART  %%%%%%%%%%%%
97ParamOut=[];%default output
98%% read input parameters from an xml file if input is a file name (batch mode)
99checkrun=1;
100if ischar(Param)
101    Param=xml2struct(Param);% read Param as input file (batch case)
102    checkrun=0;
103end
104hseries=findobj(allchild(0),'Tag','series');
105RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
106WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
107
108%% define the directory for result file (with path=RootPath{1})
109OutputDir=[Param.OutputSubDir Param.OutputDirExt];
110   
111%% root input file(s) name, type and index series
112RootPath=Param.InputTable(:,1);
113RootFile=Param.InputTable(:,3);
114SubDir=Param.InputTable(:,2);
115NomType=Param.InputTable(:,4);
116FileExt=Param.InputTable(:,5);
117hdisp=disp_uvmat('WAITING...','checking the file series',checkrun);
118[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
119if ~isempty(hdisp),delete(hdisp),end;
120%%%%%%%%%%%%
121% The cell array filecell is the list of input file names, while
122% filecell{iview,fileindex}:
123%        iview: line in the table corresponding to a given file series
124%        fileindex: file index within  the file series,
125% 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
126% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
127%%%%%%%%%%%%
128NbView=numel(i1_series);%number of input file series (lines in InputTable)
129NbField_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
130NbField_i=size(i1_series{1},2); %nb of fields for the i index
131NbField=NbField_j*NbField_i; %total number of fields
132
133%% determine the file type on each line from the first input file
134ImageTypeOptions={'image','multimage','mmreader','video'};
135NcTypeOptions={'netcdf','civx','civdata'};
136for iview=1:NbView
137    if ~exist(filecell{iview,1}','file')
138        disp_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
139        return
140    end
141    [FileInfo{iview},MovieObject{iview}]=get_file_info(filecell{iview,1});
142    FileType{iview}=FileInfo{iview}.FileType;
143    CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
144    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
145    if ~isempty(j1_series{iview})
146        frame_index{iview}=j1_series{iview};
147    else
148        frame_index{iview}=i1_series{iview};
149    end
150end
151
152%% calibration data and timing: read the ImaDoc files
153[XmlData,NbSlice_calib,time,errormsg]=read_multimadoc(RootPath,SubDir,RootFile,FileExt,i1_series,i2_series,j1_series,j2_series);
154if size(time,1)>1
155    diff_time=max(max(diff(time)));
156    if diff_time>0
157        disp_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time)],checkrun)
158    end   
159end
160
161%% coordinate transform or other user defined transform
162transform_fct='';%default
163if isfield(Param,'FieldTransform')&&~isempty(Param.FieldTransform.TransformName)
164    addpath(Param.FieldTransform.TransformPath)
165    transform_fct=str2func(Param.FieldTransform.TransformName);
166    rmpath(Param.FieldTransform.TransformPath)
167end
168
169%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
170 % EDIT FROM HERE
171
172%% check the validity of  input file types
173if CheckImage{1}
174    FileExtOut='.png'; % write result as .png images for image inputs
175elseif CheckNc{1}
176    FileExtOut='.nc';% write result as .nc files for netcdf inputs
177else
178    disp_uvmat('ERROR',['invalid file type input ' FileType{1}],checkrun)
179    return
180end
181if NbView==2 && ~isequal(CheckImage{1},CheckImage{2})
182    disp_uvmat('ERROR','input must be two image series or two netcdf file series',checkrun)
183    return
184end
185
186%% settings for the output file
187NomTypeOut=nomtype2pair(NomType{1});% determine the index nomenclature type for the output file
188first_i=i1_series{1}(1);
189last_i=i1_series{1}(end);
190if isempty(j1_series{1})% if there is no second index j
191    first_j=1;last_j=1;
192else
193    first_j=j1_series{1}(1);
194    last_j=j1_series{1}(end);
195end
196
197%% Set field names and velocity types
198InputFields{1}=[];%default (case of images)
199if NbView==2
200    InputFields{2}=[];%default (case of images)
201end
202if isfield(Param,'InputFields')
203    InputFields{1}=Param.InputFields;
204    if NbView==2
205        InputFields{2}=Param.InputFields;%default
206        if isfield(Param.InputFields,'FieldName_1')
207            InputFields{2}.FieldName=Param.InputFields.FieldName_1;
208            if isfield(Param.InputFields,'VelType_1')
209                InputFields{2}.VelType=Param.InputFields.VelType_1;
210            end
211        end
212    end
213end
214% for i_slice=1:NbSlice
215% index_slice=i_slice:NbSlice:nbfield;% select file indices of the slice
216nbfiles=0;
217% nbmissing=0;
218
219%%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
220for index=1:NbField
221    update_waitbar(WaitbarHandle,index/NbField)
222    if ~isempty(RUNHandle)&& ~strcmp(get(RUNHandle,'BusyAction'),'queue')
223        disp('program stopped by user')
224        break
225    end
226   
227    %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
228    for iview=1:NbView
229        % reading input file(s)
230        [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},InputFields{iview},frame_index{iview}(index));
231        if ~isempty(errormsg)
232            errormsg=['error of input reading: ' errormsg];
233            break
234        end
235        if ~isempty(NbSlice_calib)
236            Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
237        end
238    end
239    %%%%%%%%%%%%%%%% end loop on views (input lines) %%%%%%%%%%%%%%%%
240    %%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
241    % EDIT FROM HERE
242   
243    if isempty(errormsg)
244        Field=Data{1}; % default input field structure
245        %% coordinate transform (or other user defined transform)
246        if ~isempty(transform_fct)
247            switch nargin(transform_fct)
248                case 4
249                    if length(Data)==2
250                        Field=transform_fct(Data{1},XmlData{1},Data{2},XmlData{2});
251                    else
252                        Field=transform_fct(Data{1},XmlData{1});
253                    end
254                case 3
255                    if length(Data)==2
256                        Field=transform_fct(Data{1},XmlData{1},Data{2});
257                    else
258                        Field=transform_fct(Data{1},XmlData{1});
259                    end
260                case 2
261                    Field=transform_fct(Data{1},XmlData{1});
262                case 1
263                    Field=transform_fct(Data{1});
264            end
265        end
266       
267        %% calculate tps coefficients if needed
268        if isfield(Param,'ProjObject')&&isfield(Param.ProjObject,'ProjMode')&& strcmp(Param.ProjObject.ProjMode,'interp_tps')
269            Field=tps_coeff_field(Field,check_proj_tps);
270        end
271       
272        %field projection on an object
273        if Param.CheckObject
274            [Field,errormsg]=proj_field(Field,Param.ProjObject);
275            if ~isempty(errormsg)
276                disp_uvmat('ERROR',['error in aver_stat/proj_field:' errormsg],checkrun)
277                return
278            end
279        end
280        nbfiles=nbfiles+1;
281       
282        %%%%%%%%%%%% MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
283        if nbfiles==1 %first field
284            time_1=[];
285            if isfield(Field,'Time')
286                time_1=Field.Time(1);
287            end
288            DataOut=Field;%default
289            DataOut.Conventions='uvmat'; %suppress Conventions='uvmat/civdata' for civ input files
290            errorvar=zeros(numel(Field.ListVarName));%index of errorflag associated to each variable
291            for ivar=1:numel(Field.ListVarName)
292                VarName=Field.ListVarName{ivar};
293                DataOut.(VarName)=zeros(size(DataOut.(VarName)));% initiate each field to zero
294                NbData.(VarName)=zeros(size(DataOut.(VarName)));% initiate the nbre of good data to zero
295                for iivar=1:length(Field.VarAttribute)
296                    if isequal(Field.VarDimName{iivar},Field.VarDimName{ivar})&& isfield(Field.VarAttribute{iivar},'Role')...
297                            && strcmp(Field.VarAttribute{iivar}.Role,'errorflag')
298                        errorvar(ivar)=iivar; % index of the errorflag variable corresponding to ivar
299                    end
300                end
301            end
302            DataOut.ListVarName(errorvar(errorvar~=0))=[]; %remove errorflag from result
303            DataOut.VarDimName(errorvar(errorvar~=0))=[]; %remove errorflag from result
304            DataOut.VarAttribute(errorvar(errorvar~=0))=[]; %remove errorflag from result
305        end   %current field
306        for ivar=1:length(DataOut.ListVarName)
307            VarName=Field.ListVarName{ivar};
308            sizmean=size(DataOut.(VarName));
309            siz=size(Field.(VarName));
310            if ~isequal(DataOut.(VarName),0)&& ~isequal(siz,sizmean)
311                disp_uvmat('ERROR',['unequal size of input field ' VarName ', need to project  on a grid'],checkrun)
312                return
313            else
314                if errorvar(ivar)==0
315                    check_bad=isnan(Field.(VarName));%=0 for NaN data values, 1 else
316                else
317                    check_bad=isnan(Field.(VarName)) | Field.(Field.ListVarName{errorvar(ivar)})~=0;%=0 for NaN or error flagged data values, 1 else
318                end
319                Field.(VarName)(check_bad)=0; %set to zero NaN or data marked by error flag
320                DataOut.(VarName)=DataOut.(VarName)+ double(Field.(VarName)); % update the sum
321                NbData.(VarName)=NbData.(VarName)+ ~check_bad;% records the number of data for each point
322            end
323        end
324        %%%%%%%%%%%%   END MAIN RUNNING OPERATIONS  %%%%%%%%%%%%
325    else
326        disp(errormsg)
327    end
328end
329%%%%%%%%%%%%%%%% end loop on field indices %%%%%%%%%%%%%%%%
330
331for ivar=1:length(Field.ListVarName)
332    VarName=Field.ListVarName{ivar};
333    DataOut.(VarName)=DataOut.(VarName)./NbData.(VarName); % normalize the mean
334end
335nbmissing=NbField-nbfiles;
336if nbmissing~=0
337    disp_uvmat('WARNING',[num2str(nbmissing) ' input files are missing or skipted'],checkrun)
338end
339if isempty(time) % time is read from files
340    if isfield(Field,'Time')
341        time_end=Field.Time(1);%last time read
342        if ~isempty(time_1)
343            DataOut.Time=time_1;
344            DataOut.Time_end=time_end;
345        end
346    end
347else  % time from ImaDoc prevails if it exists
348    DataOut.Time=time(1);
349    DataOut.Time_end=time(end);
350end
351
352%% writing the result file
353OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,first_i,last_i,first_j,last_j);
354if CheckImage{1} %case of images
355    if isequal(FileInfo{1}.BitDepth,16)||(numel(FileInfo)==2 &&isequal(FileInfo{2}.BitDepth,16))
356        DataOut.A=uint16(DataOut.A);
357        imwrite(DataOut.A,OutputFile,'BitDepth',16); % case of 16 bit images
358    else
359        DataOut.A=uint8(DataOut.A);
360        imwrite(DataOut.A,OutputFile,'BitDepth',8); % case of 16 bit images
361    end
362    disp([OutputFile ' written']);
363else %case of netcdf input file , determine global attributes
364    errormsg=struct2nc(OutputFile,DataOut); %save result file
365    if isempty(errormsg)
366        disp([OutputFile ' written']);
367    else
368        disp(['error in writting result file: ' errormsg])
369    end
370end  % end averaging  loop
371
372%% open the result file with uvmat (in RUN mode)
373if checkrun
374    uvmat(OutputFile)% open the last result file with uvmat
375end
Note: See TracBrowser for help on using the repository browser.