Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
MathFuncs.h
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 * Authors:
4 * Jonas Rembser, CERN 2024
5 * Garima Singh, CERN 2023
6 *
7 * Copyright (c) 2024, CERN
8 *
9 * Redistribution and use in source and binary forms,
10 * with or without modification, are permitted according to the terms
11 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
12 */
13
14#ifndef RooFit_Detail_MathFuncs_h
15#define RooFit_Detail_MathFuncs_h
16
17#include <ROOT/RConfig.hxx> // for R__HAS_CLAD
18
19#include <TMath.h>
22
23#include <algorithm>
24#include <cmath>
25#include <limits>
26#include <stdexcept>
27
29
30/// Calculates the binomial coefficient n over k.
31/// Equivalent to TMath::Binomial, but inlined.
32inline double binomial(int n, int k)
33{
34 if (n < 0 || k < 0 || n < k)
35 return TMath::SignalingNaN();
36 if (k == 0 || n == k)
37 return 1;
38
39 int k1 = std::min(k, n - k);
40 int k2 = n - k1;
41 double fact = k2 + 1;
42 for (double i = k1; i > 1.; --i) {
43 fact *= (k2 + i) / i;
44 }
45 return fact;
46}
47
48/// The caller needs to make sure that there is at least one coefficient.
49template <typename DoubleArray>
50double bernstein(double x, double xmin, double xmax, DoubleArray coefs, int nCoefs)
51{
52 double xScaled = (x - xmin) / (xmax - xmin); // rescale to [0,1]
53 int degree = nCoefs - 1; // n+1 polys of degree n
54
55 // in case list of arguments passed is empty
56 if (degree < 0) {
57 return TMath::SignalingNaN();
58 } else if (degree == 0) {
59 return coefs[0];
60 } else if (degree == 1) {
61
62 double a0 = coefs[0]; // c0
63 double a1 = coefs[1] - a0; // c1 - c0
64 return a1 * xScaled + a0;
65
66 } else if (degree == 2) {
67
68 double a0 = coefs[0]; // c0
69 double a1 = 2 * (coefs[1] - a0); // 2 * (c1 - c0)
70 double a2 = coefs[2] - a1 - a0; // c0 - 2 * c1 + c2
71 return (a2 * xScaled + a1) * xScaled + a0;
72 }
73
74 double t = xScaled;
75 double s = 1. - xScaled;
76
77 double result = coefs[0] * s;
78 for (int i = 1; i < degree; i++) {
79 result = (result + t * binomial(degree, i) * coefs[i]) * s;
80 t *= xScaled;
81 }
82 result += t * coefs[degree];
83
84 return result;
85}
86
87/// Evaluate the logarithm of an un-normalized Gaussian.
88inline double logGaussian(double x, double mean, double sigma)
89{
90 const double arg = x - mean;
91 const double sig = sigma;
92 return -0.5 * arg * arg / (sig * sig);
93}
94
95/// @brief Function to evaluate an un-normalized Gaussian.
96inline double gaussian(double x, double mean, double sigma)
97{
98 return std::exp(logGaussian(x, mean, sigma));
99}
100
101template <typename DoubleArray>
102double product(DoubleArray factors, std::size_t nFactors)
103{
104 double out = 1.0;
105 for (std::size_t i = 0; i < nFactors; ++i) {
106 out *= factors[i];
107 }
108 return out;
109}
110
111// RooRatio evaluate function.
112inline double ratio(double numerator, double denominator)
113{
114 return numerator / denominator;
115}
116
117inline double bifurGauss(double x, double mean, double sigmaL, double sigmaR)
118{
119 // Note: this simplification does not work with Clad as of v1.1!
120 // return gaussian(x, mean, x < mean ? sigmaL : sigmaR);
121 if (x < mean)
122 return gaussian(x, mean, sigmaL);
123 return gaussian(x, mean, sigmaR);
124}
125
126inline double efficiency(double effFuncVal, int catIndex, int sigCatIndex)
127{
128 // Truncate efficiency function in range 0.0-1.0
129 effFuncVal = std::clamp(effFuncVal, 0.0, 1.0);
130
131 if (catIndex == sigCatIndex) {
132 return effFuncVal; // Accept case
133 } else {
134 return 1 - effFuncVal; // Reject case
135 }
136}
137
138/// In pdfMode, a coefficient for the constant term of 1.0 is implied if lowestOrder > 0.
139template <bool pdfMode = false, typename DoubleArray>
140double polynomial(DoubleArray coeffs, int nCoeffs, int lowestOrder, double x)
141{
142 double retVal = coeffs[nCoeffs - 1];
143 for (int i = nCoeffs - 2; i >= 0; i--) {
144 retVal = coeffs[i] + x * retVal;
145 }
146 retVal = retVal * std::pow(x, lowestOrder);
147 return retVal + (pdfMode && lowestOrder > 0 ? 1.0 : 0.0);
148}
149
150template <typename DoubleArray>
151double chebychev(DoubleArray coeffs, unsigned int nCoeffs, double x_in, double xMin, double xMax)
152{
153 // transform to range [-1, +1]
154 const double xPrime = (x_in - 0.5 * (xMax + xMin)) / (0.5 * (xMax - xMin));
155
156 // extract current values of coefficients
157 double sum = 1.;
158 if (nCoeffs > 0) {
159 double curr = xPrime;
160 double twox = 2 * xPrime;
161 double last = 1;
162 double newval = twox * curr - last;
163 last = curr;
164 curr = newval;
165 for (unsigned int i = 0; nCoeffs != i; ++i) {
166 sum += last * coeffs[i];
167 newval = twox * curr - last;
168 last = curr;
169 curr = newval;
170 }
171 }
172 return sum;
173}
174
175template <typename DoubleArray>
176double multipdf(int idx, DoubleArray pdfs)
177{
178 /* if (idx < 0 || idx >= static_cast<int>(pdfs.size())){
179 throw std::out_of_range("Invalid PDF index");
180
181 }
182 */
183 return pdfs[idx];
184}
185
186inline unsigned int uniformBinNumber(double low, double high, double val, unsigned int numBins, double coef)
187{
188 double binWidth = (high - low) / numBins;
189 return coef * (val >= high ? numBins - 1 : std::abs((val - low) / binWidth));
190}
191
192template <typename DoubleArray>
193unsigned int rawBinNumber(double x, DoubleArray boundaries, std::size_t nBoundaries)
194{
195 DoubleArray end = boundaries + nBoundaries;
196 DoubleArray it = std::lower_bound(boundaries, end, x);
197 // always return valid bin number
198 while (boundaries != it && (end == it || end == it + 1 || x < *it)) {
199 --it;
200 }
201 return it - boundaries;
202}
203
204template <typename DoubleArray>
205unsigned int binNumber(double x, double coef, DoubleArray boundaries, unsigned int nBoundaries, int nbins, int blo)
206{
207 const int rawBin = rawBinNumber(x, boundaries, nBoundaries);
208 int tmp = std::min(nbins, rawBin - blo);
209 return coef * std::max(0, tmp);
210}
211
212template <typename DoubleArray>
213double interpolate1d(double low, double high, double val, unsigned int numBins, DoubleArray vals)
214{
215 double binWidth = (high - low) / numBins;
216 int idx = val >= high ? numBins - 1 : std::abs((val - low) / binWidth);
217
218 // interpolation
219 double central = low + (idx + 0.5) * binWidth;
220 if (val > low + 0.5 * binWidth && val < high - 0.5 * binWidth) {
221 double slope;
222 if (val < central) {
223 slope = vals[idx] - vals[idx - 1];
224 } else {
225 slope = vals[idx + 1] - vals[idx];
226 }
227 return vals[idx] + slope * (val - central) / binWidth;
228 }
229
230 return vals[idx];
231}
232
233inline double poisson(double x, double par)
234{
235 if (par < 0)
236 return TMath::QuietNaN();
237
238 if (x < 0) {
239 return 0;
240 } else if (x == 0.0) {
241 return std::exp(-par);
242 } else {
243 double out = x * std::log(par) - TMath::LnGamma(x + 1.) - par;
244 return std::exp(out);
245 }
246}
247
248inline double flexibleInterpSingle(unsigned int code, double low, double high, double boundary, double nominal,
249 double paramVal, double res)
250{
251 if (code == 0) {
252 // piece-wise linear
253 if (paramVal > 0) {
254 return paramVal * (high - nominal);
255 } else {
256 return paramVal * (nominal - low);
257 }
258 } else if (code == 1) {
259 // piece-wise log
260 if (paramVal >= 0) {
261 return res * (std::pow(high / nominal, +paramVal) - 1);
262 } else {
263 return res * (std::pow(low / nominal, -paramVal) - 1);
264 }
265 } else if (code == 2) {
266 // parabolic with linear
267 double a = 0.5 * (high + low) - nominal;
268 double b = 0.5 * (high - low);
269 double c = 0;
270 if (paramVal > 1) {
271 return (2 * a + b) * (paramVal - 1) + high - nominal;
272 } else if (paramVal < -1) {
273 return -1 * (2 * a - b) * (paramVal + 1) + low - nominal;
274 } else {
275 return a * paramVal * paramVal + b * paramVal + c;
276 }
277 // According to an old comment in the source code, code 3 was apparently
278 // meant to be a "parabolic version of log-normal", but it never got
279 // implemented. If someone would need it, it could be implemented as doing
280 // code 2 in log space.
281 } else if (code == 4 || code == 6) {
282 double x = paramVal;
283 double mod = 1.0;
284 if (code == 6) {
285 high /= nominal;
286 low /= nominal;
287 nominal = 1;
288 }
289 if (x >= boundary) {
290 mod = x * (high - nominal);
291 } else if (x <= -boundary) {
292 mod = x * (nominal - low);
293 } else {
294 // interpolate 6th degree
295 double t = x / boundary;
296 double eps_plus = high - nominal;
297 double eps_minus = nominal - low;
298 double S = 0.5 * (eps_plus + eps_minus);
299 double A = 0.0625 * (eps_plus - eps_minus);
300
301 mod = x * (S + t * A * (15 + t * t * (-10 + t * t * 3)));
302 }
303
304 // code 6 is multiplicative version of code 4
305 if (code == 6) {
306 mod *= res;
307 }
308 return mod;
309
310 } else if (code == 5) {
311 double x = paramVal;
312 double mod = 1.0;
313 if (x >= boundary) {
314 mod = std::pow(high / nominal, +paramVal);
315 } else if (x <= -boundary) {
316 mod = std::pow(low / nominal, -paramVal);
317 } else {
318 // interpolate 6th degree exp
319 double x0 = boundary;
320
321 high /= nominal;
322 low /= nominal;
323
324 // GHL: Swagato's suggestions
325 double logHi = std::log(high);
326 double logLo = std::log(low);
327 double powUp = std::exp(x0 * logHi);
328 double powDown = std::exp(x0 * logLo);
329 double powUpLog = high <= 0.0 ? 0.0 : powUp * logHi;
330 double powDownLog = low <= 0.0 ? 0.0 : -powDown * logLo;
331 double powUpLog2 = high <= 0.0 ? 0.0 : powUpLog * logHi;
332 double powDownLog2 = low <= 0.0 ? 0.0 : -powDownLog * logLo;
333
334 double S0 = 0.5 * (powUp + powDown);
335 double A0 = 0.5 * (powUp - powDown);
336 double S1 = 0.5 * (powUpLog + powDownLog);
337 double A1 = 0.5 * (powUpLog - powDownLog);
338 double S2 = 0.5 * (powUpLog2 + powDownLog2);
339 double A2 = 0.5 * (powUpLog2 - powDownLog2);
340
341 // fcns+der+2nd_der are eq at bd
342
343 double x0Sq = x0 * x0;
344
345 double a = 1. / (8 * x0) * (15 * A0 - 7 * x0 * S1 + x0 * x0 * A2);
346 double b = 1. / (8 * x0Sq) * (-24 + 24 * S0 - 9 * x0 * A1 + x0 * x0 * S2);
347 double c = 1. / (4 * x0Sq * x0) * (-5 * A0 + 5 * x0 * S1 - x0 * x0 * A2);
348 double d = 1. / (4 * x0Sq * x0Sq) * (12 - 12 * S0 + 7 * x0 * A1 - x0 * x0 * S2);
349 double e = 1. / (8 * x0Sq * x0Sq * x0) * (+3 * A0 - 3 * x0 * S1 + x0 * x0 * A2);
350 double f = 1. / (8 * x0Sq * x0Sq * x0Sq) * (-8 + 8 * S0 - 5 * x0 * A1 + x0 * x0 * S2);
351
352 // evaluate the 6-th degree polynomial using Horner's method
353 double value = 1. + x * (a + x * (b + x * (c + x * (d + x * (e + x * f)))));
354 mod = value;
355 }
356 return res * (mod - 1.0);
357 }
358
359 return 0.0;
360}
361
362template <typename ParamsArray, typename DoubleArray>
363double flexibleInterp(unsigned int code, ParamsArray params, unsigned int n, DoubleArray low, DoubleArray high,
364 double boundary, double nominal, int doCutoff)
365{
366 double total = nominal;
367 for (std::size_t i = 0; i < n; ++i) {
368 total += flexibleInterpSingle(code, low[i], high[i], boundary, nominal, params[i], total);
369 }
370
371 return doCutoff && total <= 0 ? TMath::Limits<double>::Min() : total;
372}
373
374inline double landau(double x, double mu, double sigma)
375{
376 if (sigma <= 0.)
377 return 0.;
378 return ROOT::Math::landau_pdf((x - mu) / sigma);
379}
380
381inline double logNormal(double x, double k, double m0)
382{
383 return ROOT::Math::lognormal_pdf(x, std::log(m0), std::abs(std::log(k)));
384}
385
386inline double logNormalStandard(double x, double sigma, double mu)
387{
388 return ROOT::Math::lognormal_pdf(x, mu, std::abs(sigma));
389}
390
391inline double effProd(double eff, double pdf)
392{
393 return eff * pdf;
394}
395
396/// Chi-squared contribution of one bin with "expected" errors:
397/// \f$ \sigma^2 = \mu \f$. Empty/no-prediction bins contribute zero; bins with
398/// non-positive \f$ \mu \f$ but non-empty data yield NaN (to let the minimizer
399/// recover).
400inline double chi2Expected(double mu, double weight)
401{
402 if (mu == 0.0 && weight == 0.0) {
403 return 0.0;
404 }
405 if (mu <= 0.0) {
406 return std::numeric_limits<double>::quiet_NaN();
407 }
408 const double diff = mu - weight;
409 return diff * diff / mu;
410}
411
412/// Chi-squared contribution of one bin with a user-supplied symmetric error
413/// squared (e.g. `SumW2` weights from the data).
414inline double chi2Symmetric(double mu, double weight, double sigma2)
415{
416 if (sigma2 == 0.0 && mu == 0.0 && weight == 0.0) {
417 return 0.0;
418 }
419 if (sigma2 <= 0.0) {
420 return std::numeric_limits<double>::quiet_NaN();
421 }
422 const double diff = mu - weight;
423 return diff * diff / sigma2;
424}
425
426/// Chi-squared contribution of one bin with asymmetric (Poisson-style) data
427/// errors. The side facing the prediction is used: `errHi` when
428/// \f$ \mu > \mathrm{weight} \f$, otherwise `errLo`.
429inline double chi2Asymmetric(double mu, double weight, double errLo, double errHi)
430{
431 const double diff = mu - weight;
432 const double err = diff > 0.0 ? errHi : errLo;
433 const double sigma2 = err * err;
434 if (sigma2 == 0.0 && mu == 0.0 && weight == 0.0) {
435 return 0.0;
436 }
437 if (sigma2 <= 0.0) {
438 return std::numeric_limits<double>::quiet_NaN();
439 }
440 return diff * diff / sigma2;
441}
442
443/// The negative log-likelihood of one bin in a binned fit.
444inline double nll(double pdf, double weight, int doBinOffset)
445{
446 // Special handling of this case since std::log(Poisson(0,0)=0 but can't be
447 // calculated with usual log-formula since std::log(mu)=0. No update of result
448 // is required since term=0.
449 if (std::abs(pdf) < 1e-10 && std::abs(weight) < 1e-10) {
450 return 0.0;
451 }
452 if (doBinOffset) {
453 return pdf - weight - weight * (std::log(pdf) - std::log(weight));
454 }
455 return pdf - weight * std::log(pdf) + TMath::LnGamma(weight + 1);
456}
457
458template <typename DoubleArray>
459double recursiveFraction(DoubleArray a, unsigned int n)
460{
461 double prod = a[0];
462
463 for (unsigned int i = 1; i < n; ++i) {
464 prod *= 1.0 - a[i];
465 }
466
467 return prod;
468}
469
470inline double cbShape(double m, double m0, double sigma, double alpha, double n)
471{
472 double t = (m - m0) / sigma;
473 if (alpha < 0)
474 t = -t;
475
476 double absAlpha = std::abs(alpha);
477
478 if (t >= -absAlpha) {
479 return std::exp(-0.5 * t * t);
480 } else {
481 double r = n / absAlpha;
482 double a = std::exp(-0.5 * absAlpha * absAlpha);
483 double b = r - absAlpha;
484
485 return a * std::pow(r / (b - t), n);
486 }
487}
488
489// For RooCBShape
490inline double approxErf(double arg)
491{
492 if (arg > 5.0)
493 return 1.0;
494 if (arg < -5.0)
495 return -1.0;
496
497 return std::erf(arg);
498}
499
500/// @brief Function to calculate the integral of an un-normalized RooGaussian over x. To calculate the integral over
501/// mean, just interchange the respective values of x and mean.
502/// @param xMin Minimum value of variable to integrate wrt.
503/// @param xMax Maximum value of of variable to integrate wrt.
504/// @param mean Mean.
505/// @param sigma Sigma.
506/// @return The integral of an un-normalized RooGaussian over the value in x.
507inline double gaussianIntegral(double xMin, double xMax, double mean, double sigma)
508{
509 // The normalisation constant 1./sqrt(2*pi*sigma^2) is left out in evaluate().
510 // Therefore, the integral is scaled up by that amount to make RooFit normalise
511 // correctly.
512 double resultScale = 0.5 * std::sqrt(TMath::TwoPi()) * sigma;
513
514 // Here everything is scaled and shifted into a standard normal distribution:
515 double xscale = TMath::Sqrt2() * sigma;
516 double scaledMin = 0.;
517 double scaledMax = 0.;
518 scaledMin = (xMin - mean) / xscale;
519 scaledMax = (xMax - mean) / xscale;
520
521 // Here we go for maximum precision: We compute all integrals in the UPPER
522 // tail of the Gaussian, because erfc has the highest precision there.
523 // Therefore, the different cases for range limits in the negative hemisphere are mapped onto
524 // the equivalent points in the upper hemisphere using erfc(-x) = 2. - erfc(x)
525 double ecmin = std::erfc(std::abs(scaledMin));
526 double ecmax = std::erfc(std::abs(scaledMax));
527
528 double cond = 0.0;
529 // Don't put this "prd" inside the "if" because clad will not be able to differentiate the code correctly (as of
530 // v1.1)!
531 double prd = scaledMin * scaledMax;
532 if (prd < 0.0) {
533 cond = 2.0 - (ecmin + ecmax);
534 } else if (scaledMax <= 0.0) {
535 cond = ecmax - ecmin;
536 } else {
537 cond = ecmin - ecmax;
538 }
539 return resultScale * cond;
540}
541
542inline double bifurGaussIntegral(double xMin, double xMax, double mean, double sigmaL, double sigmaR)
543{
544 const double xscaleL = TMath::Sqrt2() * sigmaL;
545 const double xscaleR = TMath::Sqrt2() * sigmaR;
546
547 const double resultScale = 0.5 * std::sqrt(TMath::TwoPi());
548
549 if (xMax < mean) {
550 return resultScale * (sigmaL * (std::erf((xMax - mean) / xscaleL) - std::erf((xMin - mean) / xscaleL)));
551 } else if (xMin > mean) {
552 return resultScale * (sigmaR * (std::erf((xMax - mean) / xscaleR) - std::erf((xMin - mean) / xscaleR)));
553 } else {
554 return resultScale * (sigmaR * std::erf((xMax - mean) / xscaleR) - sigmaL * std::erf((xMin - mean) / xscaleL));
555 }
556}
557
558/// (exp(x) - 1) / x with the removable singularity at x = 0 filled in. The
559/// derivative is expm1OverXDerivative(), also registered with clad at the end
560/// of this header: differentiating the branches would give zero at x = 0.
561inline double expm1OverX(double x)
562{
563 return x == 0.0 ? 1.0 : std::expm1(x) / x;
564}
565
566/// Derivative of expm1OverX(). The closed form (x * exp(x) - expm1(x)) / x^2
567/// cancels for small x, so a Taylor expansion is used there. Both branches are
568/// accurate to about 1e-15 at the switching point.
569inline double expm1OverXDerivative(double x)
570{
571 if (std::abs(x) < 0.25) {
572 // Sum over n of (n + 1) x^n / (n + 2)!, up to n = 10 in Horner form.
573 // clang-format off
574 return 1. / 2 + x * (1. / 3 + x * (1. / 8 + x * (1. / 30 + x * (1. / 144 + x * (1. / 840
575 + x * (1. / 5760 + x * (1. / 45360 + x * (1. / 403200 + x * (1. / 3991680 + x * (1. / 43545600))))))))));
576 // clang-format on
577 }
578 return (std::exp(x) - expm1OverX(x)) / x;
579}
580
581/// Integral of exp(constant * x) from xMin to xMax. The naive form
582/// (exp(constant * xMax) - exp(constant * xMin)) / constant cancels when
583/// constant * (xMax - xMin) is small. Factoring out the larger exponential and
584/// using std::expm1 for the rest is accurate for any constant and only
585/// overflows if the integral itself does. The derivative with respect to the
586/// constant is exponentialIntegralDConstant(), also registered with clad at
587/// the end of this header (https://github.com/root-project/root/issues/23724).
588inline double exponentialIntegral(double xMin, double xMax, double constant)
589{
590 if (constant == 0.0) {
591 return xMax - xMin;
592 }
593
594 const double z = constant * (xMax - xMin);
595 if (z > 0.0) {
596 return -std::exp(constant * xMax) * std::expm1(-z) / constant;
597 }
598 return std::exp(constant * xMin) * std::expm1(z) / constant;
599}
600
601/// Derivative of exponentialIntegral() with respect to the constant, i.e. the
602/// integral of x * exp(constant * x). With a the endpoint where constant * x is
603/// larger and d the signed distance to the other one, substituting x = a + s
604/// gives exp(constant * a) * d * (a * expm1OverX(w) + d * expm1OverXDerivative(w))
605/// with w = constant * d <= 0, so the helpers only see bounded arguments.
606inline double exponentialIntegralDConstant(double xMin, double xMax, double constant)
607{
608 const bool fromMin = constant * (xMax - xMin) <= 0.0;
609 const double a = fromMin ? xMin : xMax;
610 const double d = fromMin ? xMax - xMin : xMin - xMax;
611 const double w = constant * d;
612 // The prefactor (xMax - xMin) instead of d absorbs the sign flip for a == xMax.
613 return std::exp(constant * a) * (xMax - xMin) * (a * expm1OverX(w) + d * expm1OverXDerivative(w));
614}
615
616/// In pdfMode, a coefficient for the constant term of 1.0 is implied if lowestOrder > 0.
617template <bool pdfMode = false, typename DoubleArray>
618double polynomialIntegral(DoubleArray coeffs, int nCoeffs, int lowestOrder, double xMin, double xMax)
619{
620 int denom = lowestOrder + nCoeffs;
621 double min = coeffs[nCoeffs - 1] / double(denom);
622 double max = coeffs[nCoeffs - 1] / double(denom);
623
624 for (int i = nCoeffs - 2; i >= 0; i--) {
625 denom--;
626 min = (coeffs[i] / double(denom)) + xMin * min;
627 max = (coeffs[i] / double(denom)) + xMax * max;
628 }
629
630 max = max * std::pow(xMax, 1 + lowestOrder);
631 min = min * std::pow(xMin, 1 + lowestOrder);
632
633 return max - min + (pdfMode && lowestOrder > 0.0 ? xMax - xMin : 0.0);
634}
635
636/// use fast FMA if available, fall back to normal arithmetic if not
637inline double fast_fma(double x, double y, double z) noexcept
638{
639#if defined(FP_FAST_FMA) // check if std::fma has fast hardware implementation
640 return std::fma(x, y, z);
641#else // defined(FP_FAST_FMA)
642 // std::fma might be slow, so use a more pedestrian implementation
643#if defined(__clang__)
644#pragma STDC FP_CONTRACT ON // hint clang that using an FMA is okay here
645#endif // defined(__clang__)
646 return (x * y) + z;
647#endif // defined(FP_FAST_FMA)
648}
649
650template <typename DoubleArray>
651double
652chebychevIntegral(DoubleArray coeffs, unsigned int nCoeffs, double xMin, double xMax, double xMinFull, double xMaxFull)
653{
654 const double halfrange = .5 * (xMax - xMin);
655 const double mid = .5 * (xMax + xMin);
656
657 // the full range of the function is mapped to the normalised [-1, 1] range
658 const double b = (xMaxFull - mid) / halfrange;
659 const double a = (xMinFull - mid) / halfrange;
660
661 // coefficient for integral(T_0(x)) is 1 (implicit), integrate by hand
662 // T_0(x) and T_1(x), and use for n > 1: integral(T_n(x) dx) =
663 // (T_n+1(x) / (n + 1) - T_n-1(x) / (n - 1)) / 2
664 double sum = b - a; // integrate T_0(x) by hand
665
666 const unsigned int iend = nCoeffs;
667 if (iend > 0) {
668 {
669 // integrate T_1(x) by hand...
670 const double c = coeffs[0];
671 sum = fast_fma(0.5 * (b + a) * (b - a), c, sum);
672 }
673 if (1 < iend) {
674 double bcurr = b;
675 double btwox = 2 * b;
676 double blast = 1;
677
678 double acurr = a;
679 double atwox = 2 * a;
680 double alast = 1;
681
682 double newval = atwox * acurr - alast;
683 alast = acurr;
684 acurr = newval;
685
686 newval = btwox * bcurr - blast;
687 blast = bcurr;
688 bcurr = newval;
689 double nminus1 = 1.;
690 for (unsigned int i = 1; iend != i; ++i) {
691 // integrate using recursion relation
692 const double c = coeffs[i];
693 const double term2 = (blast - alast) / nminus1;
694
695 newval = atwox * acurr - alast;
696 alast = acurr;
697 acurr = newval;
698
699 newval = btwox * bcurr - blast;
700 blast = bcurr;
701 bcurr = newval;
702
703 ++nminus1;
704 const double term1 = (bcurr - acurr) / (nminus1 + 1.);
705 const double intTn = 0.5 * (term1 - term2);
706 sum = fast_fma(intTn, c, sum);
707 }
708 }
709 }
710
711 // take care to multiply with the right factor to account for the mapping to
712 // normalised range [-1, 1]
713 return halfrange * sum;
714}
715
716// The last param should be of type bool but it is not as that causes some issues with Cling for some reason...
717inline double
718poissonIntegral(int code, double mu, double x, double integrandMin, double integrandMax, unsigned int protectNegative)
719{
720 if (protectNegative && mu < 0.0) {
721 return std::exp(-2.0 * mu); // make it fall quickly
722 }
723
724 if (code == 1) {
725 // Implement integral over x as summation. Add special handling in case
726 // range boundaries are not on integer values of x
727 integrandMin = std::max(0., integrandMin);
728
729 if (integrandMax < 0. || integrandMax < integrandMin) {
730 return 0;
731 }
732 const double delta = 100.0 * std::sqrt(mu);
733 // If the limits are more than many standard deviations away from the mean,
734 // we might as well return the integral of the full Poisson distribution to
735 // save computing time.
736 if (integrandMin < std::max(mu - delta, 0.0) && integrandMax > mu + delta) {
737 return 1.;
738 }
739
740 // The range as integers. ixMin is included, ixMax outside.
741 const unsigned int ixMin = integrandMin;
742 const unsigned int ixMax = std::min(integrandMax + 1, (double)std::numeric_limits<unsigned int>::max());
743
744 // Sum from 0 to just before the bin outside of the range.
745 if (ixMin == 0) {
746 return ROOT::Math::inc_gamma_c(ixMax, mu);
747 } else {
748 // If necessary, subtract from 0 to the beginning of the range
749 if (ixMin <= mu) {
750 return ROOT::Math::inc_gamma_c(ixMax, mu) - ROOT::Math::inc_gamma_c(ixMin, mu);
751 } else {
752 // Avoid catastrophic cancellation in the high tails:
753 return ROOT::Math::inc_gamma(ixMin, mu) - ROOT::Math::inc_gamma(ixMax, mu);
754 }
755 }
756 }
757
758 // the integral with respect to the mean is the integral of a gamma distribution
759 // negative ix does not need protection (gamma returns 0.0)
760 const double ix = 1 + x;
761
762 return ROOT::Math::inc_gamma(ix, integrandMax) - ROOT::Math::inc_gamma(ix, integrandMin);
763}
764
765inline double logNormalIntegral(double xMin, double xMax, double m0, double k)
766{
767 const double root2 = std::sqrt(2.);
768
769 double ln_k = std::abs(std::log(k));
770 double ret = 0.5 * (std::erf(std::log(xMax / m0) / (root2 * ln_k)) - std::erf(std::log(xMin / m0) / (root2 * ln_k)));
771
772 return ret;
773}
774
775inline double logNormalIntegralStandard(double xMin, double xMax, double mu, double sigma)
776{
777 const double root2 = std::sqrt(2.);
778
779 double ln_k = std::abs(sigma);
780 double ret =
781 0.5 * (std::erf((std::log(xMax) - mu) / (root2 * ln_k)) - std::erf((std::log(xMin) - mu) / (root2 * ln_k)));
782
783 return ret;
784}
785
786inline double cbShapeIntegral(double mMin, double mMax, double m0, double sigma, double alpha, double n)
787{
788 const double sqrtPiOver2 = 1.2533141373;
789 const double sqrt2 = 1.4142135624;
790
791 double result = 0.0;
792 bool useLog = false;
793
794 if (std::abs(n - 1.0) < 1.0e-05)
795 useLog = true;
796
797 double sig = std::abs(sigma);
798
799 double tmin = (mMin - m0) / sig;
800 double tmax = (mMax - m0) / sig;
801
802 if (alpha < 0) {
803 double tmp = tmin;
804 tmin = -tmax;
805 tmax = -tmp;
806 }
807
808 double absAlpha = std::abs(alpha);
809
810 if (tmin >= -absAlpha) {
811 result += sig * sqrtPiOver2 * (approxErf(tmax / sqrt2) - approxErf(tmin / sqrt2));
812 } else if (tmax <= -absAlpha) {
813 double r = n / absAlpha;
814 double a = r * std::exp(-0.5 * absAlpha * absAlpha);
815 double b = r - absAlpha;
816
817 if (useLog) {
818 double log_b_tmin = std::log(b - tmin);
819 double log_b_tmax = std::log(b - tmax);
820 result += a * std::pow(r, n - 1) * sig *
821 (log_b_tmin - log_b_tmax + 0.5 * (1.0 - n) * (log_b_tmin * log_b_tmin - log_b_tmax * log_b_tmax));
822 } else {
823 result += a * sig / (1.0 - n) * (std::pow(r / (b - tmin), n - 1.0) - std::pow(r / (b - tmax), n - 1.0));
824 }
825 } else {
826 double r = n / absAlpha;
827 double a = r * std::exp(-0.5 * absAlpha * absAlpha);
828 double b = r - absAlpha;
829
830 double term1 = 0.0;
831 if (useLog) {
832 double log_b_tmin = std::log(b - tmin);
833 double log_r = std::log(r);
834 term1 = a * std::pow(r, n - 1) * sig *
835 (log_b_tmin - log_r + 0.5 * (1.0 - n) * (log_b_tmin * log_b_tmin - log_r * log_r));
836 } else {
837 term1 = a * sig / (1.0 - n) * (std::pow(r / (b - tmin), n - 1.0) - 1.0);
838 }
839
840 double term2 = sig * sqrtPiOver2 * (approxErf(tmax / sqrt2) - approxErf(-absAlpha / sqrt2));
841
842 result += term1 + term2;
843 }
844
845 if (result == 0)
846 return 1.E-300;
847 return result;
848}
849
850template <typename DoubleArray>
851double bernsteinIntegral(double xlo, double xhi, double xmin, double xmax, DoubleArray coefs, int nCoefs)
852{
853 double xloScaled = (xlo - xmin) / (xmax - xmin);
854 double xhiScaled = (xhi - xmin) / (xmax - xmin);
855
856 int degree = nCoefs - 1; // n+1 polys of degree n
857 double norm = 0.;
858
859 for (int i = 0; i <= degree; ++i) {
860 // for each of the i Bernstein basis polynomials
861 // represent it in the 'power basis' (the naive polynomial basis)
862 // where the integral is straight forward.
863 double temp = 0.;
864 for (int j = i; j <= degree; ++j) { // power basisŧ
865 double binCoefs = binomial(degree, j) * binomial(j, i);
866 double oneOverJPlusOne = 1. / (j + 1.);
867 double powDiff = std::pow(xhiScaled, j + 1.) - std::pow(xloScaled, j + 1.);
868 temp += std::pow(-1., j - i) * binCoefs * powDiff * oneOverJPlusOne;
869 }
870 temp *= coefs[i]; // include coeff
871 norm += temp; // add this basis's contribution to total
872 }
873
874 return norm * (xmax - xmin);
875}
876
877template <typename XArray, typename MuArray, typename CovArray>
878double multiVarGaussian(int n, XArray x, MuArray mu, CovArray covI)
879{
880 double result = 0.0;
881
882 // Compute the bilinear form (x-mu)^T * covI * (x-mu)
883 for (int i = 0; i < n; ++i) {
884 for (int j = 0; j < n; ++j) {
885 result += (x[i] - mu[i]) * covI[i * n + j] * (x[j] - mu[j]);
886 }
887 }
888 return std::exp(-0.5 * result);
889}
890
891// Integral of a step function defined by `nBins` intervals, where the
892// intervals have values `coefs` and the boundary on the interval `iBin` is
893// given by `[boundaries[i], boundaries[i+1])`.
894template <typename DoubleArray>
895double stepFunctionIntegral(double xmin, double xmax, std::size_t nBins, DoubleArray boundaries, DoubleArray coefs)
896{
897 double out = 0.0;
898 for (std::size_t i = 0; i < nBins; ++i) {
899 double a = boundaries[i];
900 double b = boundaries[i + 1];
901 out += coefs[i] * std::max(0.0, std::min(b, xmax) - std::max(a, xmin));
902 }
903 return out;
904}
905
906} // namespace RooFit::Detail::MathFuncs
907
908namespace clad {
909// Only declared, never defined here: clad's own headers exist exclusively
910// inside the interpreter, but this header is also compiled normally.
911template <typename T, typename U>
913} // namespace clad
914
915namespace clad::custom_derivatives {
917
918// Clad can't generate the derivatives for binNumber because of the
919// std::lower_bound usage. But since binNumber returns an integer, and such
920// functions have mathematically no derivatives anyway, we just declare custom
921// dummy derivatives that do nothing.
922//
923// Both directions have to be covered: the pullback alone is enough for
924// gradients, but Hessians also run the forward pass over binNumber, and
925// without a pushforward clad descends into std::lower_bound.
926
927template <class... Types>
928void binNumber_pullback(Types...)
929{
930}
931
932// The second parameter is unused. It is what keeps the return type of the
933// pushforward below dependent, so that clad::ValueAndPushforward only has to be
934// complete once that template is instantiated. That happens under clad and
935// nowhere else, while parsing the declaration happens in every build that
936// includes this header. A class template is needed here: an alias template
937// would be expanded eagerly and defeat the purpose.
938template <typename T, typename>
942
943template <typename DoubleArray, class... Types>
945binNumber_pushforward(double x, double coef, DoubleArray boundaries, unsigned int nBoundaries, int nbins, int blo,
946 Types...)
947{
948 return {::RooFit::Detail::MathFuncs::binNumber(x, coef, boundaries, nBoundaries, nbins, blo), 0};
949}
950
951// Custom derivatives of exponentialIntegral and its helper expm1OverX, as
952// pullbacks for gradients and pushforwards for Hessians. Clad's derivatives of
953// the function bodies would be inaccurate for small constant * (xMax - xMin)
954// and identically zero in the == 0 branches
955// (https://github.com/root-project/root/issues/23724). The helper needs its
956// own because clad builds the Hessian by differentiating the pushforward body.
957//
958// The template parameters only keep the return types dependent, see
959// ValueAndPushforwardOf above. They are deliberately not deduced: clad passes
960// integer literals as derivatives of the integer literals in generated code.
961
962inline void expm1OverX_pullback(double x, double d_out, double *d_x)
963{
965}
966
967template <typename T = double>
972
973inline void exponentialIntegral_pullback(double xMin, double xMax, double constant, double d_out, double *d_xMin,
974 double *d_xMax, double *d_constant)
975{
976 *d_xMin -= d_out * ::std::exp(constant * xMin);
977 *d_xMax += d_out * ::std::exp(constant * xMax);
978 *d_constant += d_out * ::RooFit::Detail::MathFuncs::exponentialIntegralDConstant(xMin, xMax, constant);
979}
980
981template <typename T = double>
983exponentialIntegral_pushforward(double xMin, double xMax, double constant, double d_xMin, double d_xMax,
984 double d_constant)
985{
986 return {::RooFit::Detail::MathFuncs::exponentialIntegral(xMin, xMax, constant),
987 -::std::exp(constant * xMin) * d_xMin + ::std::exp(constant * xMax) * d_xMax +
988 ::RooFit::Detail::MathFuncs::exponentialIntegralDConstant(xMin, xMax, constant) * d_constant};
989}
990
991} // namespace RooFit::Detail::MathFuncs
992} // namespace clad::custom_derivatives
993
994#endif
#define d(i)
Definition RSha256.hxx:102
#define b(i)
Definition RSha256.hxx:100
#define f(i)
Definition RSha256.hxx:104
#define S0(x)
Definition RSha256.hxx:88
#define S1(x)
Definition RSha256.hxx:89
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
#define e(i)
Definition RSha256.hxx:103
static unsigned int total
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 Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
float xmin
float xmax
double lognormal_pdf(double x, double m, double s, double x0=0)
Probability density function of the lognormal distribution.
double landau_pdf(double x, double xi=1, double x0=0)
Probability density function of the Landau distribution:
double inc_gamma_c(double a, double x)
Calculates the normalized (regularized) upper incomplete gamma function (upper integral)
double inc_gamma(double a, double x)
Calculates the normalized (regularized) lower incomplete gamma function (lower integral)
const Double_t sigma
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
double exponentialIntegralDConstant(double xMin, double xMax, double constant)
Derivative of exponentialIntegral() with respect to the constant, i.e.
Definition MathFuncs.h:606
double polynomialIntegral(DoubleArray coeffs, int nCoeffs, int lowestOrder, double xMin, double xMax)
In pdfMode, a coefficient for the constant term of 1.0 is implied if lowestOrder > 0.
Definition MathFuncs.h:618
double logNormalIntegral(double xMin, double xMax, double m0, double k)
Definition MathFuncs.h:765
double gaussianIntegral(double xMin, double xMax, double mean, double sigma)
Function to calculate the integral of an un-normalized RooGaussian over x.
Definition MathFuncs.h:507
double flexibleInterp(unsigned int code, ParamsArray params, unsigned int n, DoubleArray low, DoubleArray high, double boundary, double nominal, int doCutoff)
Definition MathFuncs.h:363
double nll(double pdf, double weight, int doBinOffset)
The negative log-likelihood of one bin in a binned fit.
Definition MathFuncs.h:444
double bifurGaussIntegral(double xMin, double xMax, double mean, double sigmaL, double sigmaR)
Definition MathFuncs.h:542
double bernstein(double x, double xmin, double xmax, DoubleArray coefs, int nCoefs)
The caller needs to make sure that there is at least one coefficient.
Definition MathFuncs.h:50
double cbShape(double m, double m0, double sigma, double alpha, double n)
Definition MathFuncs.h:470
double multipdf(int idx, DoubleArray pdfs)
Definition MathFuncs.h:176
double chebychevIntegral(DoubleArray coeffs, unsigned int nCoeffs, double xMin, double xMax, double xMinFull, double xMaxFull)
Definition MathFuncs.h:652
double recursiveFraction(DoubleArray a, unsigned int n)
Definition MathFuncs.h:459
double cbShapeIntegral(double mMin, double mMax, double m0, double sigma, double alpha, double n)
Definition MathFuncs.h:786
double polynomial(DoubleArray coeffs, int nCoeffs, int lowestOrder, double x)
In pdfMode, a coefficient for the constant term of 1.0 is implied if lowestOrder > 0.
Definition MathFuncs.h:140
double fast_fma(double x, double y, double z) noexcept
use fast FMA if available, fall back to normal arithmetic if not
Definition MathFuncs.h:637
double logNormalIntegralStandard(double xMin, double xMax, double mu, double sigma)
Definition MathFuncs.h:775
double interpolate1d(double low, double high, double val, unsigned int numBins, DoubleArray vals)
Definition MathFuncs.h:213
double logGaussian(double x, double mean, double sigma)
Evaluate the logarithm of an un-normalized Gaussian.
Definition MathFuncs.h:88
double landau(double x, double mu, double sigma)
Definition MathFuncs.h:374
double gaussian(double x, double mean, double sigma)
Function to evaluate an un-normalized Gaussian.
Definition MathFuncs.h:96
double poisson(double x, double par)
Definition MathFuncs.h:233
double binomial(int n, int k)
Calculates the binomial coefficient n over k.
Definition MathFuncs.h:32
unsigned int uniformBinNumber(double low, double high, double val, unsigned int numBins, double coef)
Definition MathFuncs.h:186
double multiVarGaussian(int n, XArray x, MuArray mu, CovArray covI)
Definition MathFuncs.h:878
double flexibleInterpSingle(unsigned int code, double low, double high, double boundary, double nominal, double paramVal, double res)
Definition MathFuncs.h:248
double bernsteinIntegral(double xlo, double xhi, double xmin, double xmax, DoubleArray coefs, int nCoefs)
Definition MathFuncs.h:851
double chi2Asymmetric(double mu, double weight, double errLo, double errHi)
Chi-squared contribution of one bin with asymmetric (Poisson-style) data errors.
Definition MathFuncs.h:429
double chebychev(DoubleArray coeffs, unsigned int nCoeffs, double x_in, double xMin, double xMax)
Definition MathFuncs.h:151
double chi2Expected(double mu, double weight)
Chi-squared contribution of one bin with "expected" errors: .
Definition MathFuncs.h:400
double product(DoubleArray factors, std::size_t nFactors)
Definition MathFuncs.h:102
unsigned int rawBinNumber(double x, DoubleArray boundaries, std::size_t nBoundaries)
Definition MathFuncs.h:193
unsigned int binNumber(double x, double coef, DoubleArray boundaries, unsigned int nBoundaries, int nbins, int blo)
Definition MathFuncs.h:205
double chi2Symmetric(double mu, double weight, double sigma2)
Chi-squared contribution of one bin with a user-supplied symmetric error squared (e....
Definition MathFuncs.h:414
double logNormalStandard(double x, double sigma, double mu)
Definition MathFuncs.h:386
double bifurGauss(double x, double mean, double sigmaL, double sigmaR)
Definition MathFuncs.h:117
double ratio(double numerator, double denominator)
Definition MathFuncs.h:112
double expm1OverX(double x)
(exp(x) - 1) / x with the removable singularity at x = 0 filled in.
Definition MathFuncs.h:561
double approxErf(double arg)
Definition MathFuncs.h:490
double expm1OverXDerivative(double x)
Derivative of expm1OverX().
Definition MathFuncs.h:569
double effProd(double eff, double pdf)
Definition MathFuncs.h:391
double poissonIntegral(int code, double mu, double x, double integrandMin, double integrandMax, unsigned int protectNegative)
Definition MathFuncs.h:718
double logNormal(double x, double k, double m0)
Definition MathFuncs.h:381
double stepFunctionIntegral(double xmin, double xmax, std::size_t nBins, DoubleArray boundaries, DoubleArray coefs)
Definition MathFuncs.h:895
double efficiency(double effFuncVal, int catIndex, int sigCatIndex)
Definition MathFuncs.h:126
double exponentialIntegral(double xMin, double xMax, double constant)
Integral of exp(constant * x) from xMin to xMax.
Definition MathFuncs.h:588
Double_t QuietNaN()
Returns a quiet NaN as defined by IEEE 754.
Definition TMath.h:915
constexpr Double_t Sqrt2()
Definition TMath.h:89
Double_t LnGamma(Double_t z)
Computation of ln[gamma(z)] for all z.
Definition TMath.cxx:509
Double_t SignalingNaN()
Returns a signaling NaN as defined by IEEE 754.
Definition TMath.h:923
constexpr Double_t TwoPi()
Definition TMath.h:47
ValueAndPushforwardOf< unsignedint, DoubleArray >::type binNumber_pushforward(double x, double coef, DoubleArray boundaries, unsigned int nBoundaries, int nbins, int blo, Types...)
Definition MathFuncs.h:945
void exponentialIntegral_pullback(double xMin, double xMax, double constant, double d_out, double *d_xMin, double *d_xMax, double *d_constant)
Definition MathFuncs.h:973
ValueAndPushforwardOf< double, T >::type expm1OverX_pushforward(double x, double d_x)
Definition MathFuncs.h:968
ValueAndPushforwardOf< double, T >::type exponentialIntegral_pushforward(double xMin, double xMax, double constant, double d_xMin, double d_xMax, double d_constant)
Definition MathFuncs.h:983
void expm1OverX_pullback(double x, double d_out, double *d_x)
Definition MathFuncs.h:962
TMarker m
Definition textangle.C:8
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2335