source: trunk/src/series/check_peaklock.m @ 783

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

-pb of mulitple tiff reading solved
-modif of output parma in get-file_type and find_file_series

  • introduction of transform/ima_noise_rms
File size: 25.9 KB
Line 
1% 'check_peaklocking': estimte peaklocking error in a civ field series TODO: UPDATE
2%------------------------------------------------------------------------
3% function ParamOut=check_peaklocking(Param)
4%
5%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
6%
7% This function is used in four modes by the GUI series:
8%           1) config GUI: with no input argument, the function determine the suitable GUI configuration
9%           2) interactive input: the function is used to interactively introduce input parameters, and then stops
10%           3) RUN: the function itself runs, when an appropriate input  structure Param has been introduced.
11%           4) BATCH: the function itself proceeds in BATCH mode, using an xml file 'Param' as input.
12%
13% This function is used in four modes by the GUI series:
14%           1) config GUI: with no input argument, the function determine the suitable GUI configuration
15%           2) interactive input: the function is used to interactively introduce input parameters, and then stops
16%           3) RUN: the function itself runs, when an appropriate input  structure Param has been introduced.
17%           4) BATCH: the function itself proceeds in BATCH mode, using an xml file 'Param' as input.
18%
19%OUTPUT
20% GUI_input=list of options in the GUI series.fig needed for the function
21%
22%INPUT:
23% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
24% In batch mode, Param is the name of the corresponding xml file containing the same information
25% In the absence of input (as activated when the current Action is selected
26% in series), the function ouput GUI_input set the activation of the needed GUI elements
27%
28% Param contains the elements:(use the menu bar command 'export/GUI config' in series to see the current structure Param)
29%    .InputTable: cell of input file names, (several lines for multiple input)
30%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
31%    .OutputSubDir: name of the subdirectory for data outputs
32%    .OutputDirExt: directory extension for data outputs
33%    .Action: .ActionName: name of the current activated function
34%             .ActionPath:   path of the current activated function
35%    .IndexRange: set the file or frame indices on which the action must be performed
36%    .FieldTransform: .TransformName: name of the selected transform function
37%                     .TransformPath:   path  of the selected transform function
38%                     .TransformHandle: corresponding function handle
39%    .InputFields: sub structure describing the input fields withfields
40%              .FieldName: name of the field
41%              .VelType: velocity type
42%              .FieldName_1: name of the second field in case of two input series
43%              .VelType_1: velocity type of the second field in case of two input series
44%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
45%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
46function  ParamOut=check_peaklocking(Param)
47
48%% set the input elements needed on the GUI series when the action is selected in the menu ActionName
49if ~exist('Param','var') % case with no input parameter
50    ParamOut={'AllowInputSort';'off';...% allow alphabetic sorting of the list of input files (options 'off'/'on', 'off' by default)
51        'WholeIndexRange';'off';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
52        'NbSlice';'on'; ...%nbre of slices ('off' by default)
53        'VelType';'two';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
54        'FieldName';'off';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
55        'FieldTransform'; 'off';...%can use a transform function
56        'ProjObject';'on';...%can use projection object(option 'off'/'on',
57        'Mask';'off';...%can use mask option   (option 'off'/'on', 'off' by default)
58        'OutputDirExt';'.pklock';...%set the output dir extension
59               ''};
60        return
61end
62
63%%%%%%%%%%%% STANDARD PART  %%%%%%%%%%%%
64%% select different modes,  RUN, parameter input, BATCH
65% BATCH  case: read the xml file for batch case
66if ischar(Param)
67        Param=xml2struct(Param);
68        checkrun=0;
69% RUN case: parameters introduced as the input structure Param
70else
71    hseries=guidata(Param.hseries);%handles of the GUI series
72    if isfield(Param,'Specific')&& strcmp(Param.Specific,'?')
73        checkrun=1;% will only search interactive input parameters (preparation of BATCH mode)
74    else
75        checkrun=2; % indicate the RUN option is used
76    end
77end
78ParamOut=Param; %default output
79OutputDir=[Param.OutputSubDir Param.OutputDirExt];
80
81%% root input file(s) and type
82RootPath=Param.InputTable(:,1);
83RootFile=Param.InputTable(:,3);
84SubDir=Param.InputTable(:,2);
85NomType=Param.InputTable(:,4);
86FileExt=Param.InputTable(:,5);
87[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
88%%%%%%%%%%%%
89% The cell array filecell is the list of input file names, while
90% filecell{iview,fileindex}:
91%        iview: line in the table corresponding to a given file series
92%        fileindex: file index within  the file series,
93% 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
94% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
95%%%%%%%%%%%%
96NbSlice=1;%default
97if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
98    NbSlice=Param.IndexRange.NbSlice;
99end
100nbview=1;%number of input file series (lines in InputTable)
101nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
102nbfield_i=size(i1_series{1},2); %nb of fields for the i index
103nbfield=nbfield_j*nbfield_i; %total number of fields
104nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
105nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
106
107%determine the file type on each line from the first input file
108ImageTypeOptions={'image','multimage','mmreader','video'};
109NcTypeOptions={'netcdf','civx','civdata'};
110for iview=1:nbview
111    if ~exist(filecell{iview,1}','file')
112        disp_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
113        return
114    end
115    [FileInfo{iview},MovieObject{iview}]=get_file_type(filecell{iview,1});
116    FileType{iview}=FileInfo{iview}.FileType;
117    CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
118    CheckNc{iview}=~isempty(find(strcmp(FileType{iview},NcTypeOptions)));% =1 for netcdf files
119    if ~isempty(j1_series{iview})
120        frame_index{iview}=j1_series{iview};
121    else
122        frame_index{iview}=i1_series{iview};
123    end
124end
125
126%% calibration data and timing: read the ImaDoc files
127%none
128
129%% coordinate transform or other user defined transform
130% none
131
132%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
133 % EDIT FROM HERE
134
135%% check the validity of  ctinput file types
136%none
137
138%% Set field names and velocity types
139InputFields{1}=[];%default (case of images)
140if isfield(Param,'InputFields')
141    InputFields{1}=Param.InputFields;
142end
143% only one input fieldseries
144
145%% Initiate output fields
146%initiate the output structure as a copy of the first input one (reproduce fields)
147[DataOut,tild,errormsg] = read_field(filecell{1,1},FileType{1},InputFields{1},1);
148if ~isempty(errormsg)
149    disp_uvmat('ERROR',['error reading ' filecell{1,1} ': ' errormsg],checkrun)
150    return
151end
152time_1=[];
153if isfield(DataOut,'Time')
154    time_1=DataOut.Time(1);
155end
156if CheckNc{iview}
157    if isempty(strcmp('Conventions',DataOut.ListGlobalAttribute))
158        DataOut.ListGlobalAttribute=['Conventions' DataOut.ListGlobalAttribute];
159    end
160    DataOut.Conventions='uvmat';
161    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {Param.Action}];
162    ActionKey='Action';
163    while isfield(DataOut,ActionKey)
164        ActionKey=[ActionKey '_1'];
165    end
166    DataOut.(ActionKey)=Param.Action;
167    DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {ActionKey}];
168    if isfield(DataOut,'Time')
169        DataOut.ListGlobalAttribute=[DataOut.ListGlobalAttribute {'Time','Time_end'}];
170    end
171end
172
173%%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
174index_slice=1:nbfield;% select the file indices
175for index=index_slice
176    if checkrun
177        update_waitbar(hseries.Waitbar,index/(nbfield))
178        stopstate=get(hseries.RUN,'BusyAction');
179    else
180        stopstate='queue';
181    end
182    if isequal(stopstate,'queue')% enable STOP command
183        Data=cell(1,nbview);%initiate the set Data;
184        nbtime=0;
185        dt=[];
186        %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
187        for iview=1:nbview
188            % reading input file(s)
189            [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},InputFields{iview},frame_index{iview}(index));
190            if ~isempty(errormsg)
191                errormsg=['time_series / read_field / ' errormsg];
192                display(errormsg)
193                break
194            end
195        end
196        if isempty(errormsg)
197            Field=Data{1}; % default input field structure
198            % coordinate transform (or other user defined transform)
199            % none
200           
201            %field projection on an object
202            if Param.CheckObject
203                [Field,errormsg]=proj_field(Field,Param.ProjObject);
204                if ~isempty(errormsg)
205                    msgbox_uvmat('ERROR',['time_series / proj_field / ' errormsg])
206                    return
207                end
208            end
209           
210            % initiate the time series at the first iteration
211            if index==1
212                % stop program if the first field reading is in error
213                if ~isempty(errormsg)
214                    disp_uvmat('ERROR',['time_series / sub_field / ' errormsg],checkrun)
215                    return
216                end
217                DataOut=Field;%default
218                DataOut.NbDim=Field.NbDim+1; %add the time dimension for plots
219                nbvar=length(Field.ListVarName);
220                if nbvar==0
221                    disp_uvmat('ERROR','no input variable selected',checkrun)
222                    return
223                end
224                testsum=2*ones(1,nbvar);%initiate flag for action on each variable
225                if isfield(Field,'VarAttribute') % look for coordinate and flag variables
226                    for ivar=1:nbvar
227                        if length(Field.VarAttribute)>=ivar && isfield(Field.VarAttribute{ivar},'Role')
228                            var_role=Field.VarAttribute{ivar}.Role;%'role' of the variable
229                            if isequal(var_role,'errorflag')
230                                disp_uvmat('ERROR','do not handle error flags in time series',checkrun)
231                                return
232                            end
233                            if isequal(var_role,'warnflag')
234                                testsum(ivar)=0;  % not recorded variable
235                                eval(['DataOut=rmfield(DataOut,''' Field.ListVarName{ivar} ''');']);%remove variable
236                            end
237                            if isequal(var_role,'coord_x')| isequal(var_role,'coord_y')|...
238                                    isequal(var_role,'coord_z')|isequal(var_role,'coord')
239                                testsum(ivar)=1; %constant coordinates, record without time evolution
240                            end
241                        end
242                        % check whether the variable ivar is a dimension variable
243                        DimCell=Field.VarDimName{ivar};
244                        if ischar(DimCell)
245                            DimCell={DimCell};
246                        end
247                        if numel(DimCell)==1 && isequal(Field.ListVarName{ivar},DimCell{1})%detect dimension variables
248                            testsum(ivar)=1;
249                        end
250                    end
251                end
252                for ivar=1:nbvar
253                    if testsum(ivar)==2
254                        eval(['DataOut.' Field.ListVarName{ivar} '=[];'])
255                    end
256                end
257                DataOut.ListVarName=[{'Time'} DataOut.ListVarName];
258            end
259           
260            % add data to the current field
261            for ivar=1:length(Field.ListVarName)
262                VarName=Field.ListVarName{ivar};
263                VarVal=Field.(VarName);
264                if testsum(ivar)==2% test for recorded variable
265                    if isempty(errormsg)
266                        if isequal(Param.ProjObject.ProjMode,'inside')% take the average in the domain for 'inside' mode
267                            if isempty(VarVal)
268                                disp_uvmat('ERROR',['empty result at frame index ' num2str(i1_series{iview}(index))],checkrun)
269                                return
270                            end
271                            VarVal=mean(VarVal,1);
272                        end
273                        VarVal=shiftdim(VarVal,-1); %shift dimension
274                        DataOut.(VarName)=cat(1,DataOut.(VarName),VarVal);%concanete the current field to the time series
275                    else
276                        DataOut.(VarName)=cat(1,DataOut.(VarName),0);% put each variable to 0 in case of input reading error
277                    end
278                elseif testsum(ivar)==1% variable representing fixed coordinates
279                    VarInit=DataOut.(VarName);
280                    if isempty(errormsg) && ~isequal(VarVal,VarInit)
281                        disp_uvmat('ERROR',['time series requires constant coordinates ' VarName],checkrun)
282                        return
283                    end
284                end
285            end
286
287        end
288    end
289end
290%%%%%%% END OF LOOP WITHIN A SLICE
291
292%remove time for global attributes if exists
293Time_index=find(strcmp('Time',DataOut.ListGlobalAttribute));
294if ~isempty(Time_index)
295    DataOut.ListGlobalAttribute(Time_index)=[];
296end
297DataOut.Conventions='uvmat';
298for ivar=1:numel(DataOut.ListVarName)
299    VarName=DataOut.ListVarName{ivar};
300    eval(['DataOut.' VarName '=squeeze(DataOut.' VarName ');']) %remove singletons
301end
302
303% add time dimension
304for ivar=1:length(Field.ListVarName)
305    DimCell=Field.VarDimName(ivar);
306    if testsum(ivar)==2%variable used as time series
307        DataOut.VarDimName{ivar}=[{'Time'} DimCell];
308    elseif testsum(ivar)==1
309        DataOut.VarDimName{ivar}=DimCell;
310    end
311end
312indexremove=find(~testsum);
313if ~isempty(indexremove)
314    DataOut.ListVarName(1+indexremove)=[];
315    DataOut.VarDimName(indexremove)=[];
316    if isfield(DataOut,'Role') && ~isempty(DataOut.Role{1})%generaliser aus autres attributs
317        DataOut.Role(1+indexremove)=[];
318    end
319end
320
321%shift variable attributes
322if isfield(DataOut,'VarAttribute')
323    DataOut.VarAttribute=[{[]} DataOut.VarAttribute];
324end
325DataOut.VarDimName=[{'Time'} DataOut.VarDimName];
326DataOut.Action=Param.Action;%name of the processing programme
327test_time=diff(DataOut.Time)>0;% test that the readed time is increasing (not constant)
328if ~test_time
329    DataOut.Time=1:filecounter;
330end
331
332% display nbmissing
333if ~isequal(nbmissing,0)
334    disp_uvmat('WARNING',[num2str(nbmissing) ' files skipped: missing files or bad input, see command window display'],checkrun)
335end
336
337%name of result file
338OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(1),i1_series{1}(end),i_slice,[]);
339errormsg=struct2nc(OutputFile,DataOut); %save result file
340if isempty(errormsg)
341    display([OutputFile ' written'])
342else
343    disp_uvmat('ERROR',['error in Series/struct2nc: ' errormsg],checkrun)
344end
345
346return
347
348%%%%%%%%%%%%%%%%%%  END%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
349%evaluation of peacklocking errors
350%use splinhist: give spline coeff cc for a smooth histo (call spline4)
351%use histsmooth(x,cc): calculate the smooth histo for any value x
352%use histder(x,cc): calculate the derivative of the smooth histo
353global hfig1 hfig2 hfig3
354global nbb Uval Vval Uhist Vhist % nbb resolution of the histogram nbb=10: 10 values in unity interval
355global xval xerror yval yerror
356
357set(handles.vector_y,'Value',1)% trigger the option Uhist on the interface
358set(handles.Vhist_input,'Value',1)
359set(handles.cm_switch,'Value',0) % put the switch to 'pixel'
360
361%adjust the extremal values of the histogram in U with respect to integer
362%values
363minimU=round(min(Uval)-0.5)+0.5; %first value of the histogram with integer bins
364maximU=round(max(Uval)-0.5)+0.5;
365minim_fin=(minimU-0.5+1/(2*nbb)); % first bin valueat the beginning of an integer interval
366maxim_fin=(maximU+0.5-1/(2*nbb)); % last integer value
367nb_bin_min= round(-(minim_fin - min(Uval))*nbb); % nbre of bins added below
368nb_bin_max=round((maxim_fin -max(Uval))*nbb); %nbre of bins added above
369Uval=[minim_fin:(1/nbb):maxim_fin];
370histu_min=zeros(nb_bin_min,1);
371histu_max=zeros(nb_bin_max,1);
372Uhist=[histu_min; Uhist ;histu_max]; % column vector
373
374%adjust the extremal values of the histogram in V
375minimV=round(min(Vval-0.5)+0.5);
376maximV=round(max(Vval-0.5)+0.5);
377minim_fin=minimV-0.5+1/(2*nbb); % first bin valueat the beginning of an integer interval
378maxim_fin=maximV+0.5-1/(2*nbb); % last integer value
379nb_bin_min=round((min(Vval) - minim_fin)*nbb); % nbre of bins added below
380nb_bin_max=round((maxim_fin -max(Vval))*nbb);
381Vval=[minim_fin:(1/nbb):maxim_fin];
382histu_min=zeros(nb_bin_min,1);
383histu_max=zeros(nb_bin_max,1);
384Vhist=[histu_min; Vhist ;histu_max]; % column vector
385
386% RUN_histo_Callback(hObject, eventdata, handles)
387% %adjust the histogram to integer values:
388
389%histoU and V
390[Uhistinter,xval,xerror]=peaklock(nbb,minimU,maximU,Uhist);
391[Vhistinter,yval,yerror]=peaklock(nbb,minimV,maximV,Vhist);
392
393% selection of value ranges such that histo>=10 (enough statistics)
394Uval_ind=find(Uhist>=10);
395ind_min=min(Uval_ind);
396ind_max=max(Uval_ind);
397U_min=Uval(ind_min);% minimum allowed value
398U_max=Uval(ind_max);%maximum allowed value
399
400% selection of value ranges such that histo>=10 (enough statistics)
401Vval_ind=find(Vhist>=10);
402ind_min=min(Vval_ind);
403ind_max=max(Vval_ind);
404V_min=Vval(ind_min);% minimum allowed value
405V_max=Vval(ind_max);%maximum allowed value
406
407figure(4)% plot U histogram with smoothed one
408plot(Uval,Uhist,'b')
409grid on
410hold on
411plot(Uval,Uhistinter,'r');
412hold off
413
414figure(5)% plot V histogram with smoothed one
415plot(Vval,Vhist,'b')
416grid on
417hold on
418plot(Vval,Vhistinter,'r');
419hold off
420
421figure(6)% plot pixel error in two subplots
422hfig4=subplot(2,1,1);
423hfig5=subplot(2,1,2);
424axes(hfig4)
425plot(xval,xerror)
426axis([U_min U_max -0.4 0.4])
427xlabel('velocity u (pix)')
428ylabel('peaklocking error (pix)')
429grid on
430axes(hfig5)
431plot(yval,yerror)
432axis([V_min V_max -0.4 0.4]);
433xlabel('velocity v (pix)')
434ylabel('peaklocking error (pix)')
435grid on
436
437
438
439
440
441
442
443
444
445%'peaklock': determines peacklocking errors from velocity histograms.
446%-------------------------------------------------------
447%first smooth the input histogram 'histu' in such a way that the integral over
448%n-n+1 is preserved, then deduce the peaklocking 'error' function of the pixcel displacement 'x'.
449%
450% [histinter,x,error]=peaklock(nbb,minim,maxim,histu)
451%OUTPUT:
452%histinter: smoothed interpolated histogram
453% x: vector of displacement values.
454% error: vector of estimated errors corresponding to x
455%INPUT:
456%histu=vector representing the values of histogram  of measured velocity ;
457%minim, maxim: extremal values of the measured velocity (absica for histu)
458%nbb: number of bins inside each integer interval for the histograms
459%SUBROUTINES INCLUDED:
460%spline4.m% spline interpolation at 4th order
461%splinhist.m: give spline coeff cc for a smooth histo (call spline4)
462%histsmooth.m(x,cc): calculate the smooth histo for any value x
463%histder.m(x,cc): calculate the derivative of the smooth histo
464function [histinter,x,error]=peaklock(nbb,minim,maxim,histu)
465
466nint=maxim-minim+1
467xfin=[minim-0.5+1/(2*nbb):(1/nbb):maxim+0.5-(1/(2*nbb))];
468histo=(reshape(histu,nbb,nint));%extract values with x between integer -1/2 integer +1/2
469Integ=sum(histo)/nbb; %integral of the pdf on each integer bin
470[histinter,cc]=splinhist(Integ,minim,nbb);
471histx=reshape(histinter,nbb,nint);
472xint=[minim:1:maxim];
473x=zeros(nbb,nint);
474%determination of the displacement x(j,:)
475%j=1
476delx=histo(1,:)./histsmooth(-0.5*ones(1,nint),cc)/nbb;
477%del(1,:)=delx;
478x(1,:)=-0.5+delx-(delx.*delx/2).*histder(-0.5*ones(1,nint),cc);
479%histx(1,:)=histsmooth(x(j-1,:),cc);
480for j=2:nbb
481    delx=histo(j,:)./histsmooth(x(j-1,:),cc)/nbb;
482    %delx=delx.*(delx<3*ones(1,nint)/nbb)+3*ones(1,nint)/nbb.*~(delx <3*ones(1,nint)/nbb)
483    x(j,:)=x(j-1,:)+delx-(delx.*delx/2).*histder(x(j-1,:),cc);
484end
485%reshape
486xint=ones(nbb,1)*xint;
487x=x+xint;
488x=reshape(x,1,nbb*nint);
489error=xfin+1/(2*nbb)-x;
490
491%-------------------------------------------------------
492% --- determine the spline coefficients cc for the interpolated histogram.
493%-------------------------------------------------
494function [histsmooth,cc]= splinhist(Integ,mini,nbb)
495% provides a smooth histogramm histmooth, which remains always positive,
496% and is such that its sum over each integer bin [i-1/2 i+1/2] is equal to
497% Integ(i). The function determines histmooth as the exponential of a 4th
498% order spline function and adjust the cefficients by a Newton method to
499% fit the integral conditions Integ
500% histmooth is determined at the abscissa
501% xfin=[mini-0.5+1/(2*n):(1/n):maxi+0.5-(1/(2*n))] (maxi=mini+size(aa)-1)
502%cc(1-5,i) provides the spline coefficients
503
504% order 0
505siz=size(Integ);
506nint=siz(2);
507izero=find(Integ==0); %indices of zero elements
508inonzero=find(Integ);
509Integ(izero)=min(Integ(inonzero));
510aa=log(Integ);%initial guess for a coeff
511spli=spline4(aa,mini,nbb);  %appel à la fonction spline4
512histsmooth=exp(spli);
513
514S=(sum(reshape(histsmooth,nbb,nint)))/nbb;% integral of the fit histsmooth on ]i-1/2 i+1/2[
515epsilon=max(abs(Integ-S));
516iter=0;
517while epsilon > 0.000001 & iter<10
518ident=eye(nint);
519dSda=ones(nint);
520for j=1:nint% determination of the jacobian matrix dSda
521dhistda=spline4(ident(j,:),mini,nbb);
522expdhistda=dhistda.*histsmooth;
523dSda(j,:)=(sum(reshape(expdhistda,nbb,nint)))/nbb;
524end
525aa=aa+(Integ-S)*inv(dSda);%new estimate of coefficients aa by linear interpolation
526[spli,bb]=spline4(aa,mini,nbb);% new fit histsmooth
527histsmooth=exp(spli);
528S=(sum(reshape(histsmooth,nbb,nint)))/nbb;% integral of the fit histsmooth on ]i-1/2 i+1/2[
529epsilon=max(abs(Integ-S));
530iter=iter+1;
531end
532if iter==10, errordlg('splinhist did not converge after 10 iterations'),end
533cc(1,:)=aa;
534cc(2,:)=bb(1,:);
535cc(3,:)=bb(2,:);
536cc(4,:)=bb(3,:);
537cc(5,:)=bb(4,:);
538
539%-------------------------------------------------------
540% --- determine the 4th order spline coefficients from the function values aa.
541%-------------------------------------------------
542function [histsmooth,bb]= spline4(aa,mini,n)
543% spline interpolation at 4th order
544%aa=vector of values of a function at integer abscissa, starting at mini
545%n=number of subdivisions for the interpolated function
546% histmooth =interpolated values at absissa
547% xfin=[mini-0.5+1/(2*n):(1/n):maxi+0.5-(1/(2*n))] (maxi=mini+size(aa)-1)
548%bb=[b(i);c(i);d(i); e(i)] matrix of spline coeff
549L1=[1/2 1/4 1/8 1/16;1 1 3/4 1/2;0 2 3 3;0 0 6 12];
550L2=[-1/2 1/4 -1/8 1/16;1 -1 3/4 -1/2;0 2 -3 3;0 0 6 -12];
551M=inv(L2)*L1;
552[V,D]=eig(M);
553F=-inv(V)*inv(L2)*[1 ;0 ;0;0];
554a1rev=[1 -1/D(1,1)];
555b1rev=[F(1)/D(1,1)];
556a2rev=[1 -1/D(2,2)];
557b2rev=[F(2)/D(2,2)];
558a3=[1 -D(3,3)];
559b3=[F(3)];
560a4=[1 -D(4,4)];
561b4=[F(4)];
562
563%data
564% n=10;% résolution de la pdf: nbre de points par unite de u
565% mini=-10.0;%general mini=uint16(min(values)-1 CHOOSE maxi-mini+1 EVEN
566% maxi=9.0; % general maxi=uint16(max(values))+1
567%nint=double(maxi-mini+1); % nombre d'intervals entiers EVEN!
568siz=size(aa);
569nint=siz(2);
570maxi=mini+nint-1;
571npdf=nint*n;% nbre total d'intervals à introduire dans la pdf: hist(u,npdf)
572%simulation de pdf
573xfin=[mini-0.5+1/(2*n):(1/n):maxi+0.5-(1/(2*n))];% valeurs d'interpolation: we take n values in each integer interval
574%histolin=exp(-(xfin-1).*(xfin-1)).*(2+cos(10*(xfin-1)));% simulation d'une pdf
575%histo=log(histolin);
576%histo=sin(2*pi*xfin);
577%histextract=(reshape(histo,n,nint));
578%aa=sum(histextract)/n %integral of the pdf on each integer bin
579IP=[0 diff(aa)];
580Irev=zeros(size(aa));
581for i=1:nint
582    Irev(i)=aa(end-i+1);
583end
584IPrev=[0 diff(Irev)];
585
586%get the spline coelfficients a_d, using filter on the eigen vectors A,B,C
587Arev=filter(b1rev,a1rev,IPrev);
588Brev=filter(b2rev,a2rev,IPrev);
589C=filter(b3,a3,IP);
590D=filter(b4,a4,IP);
591A=zeros(size(Arev));
592B=zeros(size(Brev));
593for i=1:nint
594    A(i)=Arev(end-i+1);
595    B(i)=Brev(end-i+1);
596end
597%Matr=V*[A;B;C;D];
598bb=V*[A;B;C;D];
599%b=Matr(1,:);
600%c=Matr(2,:);
601%d=Matr(3,:);
602%e=Matr(4,:);
603%a=aa;
604
605%calculate the interpolation using the spline coefficients a-d
606%xextract=(reshape(xfin,n,nint));%
607chi=xfin+1/(2*n)-min(xfin)-double(int16(xfin+(1/(2*n))-min(xfin)))-0.5;% decimal part
608chi2=chi.*chi;
609chi3=chi2.*chi;
610chi4=chi3.*chi;
611avec=reshape(ones(n,1)*aa,1,n*nint);
612bvec=reshape(ones(n,1)*bb(1,:),1,n*nint);
613cvec=reshape(ones(n,1)*bb(2,:),1,n*nint);
614dvec=reshape(ones(n,1)*bb(3,:),1,n*nint);
615evec=reshape(ones(n,1)*bb(4,:),1,n*nint);
616histsmooth=avec+bvec.*chi+cvec.*chi2+dvec.*chi3+evec.*chi4;
617
618%-------------------------------------------------------
619% --- determine the interpolated histogram at points chi from the spline ceff cc.
620%-------------------------------------------------
621function histx= histsmooth(chi,cc)
622% provides the value of the interpolated histogram at values chi=x-i
623%(difference with the mnearest integer)
624% cc(5,size(chi)) is the set of spline coefficients obtained by splinhist
625chi2=chi.*chi;
626chi3=chi2.*chi;
627chi4=chi3.*chi;
628histx=exp(cc(1,:)+cc(2,:).*chi+cc(3,:).*chi2+cc(4,:).*chi3+cc(5,:).*chi4);
629
630%-------------------------------------------------------
631% --- determine the derivative p'/p of the interpolated histogram at points chi from the spline ceff cc.
632%-------------------------------------------------
633function histder= histder(chi,cc)
634% provides the logarithmique derivative p'/p of the interpolated histogram
635%at values chi=x-i
636%(difference with the nearest integer)
637% cc(5,size(chi)) is the set of spline coefficients obtained by splinhist
638chi2=chi.*chi;
639chi3=chi2.*chi;
640chi4=chi3.*chi;
641histder=cc(2,:)+2*cc(3,:).*chi+3*cc(4,:).*chi2+4*cc(5,:).*chi3;
Note: See TracBrowser for help on using the repository browser.