Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TGraphSmooth.cxx
Go to the documentation of this file.
1// @(#)root/hist:$Id$
2// Author: Christian Stratowa 30/09/2001
3
4/*************************************************************************
5 * Copyright (C) 2006, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12/******************************************************************************
13* Copyright(c) 2001-2006, Dr. Christian Stratowa, Vienna, Austria. *
14* Author: Christian Stratowa with help from Rene Brun. *
15* *
16* Algorithms for smooth regression adapted from: *
17* R: A Computer Language for Statistical Data Analysis *
18* *
19******************************************************************************/
20
21#include "TMath.h"
22#include "TGraphSmooth.h"
23#include "TGraphErrors.h"
24
25#include <iostream>
26
27//______________________________________________________________________
28/** \class TGraphSmooth
29 \ingroup Graphs
30A helper class to smooth TGraph.
31see the following examples: gr010_approx_smooth.C and gr015_smooth.C.
32*/
33
35{
36 fNin = 0;
37 fNout = 0;
38 fGin = nullptr;
39 fGout = nullptr;
40 fMinX = 0;
41 fMaxX = 0;
42}
43
44////////////////////////////////////////////////////////////////////////////////
45/// GraphSmooth constructor
46
48{
49 fNin = 0;
50 fNout = 0;
51 fGin = nullptr;
52 fGout = nullptr;
53 fMinX = 0;
54 fMaxX = 0;
55}
56
57////////////////////////////////////////////////////////////////////////////////
58/// GraphSmooth destructor
59
61{
62 if (fGout) delete fGout;
63 fGin = nullptr;
64 fGout = nullptr;
65}
66
67////////////////////////////////////////////////////////////////////////////////
68/// Sort input data points
69
71{
72 if (fGout) {delete fGout; fGout = nullptr;}
73 fGin = grin;
74
75 fNin = fGin->GetN();
76 Double_t *xin = new Double_t[fNin];
77 Double_t *yin = new Double_t[fNin];
78 Int_t i;
79 for (i=0;i<fNin;i++) {
80 xin[i] = fGin->GetX()[i];
81 yin[i] = fGin->GetY()[i];
82 }
83
84// sort input x, y
85 Int_t *index = new Int_t[fNin];
87 for (i=0;i<fNin;i++) {
88 fGin->SetPoint(i, xin[index[i]], yin[index[i]]);
89 }
90
91 fMinX = fGin->GetX()[0]; //already sorted!
92 fMaxX = fGin->GetX()[fNin-1];
93
94 delete [] index;
95 delete [] xin;
96 delete [] yin;
97}
98
99////////////////////////////////////////////////////////////////////////////////
100/// Smooth data with Kernel smoother. Smooth grin with the Nadaraya-Watson kernel regression estimate.
101///
102/// \param[in] grin input graph
103/// \param[in] option the kernel to be used: "box", "normal"
104/// \param[in] bandwidth the bandwidth. The kernels are scaled so that their quartiles
105/// (viewed as probability densities) are at +/- 0.25*bandwidth.
106/// \param[in] nout If xout is not specified, interpolation takes place at equally
107/// spaced points spanning the interval [min(x), max(x)], where nout = max(nout, number of input data).
108/// \param[in] xout an optional set of values at which to evaluate the fit
109
112{
113 TString opt = option;
114 opt.ToLower();
115 Int_t kernel = 1;
116 if (opt.Contains("normal")) kernel = 2;
117
118 Smoothin(grin);
119
120 Double_t delta = 0;
121 Int_t *index = nullptr;
122 if (xout == nullptr) {
124 delta = (fMaxX - fMinX)/(fNout - 1);
125 } else {
126 fNout = nout;
127 index = new Int_t[nout];
129 }
130
131 fGout = new TGraph(fNout);
132 // To calculate x coordinates and avoid a rounding issue in last point,
133 // (fMin + (fNout-1)* delta > fMaxX) if fNout is large,
134 // we split the calculation in two loops,
135 // the left half of x points is calculated as min + i*delta
136 // the right half of x points as max - j*delta
137 for (Int_t i=0;i<fNout/2;i++) {
138 if (xout == nullptr) fGout->SetPoint(i,fMinX + i*delta, 0);
139 else fGout->SetPoint(i,xout[index[i]], 0);
140 }
141 for (Int_t i=fNout/2;i<fNout;i++) {
142 if (xout == nullptr) fGout->SetPoint(i,fMaxX + (i + 1 - fNout)*delta, 0);
143 else fGout->SetPoint(i,xout[index[i]], 0);
144 }
145
148
149 if (index) {delete [] index; index = nullptr;}
150
151 return fGout;
152}
153
154////////////////////////////////////////////////////////////////////////////////
155/// Smooth data with specified kernel.
156/// Based on R function ksmooth: Translated to C++ by C. Stratowa
157/// (R source file: ksmooth.c by B.D.Ripley Copyright (C) 1998)
158
161{
162 Int_t imin = 0;
163 Double_t cutoff = 0.0;
164
165// bandwidth is in units of half inter-quartile range
166 if (kernel == 1) {
167 bw *= 0.5;
168 cutoff = bw;
169 }
170 if (kernel == 2) {
171 bw *= 0.3706506;
172 cutoff = 4*bw;
173 }
174
175 while ((imin < n) && (x[imin] < xp[0] - cutoff))
176 imin++;
177
178 for (Int_t j=0;j<np;j++) {
179 Double_t xx, w;
180 Double_t num = 0.0;
181 Double_t den = 0.0;
182 Double_t x0 = xp[j];
183 for (Int_t i=imin;i<n;i++) {
184 if (x[i] < x0 - cutoff) imin = i;
185 if (x[i] > x0 + cutoff) break;
186 xx = TMath::Abs(x[i] - x0)/bw;
187 if (kernel == 1) w = 1;
188 else w = TMath::Exp(-0.5*xx*xx);
189 num += w*y[i];
190 den += w;
191 }
192 if (den > 0) {
193 yp[j] = num/den;
194 } else {
195 yp[j] = 0; //should be NA_REAL (see R.h) or nan("NAN")
196 }
197 }
198}
199
200
201////////////////////////////////////////////////////////////////////////////////
202/// Smooth data with Lowess smoother
203///
204/// This function performs the computations for the LOWESS smoother
205/// (see the reference below). Lowess returns the output points
206/// x and y which give the coordinates of the smooth.
207///
208/// \param[in] grin Input graph
209/// \param[in] option specific options
210/// \param[in] span the smoother span. This gives the proportion of points in the plot
211/// which influence the smooth at each value. Larger values give more smoothness.
212/// \param[in] iter the number of robustifying iterations which should be performed.
213/// Using smaller values of iter will make lowess run faster.
214/// \param[in] delta values of x which lie within delta of each other replaced by a
215/// single value in the output from lowess.
216/// For delta = 0, delta will be calculated.
217///
218/// References:
219///
220/// - Cleveland, W. S. (1979) Robust locally weighted regression and smoothing
221/// scatterplots. J. Amer. Statist. Assoc. 74, 829-836.
222/// - Cleveland, W. S. (1981) LOWESS: A program for smoothing scatterplots
223/// by robust locally weighted regression.
224/// The American Statistician, 35, 54.
225
227 Double_t span, Int_t iter, Double_t delta)
228{
229 TString opt = option;
230 opt.ToLower();
231
232 Smoothin(grin);
233
234 if (delta == 0) {delta = 0.01*(TMath::Abs(fMaxX - fMinX));}
235
236// output X, Y
237 fNout = fNin;
238 fGout = new TGraphErrors(fNout);
239
240 for (Int_t i=0;i<fNout;i++) {
241 fGout->SetPoint(i,fGin->GetX()[i], 0);
242 }
243
244 Lowess(fGin->GetX(), fGin->GetY(), fNin, fGout->GetY(), span, iter, delta);
245
246 return fGout;
247}
248
249////////////////////////////////////////////////////////////////////////////////
250/// Lowess regression smoother.
251/// Based on R function clowess: Translated to C++ by C. Stratowa
252/// (R source file: lowess.c by R Development Core Team (C) 1999-2001)
253
255 Double_t span, Int_t iter, Double_t delta)
256{
257 Int_t i, iiter, j, last, m1, m2, nleft, nright, ns;
258 Double_t alpha, c1, c9, cmad, cut, d1, d2, denom, r;
259 Bool_t ok;
260
261 if (n < 2) {
262 ys[0] = y[0];
263 return;
264 }
265
266// nleft, nright, last, etc. must all be shifted to get rid of these:
267 x--;
268 y--;
269 ys--;
270
271 Double_t *rw = ((TGraphErrors*)fGout)->GetEX();
272 Double_t *res = ((TGraphErrors*)fGout)->GetEY();
273
274// at least two, at most n points
275 ns = TMath::Max(2, TMath::Min(n, (Int_t)(span*n + 1e-7)));
276
277// robustness iterations
278 iiter = 1;
279 while (iiter <= iter+1) {
280 nleft = 1;
281 nright = ns;
282 last = 0; // index of prev estimated point
283 i = 1; // index of current point
284
285 for(;;) {
286 if (nright < n) {
287 // move nleft, nright to right if radius decreases
288 d1 = x[i] - x[nleft];
289 d2 = x[nright+1] - x[i];
290
291 // if d1 <= d2 with x[nright+1] == x[nright], lowest fixes
292 if (d1 > d2) {
293 // radius will not decrease by move right
294 nleft++;
295 nright++;
296 continue;
297 }
298 }
299
300 // fitted value at x[i]
301 Bool_t iterg1 = iiter>1;
302 Lowest(&x[1], &y[1], n, x[i], ys[i], nleft, nright,
303 res, iterg1, rw, ok);
304 if (!ok) ys[i] = y[i];
305
306 // all weights zero copy over value (all rw==0)
307 if (last < i-1) {
308 denom = x[i]-x[last];
309
310 // skipped points -- Int_terpolate non-zero - proof?
311 for(j = last+1; j < i; j++) {
312 alpha = (x[j]-x[last])/denom;
313 ys[j] = alpha*ys[i] + (1.-alpha)*ys[last];
314 }
315 }
316
317 // last point actually estimated
318 last = i;
319
320 // x coord of close points
321 cut = x[last] + delta;
322 for (i = last+1; i <= n; i++) {
323 if (x[i] > cut)
324 break;
325 if (x[i] == x[last]) {
326 ys[i] = ys[last];
327 last = i;
328 }
329 }
330 i = TMath::Max(last+1, i-1);
331 if (last >= n)
332 break;
333 }
334
335 // residuals
336 for(i=0; i < n; i++)
337 res[i] = y[i+1] - ys[i+1];
338
339 // compute robustness weights except last time
340 if (iiter > iter)
341 break;
342 for(i=0 ; i<n ; i++)
343 rw[i] = TMath::Abs(res[i]);
344
345 // compute cmad := 6 * median(rw[], n)
346 m1 = n/2;
347 // partial sort, for m1 & m2
348 Psort(rw, n, m1);
349 if(n % 2 == 0) {
350 m2 = n-m1-1;
351 Psort(rw, n, m2);
352 cmad = 3.*(rw[m1]+rw[m2]);
353 } else { /* n odd */
354 cmad = 6.*rw[m1];
355 }
356
357 c9 = 0.999*cmad;
358 c1 = 0.001*cmad;
359 for(i=0 ; i<n ; i++) {
360 r = TMath::Abs(res[i]);
361 if (r <= c1)
362 rw[i] = 1.;
363 else if (r <= c9)
364 rw[i] = (1.-(r/cmad)*(r/cmad))*(1.-(r/cmad)*(r/cmad));
365 else
366 rw[i] = 0.;
367 }
368 iiter++;
369 }
370}
371
372////////////////////////////////////////////////////////////////////////////////
373/// Fit value at x[i]
374/// Based on R function lowest: Translated to C++ by C. Stratowa
375/// (R source file: lowess.c by R Development Core Team (C) 1999-2001)
376
380{
381 Int_t nrt, j;
382 Double_t a, b, c, d, h, h1, h9, r, range;
383
384 x--;
385 y--;
386 w--;
387 rw--;
388
389 range = x[n]-x[1];
390 h = TMath::Max(xs-x[nleft], x[nright]-xs);
391 h9 = 0.999*h;
392 h1 = 0.001*h;
393
394// sum of weights
395 a = 0.;
396 j = nleft;
397 while (j <= n) {
398 // compute weights (pick up all ties on right)
399 w[j] = 0.;
400 r = TMath::Abs(x[j] - xs);
401 if (r <= h9) {
402 if (r <= h1) {
403 w[j] = 1.;
404 } else {
405 d = (r/h)*(r/h)*(r/h);
406 w[j] = (1.- d)*(1.- d)*(1.- d);
407 }
408 if (userw)
409 w[j] *= rw[j];
410 a += w[j];
411 } else if (x[j] > xs)
412 break;
413 j = j+1;
414 }
415
416// rightmost pt (may be greater than nright because of ties)
417 nrt = j-1;
418 if (a <= 0.)
419 ok = kFALSE;
420 else {
421 ok = kTRUE;
422 // weighted least squares: make sum of w[j] == 1
423 for(j=nleft ; j<=nrt ; j++)
424 w[j] /= a;
425 if (h > 0.) {
426 a = 0.;
427 // use linear fit weighted center of x values
428 for(j=nleft ; j<=nrt ; j++)
429 a += w[j] * x[j];
430 b = xs - a;
431 c = 0.;
432 for(j=nleft ; j<=nrt ; j++)
433 c += w[j]*(x[j]-a)*(x[j]-a);
434 if (TMath::Sqrt(c) > 0.001*range) {
435 b /= c;
436 // points are spread out enough to compute slope
437 for(j=nleft; j <= nrt; j++)
438 w[j] *= (b*(x[j]-a) + 1.);
439 }
440 }
441 ys = 0.;
442 for(j=nleft; j <= nrt; j++)
443 ys += w[j] * y[j];
444 }
445}
446
447////////////////////////////////////////////////////////////////////////////////
448/// Smooth data with Super smoother.
449/// Smooth the (x, y) values by Friedman's ``super smoother''.
450///
451/// \param[in] grin graph for smoothing
452/// \param[in] option specific options
453/// \param[in] span the fraction of the observations in the span of the running lines
454/// smoother, or 0 to choose this by leave-one-out cross-validation.
455/// \param[in] bass controls the smoothness of the fitted curve.
456/// Values of up to 10 indicate increasing smoothness.
457/// \param[in] isPeriodic if TRUE, the x values are assumed to be in [0, 1]
458/// and of period 1.
459/// \param[in] w case weights
460///
461/// Details:
462///
463/// supsmu is a running lines smoother which chooses between three spans for
464/// the lines. The running lines smoothers are symmetric, with k/2 data points
465/// each side of the predicted point, and values of k as 0.5 * n, 0.2 * n and
466/// 0.05 * n, where n is the number of data points. If span is specified,
467/// a single smoother with span span * n is used.
468///
469/// The best of the three smoothers is chosen by cross-validation for each
470/// prediction. The best spans are then smoothed by a running lines smoother
471/// and the final prediction chosen by linear interpolation.
472///
473/// The FORTRAN code says: ``For small samples (n < 40) or if there are
474/// substantial serial correlations between observations close in x - value,
475/// then a prespecified fixed span smoother (span > 0) should be used.
476/// Reasonable span values are 0.2 to 0.4.''
477///
478/// References:
479/// - Friedman, J. H. (1984) SMART User's Guide.
480/// Laboratory for Computational Statistics,
481/// Stanford University Technical Report No. 1.
482/// - Friedman, J. H. (1984) A variable span scatterplot smoother.
483/// Laboratory for Computational Statistics,
484/// Stanford University Technical Report No. 5.
485
488{
489 if (span < 0 || span > 1) {
490 std::cout << "Error: Span must be between 0 and 1" << std::endl;
491 return nullptr;
492 }
493 TString opt = option;
494 opt.ToLower();
495
496 Smoothin(grin);
497
498 Int_t iper = 1;
499 if (isPeriodic) {
500 iper = 2;
501 if (fMinX < 0 || fMaxX > 1) {
502 std::cout << "Error: x must be between 0 and 1 for periodic smooth" << std::endl;
503 return nullptr;
504 }
505 }
506
507// output X, Y
508 fNout = fNin;
509 fGout = new TGraph(fNout);
510 Int_t i;
511 for (i=0; i<fNout; i++) {
512 fGout->SetPoint(i,fGin->GetX()[i], 0);
513 }
514
515// weights
516 Double_t *weight = new Double_t[fNin];
517 for (i=0; i<fNin; i++) {
518 if (w == nullptr) weight[i] = 1;
519 else weight[i] = w[i];
520 }
521
522// temporary storage array
523 Int_t nTmp = (fNin+1)*8;
524 Double_t *tmp = new Double_t[nTmp];
525 for (i=0; i<nTmp; i++) {
526 tmp[i] = 0;
527 }
528
529 BDRsupsmu(fNin, fGin->GetX(), fGin->GetY(), weight, iper, span, bass, fGout->GetY(), tmp);
530
531 delete [] tmp;
532 delete [] weight;
533
534 return fGout;
535}
536
537////////////////////////////////////////////////////////////////////////////////
538/// Friedmanns super smoother (Friedman, 1984).
539///
540/// version 10/10/84
541/// coded and copyright (c) 1984 by:
542///
543/// Jerome H. Friedman
544/// department of statistics
545/// and
546/// stanford linear accelerator center
547/// stanford university
548///
549/// all rights reserved.
550///
551/// \param[in] n number of observations (x,y - pairs).
552/// \param[in] x ordered abscissa values.
553/// \param[in] y corresponding ordinate (response) values.
554/// \param[in] w weight for each (x,y) observation.
555/// \param[in] iper periodic variable flag.
556/// - iper=1 => x is ordered interval variable.
557/// - iper=2 => x is a periodic variable with values
558/// in the range (0.0,1.0) and period 1.0.
559/// \param[in] span smoother span (fraction of observations in window).
560/// - span=0.0 => automatic (variable) span selection.
561/// \param[in] alpha controls high frequency (small span) penality
562/// used with automatic span selection (bass tone control).
563/// (alpha.le.0.0 or alpha.gt.10.0 => no effect.)
564/// \param[out] smo smoothed ordinate (response) values.
565/// \param sc internal working storage.
566///
567/// note:
568///
569/// for small samples (n < 40) or if there are substantial serial
570/// correlations between observations close in x - value, then
571/// a prespecified fixed span smoother (span > 0) should be
572/// used. reasonable span values are 0.2 to 0.4.
573///
574/// current implementation:
575///
576/// Based on R function supsmu: Translated to C++ by C. Stratowa
577/// (R source file: ppr.f by B.D.Ripley Copyright (C) 1994-97)
578
581{
582// Local variables
584 Int_t i, j, jper;
585 Double_t a, f;
588 Double_t d1, d2;
589
590 Double_t spans[3] = { 0.05, 0.2, 0.5 };
591 Double_t big = 1e20;
592 Double_t sml = 1e-7;
593 Double_t eps = 0.001;
594
595// Parameter adjustments
596 sc_offset = n + 1;
597 sc -= sc_offset;
598 --smo;
599 --w;
600 --y;
601 --x;
602
603// Function Body
604 if (x[n] <= x[1]) {
605 sy = 0.0;
606 sw = sy;
607 for (j=1;j<=n;++j) {
608 sy += w[j] * y[j];
609 sw += w[j];
610 }
611
612 a = 0.0;
613 if (sw > 0.0) a = sy / sw;
614 for (j=1;j<=n;++j) smo[j] = a;
615 return;
616 }
617
618 i = (Int_t)(n / 4);
619 j = i * 3;
620 scale = x[j] - x[i];
621 while (scale <= 0.0) {
622 if (j < n) ++j;
623 if (i > 1) --i;
624 scale = x[j] - x[i];
625 }
626
627// Computing 2nd power
628 d1 = eps * scale;
629 vsmlsq = d1 * d1;
630 jper = iper;
631 if (iper == 2 && (x[1] < 0.0 || x[n] > 1.0)) {
632 jper = 1;
633 }
634 if (jper < 1 || jper > 2) {
635 jper = 1;
636 }
637 if (span > 0.0) {
638 BDRsmooth(n, &x[1], &y[1], &w[1], span, jper, vsmlsq,
639 &smo[1], &sc[sc_offset]);
640 return;
641 }
642
643 Double_t *h = new Double_t[n+1];
644 for (i = 1; i <= 3; ++i) {
645 BDRsmooth(n, &x[1], &y[1], &w[1], spans[i - 1], jper, vsmlsq,
646 &sc[((i<<1)-1)*n + 1], &sc[n*7 + 1]);
647 BDRsmooth(n, &x[1], &sc[n*7 + 1], &w[1], spans[1], -jper, vsmlsq,
648 &sc[(i<<1)*n + 1], &h[1]);
649 }
650
651 for (j=1; j<=n; ++j) {
652 resmin = big;
653 for (i=1; i<=3; ++i) {
654 if (sc[j + (i<<1)*n] < resmin) {
655 resmin = sc[j + (i<<1)*n];
656 sc[j + n*7] = spans[i-1];
657 }
658 }
659
660 if (alpha>0.0 && alpha<=10.0 && resmin<sc[j + n*6] && resmin>0.0) {
661 // Computing MAX
662 d1 = TMath::Max(sml,(resmin/sc[j + n*6]));
663 d2 = 10. - alpha;
664 sc[j + n*7] += (spans[2] - sc[j + n*7]) * TMath::Power(d1, d2);
665 }
666 }
667
668 BDRsmooth(n, &x[1], &sc[n*7 + 1], &w[1], spans[1], -jper, vsmlsq,
669 &sc[(n<<1) + 1], &h[1]);
670
671 for (j=1; j<=n; ++j) {
672 if (sc[j + (n<<1)] <= spans[0]) {
673 sc[j + (n<<1)] = spans[0];
674 }
675 if (sc[j + (n<<1)] >= spans[2]) {
676 sc[j + (n<<1)] = spans[2];
677 }
678 f = sc[j + (n<<1)] - spans[1];
679 if (f < 0.0) {
680 f = -f / (spans[1] - spans[0]);
681 sc[j + (n<<2)] = (1.0 - f) * sc[j + n*3] + f * sc[j + n];
682 } else {
683 f /= spans[2] - spans[1];
684 sc[j + (n<<2)] = (1.0 - f) * sc[j + n*3] + f * sc[j + n*5];
685 }
686 }
687
688 BDRsmooth(n, &x[1], &sc[(n<<2) + 1], &w[1], spans[0], -jper, vsmlsq,
689 &smo[1], &h[1]);
690
691 delete [] h;
692 return;
693}
694
695////////////////////////////////////////////////////////////////////////////////
696/// Function for super smoother
697/// Based on R function supsmu: Translated to C++ by C. Stratowa
698/// (R source file: ppr.f by B.D.Ripley Copyright (C) 1994-97)
699
702{
703// Local variables
704 Int_t i, j, j0, in, out, it, jper, ibw;
705 Double_t a, h1, d1;
706 Double_t xm, ym, wt, sy, fbo, fbw;
707 Double_t cvar, var, tmp, xti, xto;
708
709// Parameter adjustments
710 --acvr;
711 --smo;
712 --w;
713 --y;
714 --x;
715
716// Function Body
717 xm = 0.;
718 ym = xm;
719 var = ym;
720 cvar = var;
721 fbw = cvar;
723
724 ibw = (Int_t)(span * 0.5 * n + 0.5);
725 if (ibw < 2) {
726 ibw = 2;
727 }
728
729 it = 2*ibw + 1;
730 for (i=1; i<=it; ++i) {
731 j = i;
732 if (jper == 2) {
733 j = i - ibw - 1;
734 }
735 xti = x[j];
736 if (j < 1) {
737 j = n + j;
738 xti = x[j] - 1.0;
739 }
740 wt = w[j];
741 fbo = fbw;
742 fbw += wt;
743 if (fbw > 0.0) {
744 xm = (fbo * xm + wt * xti) / fbw;
745 ym = (fbo * ym + wt * y[j]) / fbw;
746 }
747 tmp = 0.0;
748 if (fbo > 0.0) {
749 tmp = fbw * wt * (xti - xm) / fbo;
750 }
751 var += tmp * (xti - xm);
752 cvar += tmp * (y[j] - ym);
753 }
754
755 for (j=1; j<=n; ++j) {
756 out = j - ibw - 1;
757 in = j + ibw;
758 if (!(jper != 2 && (out < 1 || in > n))) {
759 if (out < 1) {
760 out = n + out;
761 xto = x[out] - 1.0;
762 xti = x[in];
763 } else if (in > n) {
764 in -= n;
765 xti = x[in] + 1.0;
766 xto = x[out];
767 } else {
768 xto = x[out];
769 xti = x[in];
770 }
771
772 wt = w[out];
773 fbo = fbw;
774 fbw -= wt;
775 tmp = 0.0;
776 if (fbw > 0.0) {
777 tmp = fbo * wt * (xto - xm) / fbw;
778 }
779 var -= tmp * (xto - xm);
780 cvar -= tmp * (y[out] - ym);
781 if (fbw > 0.0) {
782 xm = (fbo * xm - wt * xto) / fbw;
783 ym = (fbo * ym - wt * y[out]) / fbw;
784 }
785 wt = w[in];
786 fbo = fbw;
787 fbw += wt;
788 if (fbw > 0.0) {
789 xm = (fbo * xm + wt * xti) / fbw;
790 ym = (fbo * ym + wt * y[in]) / fbw;
791 }
792 tmp = 0.0;
793 if (fbo > 0.0) {
794 tmp = fbw * wt * (xti - xm) / fbo;
795 }
796 var += tmp * (xti - xm);
797 cvar += tmp * (y[in] - ym);
798 }
799
800 a = 0.0;
801 if (var > vsmlsq) {
802 a = cvar / var;
803 }
804 smo[j] = a * (x[j] - xm) + ym;
805
806 if (iper <= 0) {
807 continue;
808 }
809
810 h1 = 0.0;
811 if (fbw > 0.0) {
812 h1 = 1.0 / fbw;
813 }
814 if (var > vsmlsq) {
815 // Computing 2nd power
816 d1 = x[j] - xm;
817 h1 += d1 * d1 / var;
818 }
819
820 acvr[j] = 0.0;
821 a = 1.0 - w[j] * h1;
822 if (a > 0.0) {
823 acvr[j] = TMath::Abs(y[j] - smo[j]) / a;
824 continue;
825 }
826 if (j > 1) {
827 acvr[j] = acvr[j-1];
828 }
829 }
830
831 j = 1;
832 do {
833 j0 = j;
834 sy = smo[j] * w[j];
835 fbw = w[j];
836 if (j < n) {
837 do {
838 if (x[j + 1] > x[j]) {
839 break;
840 }
841 ++j;
842 sy += w[j] * smo[j];
843 fbw += w[j];
844 } while (j < n);
845 }
846
847 if (j > j0) {
848 a = 0.0;
849 if (fbw > 0.0) {
850 a = sy / fbw;
851 }
852 for (i=j0; i<=j; ++i) {
853 smo[i] = a;
854 }
855 }
856 ++j;
857 } while (j <= n);
858
859 return;
860}
861
862////////////////////////////////////////////////////////////////////////////////
863/// Sort data points and eliminate double x values
864
867{
868 if (fGout) {delete fGout; fGout = nullptr;}
869 fGin = grin;
870
871 fNin = fGin->GetN();
872 Double_t *xin = new Double_t[fNin];
873 Double_t *yin = new Double_t[fNin];
874 Int_t i;
875 for (i=0;i<fNin;i++) {
876 xin[i] = fGin->GetX()[i];
877 yin[i] = fGin->GetY()[i];
878 }
879
880// sort/rank input x, y
881 Int_t *index = new Int_t[fNin];
882 Int_t *rank = new Int_t[fNin];
884
885// input X, Y
886 Int_t vNDup = 0;
887 Int_t k = 0;
888 Int_t *dup = new Int_t[fNin];
889 Double_t *x = new Double_t[fNin];
890 Double_t *y = new Double_t[fNin];
892 for (i=1;i<fNin+1;i++) {
893 Int_t ndup = 1;
894 vMin = vMean = vMax = yin[index[i-1]];
895 while ((i < fNin) && (rank[index[i]] == rank[index[i-1]])) {
896 vMean += yin[index[i]];
897 vMax = (vMax < yin[index[i]]) ? yin[index[i]] : vMax;
898 vMin = (vMin > yin[index[i]]) ? yin[index[i]] : vMin;
899 dup[vNDup] = i;
900 i++;
901 ndup++;
902 vNDup++;
903 }
904 x[k] = xin[index[i-1]];
905 if (ndup == 1) {y[k++] = yin[index[i-1]];}
906 else switch(iTies) {
907 case 1:
908 y[k++] = vMean/ndup;
909 break;
910 case 2:
911 y[k++] = vMin;
912 break;
913 case 3:
914 y[k++] = vMax;
915 break;
916 default:
917 y[k++] = vMean/ndup;
918 break;
919 }
920 }
921 fNin = k;
922
923// set unique sorted input data x,y as final graph points
924 fGin->Set(fNin);
925 for (i=0;i<fNin;i++) {
926 fGin->SetPoint(i, x[i], y[i]);
927 }
928
929 fMinX = fGin->GetX()[0]; //already sorted!
930 fMaxX = fGin->GetX()[fNin-1];
931
932// interpolate outside interval [min(x),max(x)]
933 switch(rule) {
934 case 1:
935 ylow = 0; // = nan("NAN") ??
936 yhigh = 0; // = nan("NAN") ??
937 break;
938 case 2:
939 ylow = fGin->GetY()[0];
940 yhigh = fGin->GetY()[fNin-1];
941 break;
942 default:
943 break;
944 }
945
946// cleanup
947 delete [] x;
948 delete [] y;
949 delete [] dup;
950 delete [] rank;
951 delete [] index;
952 delete [] xin;
953 delete [] yin;
954}
955
956////////////////////////////////////////////////////////////////////////////////
957/// Approximate data points
958/// \param[in] grin graph giving the coordinates of the points to be interpolated.
959/// Alternatively a single plotting structure can be specified:
960/// \param[in] option specifies the interpolation method to be used.
961/// Choices are "linear" (iKind = 1) or "constant" (iKind = 2).
962/// \param[in] nout If xout is not specified, interpolation takes place at n equally
963/// spaced points spanning the interval [min(x), max(x)], where
964/// nout = max(nout, number of input data).
965/// \param[in] xout an optional set of values specifying where interpolation is to
966/// take place.
967/// \param[in] yleft the value to be returned when input x values less than min(x).
968/// The default is defined by the value of rule given below.
969/// \param[in] yright the value to be returned when input x values greater than max(x).
970/// The default is defined by the value of rule given below.
971/// \param[in] rule an integer describing how interpolation is to take place outside
972/// the interval [min(x), max(x)]. If rule is 0 then the given yleft
973/// and yright values are returned, if it is 1 then 0 is returned
974/// for such points and if it is 2, the value at the closest data
975/// extreme is used.
976/// \param[in] f For method="constant" a number between 0 and 1 inclusive,
977/// indicating a compromise between left- and right-continuous step
978/// functions. If y0 and y1 are the values to the left and right of
979/// the point then the value is y0*f+y1*(1-f) so that f=0 is
980/// right-continuous and f=1 is left-continuous
981/// \param[in] ties Handling of tied x values. An integer describing a function with
982/// a single vector argument returning a single number result:
983/// - ties = "ordered" (iTies = 0): input x are "ordered"
984/// - ties = "mean" (iTies = 1): function "mean"
985/// - ties = "min" (iTies = 2): function "min"
986/// - ties = "max" (iTies = 3): function "max"
987///
988/// Details:
989///
990/// At least two complete (x, y) pairs are required.
991/// If there are duplicated (tied) x values and ties is a function it is
992/// applied to the y values for each distinct x value. Useful functions in
993/// this context include mean, min, and max.
994/// If ties="ordered" the x values are assumed to be already ordered. The
995/// first y value will be used for interpolation to the left and the last
996/// one for interpolation to the right.
997///
998/// Value:
999///
1000/// approx returns a graph with components x and y, containing n coordinates
1001/// which interpolate the given data points according to the method (and rule)
1002/// desired.
1003
1006{
1007 TString opt = option;
1008 opt.ToLower();
1009 Int_t iKind = 0;
1010 if (opt.Contains("linear")) iKind = 1;
1011 else if (opt.Contains("constant")) iKind = 2;
1012
1013 if (f < 0 || f > 1) {
1014 std::cout << "Error: Invalid f value" << std::endl;
1015 return nullptr;
1016 }
1017
1018 opt = ties;
1019 opt.ToLower();
1020 Int_t iTies = 0;
1021 if (opt.Contains("ordered")) {
1022 iTies = 0;
1023 } else if (opt.Contains("mean")) {
1024 iTies = 1;
1025 } else if (opt.Contains("min")) {
1026 iTies = 2;
1027 } else if (opt.Contains("max")) {
1028 iTies = 3;
1029 } else {
1030 std::cout << "Error: Method not known: " << ties << std::endl;
1031 return nullptr;
1032 }
1033
1034// input X, Y
1035 Double_t ylow = yleft;
1037 Approxin(grin, iKind, ylow, yhigh, rule, iTies);
1038
1039// output X, Y
1040 Double_t delta = 0;
1041 fNout = nout;
1042 if (xout == nullptr) {
1044 delta = (fMaxX - fMinX)/(fNout - 1);
1045 }
1046
1047 fGout = new TGraph(fNout);
1048
1049 Double_t x;
1050 for (Int_t i=0;i<fNout/2;i++) {
1051 if (xout == nullptr) x = fMinX + i*delta;
1052 else x = xout[i];
1053 Double_t yout = Approx1(x, f, fGin->GetX(), fGin->GetY(), fNin, iKind, ylow, yhigh);
1054 fGout->SetPoint(i, x, yout);
1055 }
1056 for (Int_t i=fNout/2;i<fNout;i++) {
1057 if (xout == nullptr) x = fMaxX + delta*(i + 1 - fNout);
1058 else x = xout[i];
1059 Double_t yout = Approx1(x, f, fGin->GetX(), fGin->GetY(), fNin, iKind, ylow, yhigh);
1060 fGout->SetPoint(i, x, yout);
1061 }
1062
1063 return fGout;
1064}
1065
1066////////////////////////////////////////////////////////////////////////////////
1067/// Approximate one data point.
1068/// Approximate y(v), given (x,y)[i], i = 0,..,n-1
1069/// Based on R function approx1: Translated to C++ by Christian Stratowa
1070/// (R source file: approx.c by R Development Core Team (C) 1999-2001)
1071
1074{
1075 Int_t i = 0;
1076 Int_t j = n - 1;
1077
1078// handle out-of-domain points
1079 if(v < x[i]) return ylow;
1080 if(v > x[j]) return yhigh;
1081
1082// find the correct interval by bisection
1083 while(i < j - 1) {
1084 Int_t ij = (i + j)/2;
1085 if(v < x[ij]) j = ij;
1086 else i = ij;
1087 }
1088
1089// interpolation
1090 if(v == x[j]) return y[j];
1091 if(v == x[i]) return y[i];
1092
1093 if(iKind == 1) { // linear
1094 return y[i] + (y[j] - y[i]) * ((v - x[i])/(x[j] - x[i]));
1095 } else { // 2 : constant
1096 return y[i] * (1-f) + y[j] * f;
1097 }
1098}
1099
1100// helper functions
1101////////////////////////////////////////////////////////////////////////////////
1102/// Static function
1103/// if (ISNAN(x)) return 1;
1104/// if (ISNAN(y)) return -1;
1105
1107{
1108 if (x < y) return -1;
1109 if (x > y) return 1;
1110 return 0;
1111}
1112
1113////////////////////////////////////////////////////////////////////////////////
1114/// Static function
1115/// based on R function rPsort: adapted to C++ by Christian Stratowa
1116/// (R source file: R_sort.c by R Development Core Team (C) 1999-2001)
1117
1119{
1120 Double_t v, w;
1121 Int_t pL, pR, i, j;
1122
1123 for (pL = 0, pR = n - 1; pL < pR; ) {
1124 v = x[k];
1125 for(i = pL, j = pR; i <= j;) {
1126 while (TGraphSmooth::Rcmp(x[i], v) < 0) i++;
1127 while (TGraphSmooth::Rcmp(v, x[j]) < 0) j--;
1128 if (i <= j) { w = x[i]; x[i++] = x[j]; x[j--] = w; }
1129 }
1130 if (j < k) pL = i;
1131 if (k < i) pR = j;
1132 }
1133}
1134
1135////////////////////////////////////////////////////////////////////////////////
1136/// static function
1137
1139{
1140 if (n <= 0) return;
1141 if (n == 1) {
1142 index[0] = 0;
1143 rank[0] = 0;
1144 return;
1145 }
1146
1148
1149 Int_t k = 0;
1150 for (Int_t i=0;i<n;i++) {
1151 if ((i > 0) && (a[index[i]] == a[index[i-1]])) {
1152 rank[index[i]] = i-1;
1153 k++;
1154 }
1155 rank[index[i]] = i-k;
1156 }
1157}
#define d(i)
Definition RSha256.hxx:102
#define b(i)
Definition RSha256.hxx:100
#define f(i)
Definition RSha256.hxx:104
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
#define h(i)
Definition RSha256.hxx:106
#define e(i)
Definition RSha256.hxx:103
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
constexpr Bool_t kFALSE
Definition RtypesCore.h:109
constexpr Bool_t kTRUE
Definition RtypesCore.h:108
const char Option_t
Option string (const char)
Definition RtypesCore.h:81
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t option
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t np
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
char name[80]
Definition TGX11.cxx:142
A TGraphErrors is a TGraph with error bars.
Double_t fMinX
Minimum value of array X.
TGraph * fGin
Input graph.
Double_t fMaxX
Maximum value of array X.
static Int_t Rcmp(Double_t x, Double_t y)
Static function if (ISNAN(x)) return 1; if (ISNAN(y)) return -1;.
TGraph * SmoothLowess(TGraph *grin, Option_t *option="", Double_t span=0.67, Int_t iter=3, Double_t delta=0)
Smooth data with Lowess smoother.
~TGraphSmooth() override
GraphSmooth destructor.
TGraph * SmoothSuper(TGraph *grin, Option_t *option="", Double_t bass=0, Double_t span=0, Bool_t isPeriodic=kFALSE, Double_t *w=nullptr)
Smooth data with Super smoother.
static void Rank(Int_t n, Double_t *a, Int_t *index, Int_t *rank, Bool_t down=kTRUE)
static function
Int_t fNout
Number of output points.
static void BDRksmooth(Double_t *x, Double_t *y, Int_t n, Double_t *xp, Double_t *yp, Int_t np, Int_t kernel, Double_t bw)
Smooth data with specified kernel.
Int_t fNin
Number of input points.
void Smoothin(TGraph *grin)
Sort input data points.
TGraph * SmoothKern(TGraph *grin, Option_t *option="normal", Double_t bandwidth=0.5, Int_t nout=100, Double_t *xout=nullptr)
Smooth data with Kernel smoother.
TGraph * Approx(TGraph *grin, Option_t *option="linear", Int_t nout=50, Double_t *xout=nullptr, Double_t yleft=0, Double_t yright=0, Int_t rule=0, Double_t f=0, Option_t *ties="mean")
Approximate data points.
static void BDRsupsmu(Int_t n, Double_t *x, Double_t *y, Double_t *w, Int_t iper, Double_t span, Double_t alpha, Double_t *smo, Double_t *sc)
Friedmanns super smoother (Friedman, 1984).
static void Psort(Double_t *x, Int_t n, Int_t k)
Static function based on R function rPsort: adapted to C++ by Christian Stratowa (R source file: R_so...
TGraph * fGout
Output graph.
static void Lowest(Double_t *x, Double_t *y, Int_t n, Double_t &xs, Double_t &ys, Int_t nleft, Int_t nright, Double_t *w, Bool_t userw, Double_t *rw, Bool_t &ok)
Fit value at x[i] Based on R function lowest: Translated to C++ by C.
static void BDRsmooth(Int_t n, Double_t *x, Double_t *y, Double_t *w, Double_t span, Int_t iper, Double_t vsmlsq, Double_t *smo, Double_t *acvr)
Function for super smoother Based on R function supsmu: Translated to C++ by C.
static Double_t Approx1(Double_t v, Double_t f, Double_t *x, Double_t *y, Int_t n, Int_t iKind, Double_t Ylow, Double_t Yhigh)
Approximate one data point.
void Lowess(Double_t *x, Double_t *y, Int_t n, Double_t *ys, Double_t span, Int_t iter, Double_t delta)
Lowess regression smoother.
void Approxin(TGraph *grin, Int_t iKind, Double_t &Ylow, Double_t &Yhigh, Int_t rule, Int_t iTies)
Sort data points and eliminate double x values.
A TGraph is an object made of two arrays X and Y with npoints each.
Definition TGraph.h:41
virtual void SetPoint(Int_t i, Double_t x, Double_t y)
Set x and y values for point number i.
Definition TGraph.cxx:2386
Double_t * GetY() const
Definition TGraph.h:139
Int_t GetN() const
Definition TGraph.h:131
Double_t * GetX() const
Definition TGraph.h:138
virtual void Set(Int_t n)
Set number of points in the graph Existing coordinates are preserved New coordinates above fNpoints a...
Definition TGraph.cxx:2314
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
Basic string class.
Definition TString.h:137
void ToLower()
Change string to lower-case.
Definition TString.cxx:1190
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:642
Double_t y[n]
Definition legend1.C:17
return c1
Definition legend1.C:41
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
TH1F * h1
Definition legend1.C:5
Short_t Max(Short_t a, Short_t b)
Returns the largest of a and b.
Definition TMathBase.h:249
Double_t Exp(Double_t x)
Returns the base-e exponential function of x, which is e raised to the power x.
Definition TMath.h:722
Double_t Sqrt(Double_t x)
Returns the square root of x.
Definition TMath.h:675
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Returns x raised to the power y.
Definition TMath.h:734
Short_t Min(Short_t a, Short_t b)
Returns the smallest of a and b.
Definition TMathBase.h:197
void Sort(Index n, const Element *a, Index *index, Bool_t down=kTRUE)
Sort the n elements of the array a of generic templated type Element.
Definition TMathBase.h:413
Short_t Abs(Short_t d)
Returns the absolute value of parameter Short_t d.
Definition TMathBase.h:122