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