source: tags/Mars-V0.10.2/mbase/MMath.cc

Last change on this file was 8029, checked in by tbretz, 18 years ago
*** empty log message ***
File size: 19.6 KB
Line 
1/* ======================================================================== *\
2!
3! *
4! * This file is part of MARS, the MAGIC Analysis and Reconstruction
5! * Software. It is distributed to you in the hope that it can be a useful
6! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
7! * It is distributed WITHOUT ANY WARRANTY.
8! *
9! * Permission to use, copy, modify and distribute this software and its
10! * documentation for any purpose is hereby granted without fee,
11! * provided that the above copyright notice appear in all copies and
12! * that both that copyright notice and this permission notice appear
13! * in supporting documentation. It is provided "as is" without express
14! * or implied warranty.
15! *
16!
17!
18! Author(s): Thomas Bretz 3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
19!
20! Copyright: MAGIC Software Development, 2000-2005
21!
22!
23\* ======================================================================== */
24
25/////////////////////////////////////////////////////////////////////////////
26//
27// MMath
28//
29// Mars - Math package (eg Significances, etc)
30//
31/////////////////////////////////////////////////////////////////////////////
32#include "MMath.h"
33
34#ifndef ROOT_TVector3
35#include <TVector3.h>
36#endif
37
38#ifndef ROOT_TArrayD
39#include <TArrayD.h>
40#endif
41
42#ifndef ROOT_TComplex
43#include <TComplex.h>
44#endif
45
46//NamespaceImp(MMath);
47
48// --------------------------------------------------------------------------
49//
50// Calculate Significance as
51// significance = (s-b)/sqrt(s+k*k*b) mit k=s/b
52//
53// s: total number of events in signal region
54// b: number of background events in signal region
55//
56Double_t MMath::Significance(Double_t s, Double_t b)
57{
58 const Double_t k = b==0 ? 0 : s/b;
59 const Double_t f = s+k*k*b;
60
61 return f==0 ? 0 : (s-b)/TMath::Sqrt(f);
62}
63
64// --------------------------------------------------------------------------
65//
66// Symmetrized significance - this is somehow analog to
67// SignificanceLiMaSigned
68//
69// Returns Significance(s,b) if s>b otherwise -Significance(b, s);
70//
71Double_t MMath::SignificanceSym(Double_t s, Double_t b)
72{
73 return s>b ? Significance(s, b) : -Significance(b, s);
74}
75
76// --------------------------------------------------------------------------
77//
78// calculates the significance according to Li & Ma
79// ApJ 272 (1983) 317, Formula 17
80//
81// s // s: number of on events
82// b // b: number of off events
83// alpha = t_on/t_off; // t: observation time
84//
85// The significance has the same (positive!) value for s>b and b>s.
86//
87// Returns -1 if s<0 or b<0 or alpha<0 or the argument of sqrt<0
88//
89// Here is some eMail written by Daniel Mazin about the meaning of the arguments:
90//
91// > Ok. Here is my understanding:
92// > According to Li&Ma paper (correctly cited in MMath.cc) alpha is the
93// > scaling factor. The mathematics behind the formula 17 (and/or 9) implies
94// > exactly this. If you scale OFF to ON first (using time or using any other
95// > method), then you cannot use formula 17 (9) anymore. You can just try
96// > the formula before scaling (alpha!=1) and after scaling (alpha=1), you
97// > will see the result will be different.
98//
99// > Here are less mathematical arguments:
100//
101// > 1) the better background determination you have (smaller alpha) the more
102// > significant is your excess, thus your analysis is more sensitive. If you
103// > normalize OFF to ON first, you loose this sensitivity.
104//
105// > 2) the normalization OFF to ON has an error, which naturally depends on
106// > the OFF and ON. This error is propagating to the significance of your
107// > excess if you use the Li&Ma formula 17 correctly. But if you normalize
108// > first and use then alpha=1, the error gets lost completely, you loose
109// > somehow the criteria of goodness of the normalization.
110//
111Double_t MMath::SignificanceLiMa(Double_t s, Double_t b, Double_t alpha)
112{
113 const Double_t sum = s+b;
114
115 if (s<0 || b<0 || alpha<=0)
116 return -1;
117
118 const Double_t l = s==0 ? 0 : s*TMath::Log(s/sum*(alpha+1)/alpha);
119 const Double_t m = b==0 ? 0 : b*TMath::Log(b/sum*(alpha+1) );
120
121 return l+m<0 ? -1 : TMath::Sqrt((l+m)*2);
122}
123
124// --------------------------------------------------------------------------
125//
126// Calculates MMath::SignificanceLiMa(s, b, alpha). Returns 0 if the
127// calculation has failed. Otherwise the Li/Ma significance which was
128// calculated. If s<b a negative value is returned.
129//
130Double_t MMath::SignificanceLiMaSigned(Double_t s, Double_t b, Double_t alpha)
131{
132 const Double_t sig = SignificanceLiMa(s, b, alpha);
133 if (sig<=0)
134 return 0;
135
136 return TMath::Sign(sig, s-alpha*b);
137}
138
139// --------------------------------------------------------------------------
140//
141// Return Li/Ma (5) for the error of the excess, under the assumption that
142// the existance of a signal is already known.
143//
144Double_t MMath::SignificanceLiMaExc(Double_t s, Double_t b, Double_t alpha)
145{
146 Double_t Ns = s - alpha*b;
147 Double_t sN = s + alpha*alpha*b;
148
149 return Ns<0 || sN<0 ? 0 : Ns/TMath::Sqrt(sN);
150}
151
152// --------------------------------------------------------------------------
153//
154// Returns: 2/(sigma*sqrt(2))*integral[0,x](exp(-(x-mu)^2/(2*sigma^2)))
155//
156Double_t MMath::GaussProb(Double_t x, Double_t sigma, Double_t mean)
157{
158 static const Double_t sqrt2 = TMath::Sqrt(2.);
159
160 const Double_t rc = TMath::Erf((x-mean)/(sigma*sqrt2));
161
162 if (rc<0)
163 return 0;
164 if (rc>1)
165 return 1;
166
167 return rc;
168}
169
170// ------------------------------------------------------------------------
171//
172// Return the "median" (at 68.3%) value of the distribution of
173// abs(a[i]-Median)
174//
175template <class Size, class Element>
176Double_t MMath::MedianDevImp(Size n, const Element *a, Double_t &med)
177{
178 static const Double_t prob = 0.682689477208650697; //MMath::GaussProb(1.0);
179
180 // Sanity check
181 if (n <= 0 || !a)
182 return 0;
183
184 // Get median of distribution
185 med = TMath::Median(n, a);
186
187 // Create the abs(a[i]-med) distribution
188 Double_t arr[n];
189 for (int i=0; i<n; i++)
190 arr[i] = TMath::Abs(a[i]-med);
191
192 // FIXME: GausProb() is a workaround. It should be taken into account in Median!
193 //return TMath::Median(n, arr);
194
195 // Sort distribution
196 Long64_t idx[n];
197 TMath::SortImp(n, arr, idx, kTRUE);
198
199 // Define where to divide
200 const Int_t div = TMath::Nint(n*prob);
201
202 // Calculate result
203 Double_t dev = TMath::KOrdStat(n, arr, div, idx);
204 if (n%2 == 0)
205 {
206 dev += TMath::KOrdStat(n, arr, div-1, idx);
207 dev /= 2;
208 }
209
210 return dev;
211}
212
213// ------------------------------------------------------------------------
214//
215// Return the "median" (at 68.3%) value of the distribution of
216// abs(a[i]-Median)
217//
218Double_t MMath::MedianDev(Long64_t n, const Short_t *a, Double_t &med)
219{
220 return MedianDevImp(n, a, med);
221}
222
223// ------------------------------------------------------------------------
224//
225// Return the "median" (at 68.3%) value of the distribution of
226// abs(a[i]-Median)
227//
228Double_t MMath::MedianDev(Long64_t n, const Int_t *a, Double_t &med)
229{
230 return MedianDevImp(n, a, med);
231}
232
233// ------------------------------------------------------------------------
234//
235// Return the "median" (at 68.3%) value of the distribution of
236// abs(a[i]-Median)
237//
238Double_t MMath::MedianDev(Long64_t n, const Float_t *a, Double_t &med)
239{
240 return MedianDevImp(n, a, med);
241}
242
243// ------------------------------------------------------------------------
244//
245// Return the "median" (at 68.3%) value of the distribution of
246// abs(a[i]-Median)
247//
248Double_t MMath::MedianDev(Long64_t n, const Double_t *a, Double_t &med)
249{
250 return MedianDevImp(n, a, med);
251}
252
253// ------------------------------------------------------------------------
254//
255// Return the "median" (at 68.3%) value of the distribution of
256// abs(a[i]-Median)
257//
258Double_t MMath::MedianDev(Long64_t n, const Long_t *a, Double_t &med)
259{
260 return MedianDevImp(n, a, med);
261}
262
263// ------------------------------------------------------------------------
264//
265// Return the "median" (at 68.3%) value of the distribution of
266// abs(a[i]-Median)
267//
268Double_t MMath::MedianDev(Long64_t n, const Long64_t *a, Double_t &med)
269{
270 return MedianDevImp(n, a, med);
271}
272
273Double_t MMath::MedianDev(Long64_t n, const Short_t *a) { Double_t med; return MedianDevImp(n, a, med); }
274Double_t MMath::MedianDev(Long64_t n, const Int_t *a) { Double_t med; return MedianDevImp(n, a, med); }
275Double_t MMath::MedianDev(Long64_t n, const Float_t *a) { Double_t med; return MedianDevImp(n, a, med); }
276Double_t MMath::MedianDev(Long64_t n, const Double_t *a) { Double_t med; return MedianDevImp(n, a, med); }
277Double_t MMath::MedianDev(Long64_t n, const Long_t *a) { Double_t med; return MedianDevImp(n, a, med); }
278Double_t MMath::MedianDev(Long64_t n, const Long64_t *a) { Double_t med; return MedianDevImp(n, a, med); }
279
280// --------------------------------------------------------------------------
281//
282// This function reduces the precision to roughly 0.5% of a Float_t by
283// changing its bit-pattern (Be carefull, in rare cases this function must
284// be adapted to different machines!). This is usefull to enforce better
285// compression by eg. gzip.
286//
287void MMath::ReducePrecision(Float_t &val)
288{
289 UInt_t &f = (UInt_t&)val;
290
291 f += 0x00004000;
292 f &= 0xffff8000;
293}
294
295// -------------------------------------------------------------------------
296//
297// Quadratic interpolation
298//
299// calculate the parameters of a parabula such that
300// y(i) = a + b*x(i) + c*x(i)^2
301//
302// If the determinant==0 an empty TVector3 is returned.
303//
304TVector3 MMath::GetParab(const TVector3 &x, const TVector3 &y)
305{
306 Double_t x1 = x(0);
307 Double_t x2 = x(1);
308 Double_t x3 = x(2);
309
310 Double_t y1 = y(0);
311 Double_t y2 = y(1);
312 Double_t y3 = y(2);
313
314 const double det =
315 + x2*x3*x3 + x1*x2*x2 + x3*x1*x1
316 - x2*x1*x1 - x3*x2*x2 - x1*x3*x3;
317
318
319 if (det==0)
320 return TVector3();
321
322 const double det1 = 1.0/det;
323
324 const double ai11 = x2*x3*x3 - x3*x2*x2;
325 const double ai12 = x3*x1*x1 - x1*x3*x3;
326 const double ai13 = x1*x2*x2 - x2*x1*x1;
327
328 const double ai21 = x2*x2 - x3*x3;
329 const double ai22 = x3*x3 - x1*x1;
330 const double ai23 = x1*x1 - x2*x2;
331
332 const double ai31 = x3 - x2;
333 const double ai32 = x1 - x3;
334 const double ai33 = x2 - x1;
335
336 return TVector3((ai11*y1 + ai12*y2 + ai13*y3) * det1,
337 (ai21*y1 + ai22*y2 + ai23*y3) * det1,
338 (ai31*y1 + ai32*y2 + ai33*y3) * det1);
339}
340
341Double_t MMath::InterpolParabLin(const TVector3 &vx, const TVector3 &vy, Double_t x)
342{
343 const TVector3 c = GetParab(vx, vy);
344 return c(0) + c(1)*x + c(2)*x*x;
345}
346
347Double_t MMath::InterpolParabLog(const TVector3 &vx, const TVector3 &vy, Double_t x)
348{
349 const Double_t l0 = TMath::Log10(vx(0));
350 const Double_t l1 = TMath::Log10(vx(1));
351 const Double_t l2 = TMath::Log10(vx(2));
352
353 const TVector3 vx0(l0, l1, l2);
354 return InterpolParabLin(vx0, vy, TMath::Log10(x));
355}
356
357Double_t MMath::InterpolParabCos(const TVector3 &vx, const TVector3 &vy, Double_t x)
358{
359 const Double_t l0 = TMath::Cos(vx(0));
360 const Double_t l1 = TMath::Cos(vx(1));
361 const Double_t l2 = TMath::Cos(vx(2));
362
363 const TVector3 vx0(l0, l1, l2);
364 return InterpolParabLin(vx0, vy, TMath::Cos(x));
365}
366
367// --------------------------------------------------------------------------
368//
369// Analytically calculated result of a least square fit of:
370// y = A*e^(B*x)
371// Equal weights
372//
373// It returns TArrayD(2) = { A, B };
374//
375// see: http://mathworld.wolfram.com/LeastSquaresFittingExponential.html
376//
377TArrayD MMath::LeastSqFitExpW1(Int_t n, Double_t *x, Double_t *y)
378{
379 Double_t sumxsqy = 0;
380 Double_t sumylny = 0;
381 Double_t sumxy = 0;
382 Double_t sumy = 0;
383 Double_t sumxylny = 0;
384 for (int i=0; i<n; i++)
385 {
386 sumylny += y[i]*TMath::Log(y[i]);
387 sumxy += x[i]*y[i];
388 sumxsqy += x[i]*x[i]*y[i];
389 sumxylny += x[i]*y[i]*TMath::Log(y[i]);
390 sumy += y[i];
391 }
392
393 const Double_t dev = sumy*sumxsqy - sumxy*sumxy;
394
395 const Double_t a = (sumxsqy*sumylny - sumxy*sumxylny)/dev;
396 const Double_t b = (sumy*sumxylny - sumxy*sumylny)/dev;
397
398 TArrayD rc(2);
399 rc[0] = TMath::Exp(a);
400 rc[1] = b;
401 return rc;
402}
403
404// --------------------------------------------------------------------------
405//
406// Analytically calculated result of a least square fit of:
407// y = A*e^(B*x)
408// Greater weights to smaller values
409//
410// It returns TArrayD(2) = { A, B };
411//
412// see: http://mathworld.wolfram.com/LeastSquaresFittingExponential.html
413//
414TArrayD MMath::LeastSqFitExp(Int_t n, Double_t *x, Double_t *y)
415{
416 // -------- Greater weights to smaller values ---------
417 Double_t sumlny = 0;
418 Double_t sumxlny = 0;
419 Double_t sumxsq = 0;
420 Double_t sumx = 0;
421 for (int i=0; i<n; i++)
422 {
423 sumlny += TMath::Log(y[i]);
424 sumxlny += x[i]*TMath::Log(y[i]);
425
426 sumxsq += x[i]*x[i];
427 sumx += x[i];
428 }
429
430 const Double_t dev = n*sumxsq-sumx*sumx;
431
432 const Double_t a = (sumlny*sumxsq - sumx*sumxlny)/dev;
433 const Double_t b = (n*sumxlny - sumx*sumlny)/dev;
434
435 TArrayD rc(2);
436 rc[0] = TMath::Exp(a);
437 rc[1] = b;
438 return rc;
439}
440
441// --------------------------------------------------------------------------
442//
443// Analytically calculated result of a least square fit of:
444// y = A+B*ln(x)
445//
446// It returns TArrayD(2) = { A, B };
447//
448// see: http://mathworld.wolfram.com/LeastSquaresFittingLogarithmic.html
449//
450TArrayD MMath::LeastSqFitLog(Int_t n, Double_t *x, Double_t *y)
451{
452 Double_t sumylnx = 0;
453 Double_t sumy = 0;
454 Double_t sumlnx = 0;
455 Double_t sumlnxsq = 0;
456 for (int i=0; i<n; i++)
457 {
458 sumylnx += y[i]*TMath::Log(x[i]);
459 sumy += y[i];
460 sumlnx += TMath::Log(x[i]);
461 sumlnxsq += TMath::Log(x[i])*TMath::Log(x[i]);
462 }
463
464 const Double_t b = (n*sumylnx-sumy*sumlnx)/(n*sumlnxsq-sumlnx*sumlnx);
465 const Double_t a = (sumy-b*sumlnx)/n;
466
467 TArrayD rc(2);
468 rc[0] = a;
469 rc[1] = b;
470 return rc;
471}
472
473// --------------------------------------------------------------------------
474//
475// Analytically calculated result of a least square fit of:
476// y = A*x^B
477//
478// It returns TArrayD(2) = { A, B };
479//
480// see: http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html
481//
482TArrayD MMath::LeastSqFitPowerLaw(Int_t n, Double_t *x, Double_t *y)
483{
484 Double_t sumlnxlny = 0;
485 Double_t sumlnx = 0;
486 Double_t sumlny = 0;
487 Double_t sumlnxsq = 0;
488 for (int i=0; i<n; i++)
489 {
490 sumlnxlny += TMath::Log(x[i])*TMath::Log(y[i]);
491 sumlnx += TMath::Log(x[i]);
492 sumlny += TMath::Log(y[i]);
493 sumlnxsq += TMath::Log(x[i])*TMath::Log(x[i]);
494 }
495
496 const Double_t b = (n*sumlnxlny-sumlnx*sumlny)/(n*sumlnxsq-sumlnx*sumlnx);
497 const Double_t a = (sumlny-b*sumlnx)/n;
498
499 TArrayD rc(2);
500 rc[0] = TMath::Exp(a);
501 rc[1] = b;
502 return rc;
503}
504
505// --------------------------------------------------------------------------
506//
507// Solves: x^2 + ax + b = 0;
508// Return number of solutions returned as x1, x2
509//
510Int_t MMath::SolvePol2(Double_t a, Double_t b, Double_t &x1, Double_t &x2)
511{
512 const Double_t r = a*a - 4*b;
513 if (r<0)
514 return 0;
515
516 if (r==0)
517 {
518 x1 = -a/2;
519 return 1;
520 }
521
522 const Double_t s = TMath::Sqrt(r);
523
524 x1 = (-a+s)/2;
525 x2 = (-a-s)/2;
526
527 return 2;
528}
529
530// --------------------------------------------------------------------------
531//
532// This is a helper function making the execution of SolverPol3 a bit faster
533//
534static inline Double_t ReMul(const TComplex &c1, const TComplex &th)
535{
536 const TComplex c2 = TComplex::Cos(th/3.);
537 return c1.Re() * c2.Re() - c1.Im() * c2.Im();
538}
539
540// --------------------------------------------------------------------------
541//
542// Solves: x^3 + ax^2 + bx + c = 0;
543// Return number of the real solutions, returned as z1, z2, z3
544//
545// Algorithm adapted from http://home.att.net/~srschmitt/cubizen.heml
546// Which is based on the solution given in
547// http://mathworld.wolfram.com/CubicEquation.html
548//
549// -------------------------------------------------------------------------
550//
551// Exact solutions of cubic polynomial equations
552// by Stephen R. Schmitt Algorithm
553//
554// An exact solution of the cubic polynomial equation:
555//
556// x^3 + a*x^2 + b*x + c = 0
557//
558// was first published by Gerolamo Cardano (1501-1576) in his treatise,
559// Ars Magna. He did not discoverer of the solution; a professor of
560// mathematics at the University of Bologna named Scipione del Ferro (ca.
561// 1465-1526) is credited as the first to find an exact solution. In the
562// years since, several improvements to the original solution have been
563// discovered. Zeno source code
564//
565// % compute real or complex roots of cubic polynomial
566// function cubic( var z1, z2, z3 : real, a, b, c : real ) : real
567//
568// var Q, R, D, S, T : real
569// var im, th : real
570//
571// Q := (3*b - a^2)/9
572// R := (9*b*a - 27*c - 2*a^3)/54
573// D := Q^3 + R^2 % polynomial discriminant
574//
575// if (D >= 0) then % complex or duplicate roots
576//
577// S := sgn(R + sqrt(D))*abs(R + sqrt(D))^(1/3)
578// T := sgn(R - sqrt(D))*abs(R - sqrt(D))^(1/3)
579//
580// z1 := -a/3 + (S + T) % real root
581// z2 := -a/3 - (S + T)/2 % real part of complex root
582// z3 := -a/3 - (S + T)/2 % real part of complex root
583// im := abs(sqrt(3)*(S - T)/2) % complex part of root pair
584//
585// else % distinct real roots
586//
587// th := arccos(R/sqrt( -Q^3))
588//
589// z1 := 2*sqrt(-Q)*cos(th/3) - a/3
590// z2 := 2*sqrt(-Q)*cos((th + 2*pi)/3) - a/3
591// z3 := 2*sqrt(-Q)*cos((th + 4*pi)/3) - a/3
592// im := 0
593//
594// end if
595//
596// return im % imaginary part
597//
598// end function
599//
600Int_t MMath::SolvePol3(Double_t a, Double_t b, Double_t c,
601 Double_t &x1, Double_t &x2, Double_t &x3)
602{
603 const Double_t Q = (a*a - 3*b)/9;
604 const Double_t R = (9*b*a - 27*c - 2*a*a*a)/54;
605 const Double_t D = R*R - Q*Q*Q; // polynomial discriminant
606
607 // ----- The single-real / duplicate-roots solution -----
608
609 if (D==0)
610 {
611 const Double_t r = MMath::Sqrt3(R);
612
613 x1 = 2*r - a/3.; // real root
614 x2 = r - a/3.; // real root
615
616 return 2;
617 }
618
619 if (D>0) // complex or duplicate roots
620 {
621 const Double_t sqrtd = TMath::Sqrt(D);
622
623 const Double_t S = MMath::Sqrt3(R + sqrtd);
624 const Double_t T = MMath::Sqrt3(R - sqrtd);
625
626 x1 = (S+T) - a/3.; // real root
627
628 return 1;
629
630 //z2 = (S + T)/2 - a/3.; // real part of complex root
631 //z3 = (S + T)/2 - a/3.; // real part of complex root
632 //im = fabs(sqrt(3)*(S - T)/2) // complex part of root pair
633 }
634
635 // ----- The general solution with three roots ---
636
637 if (Q==0)
638 return 0;
639
640 if (Q>0) // This is here for speed reasons
641 {
642 const Double_t sqrtq = TMath::Sqrt(Q);
643 const Double_t rq = R/TMath::Abs(Q);
644
645 const Double_t th1 = TMath::ACos(rq/sqrtq);
646 const Double_t th2 = th1 + TMath::TwoPi();
647 const Double_t th3 = th2 + TMath::TwoPi();
648
649 x1 = 2.*sqrtq * TMath::Cos(th1/3.) - a/3.;
650 x2 = 2.*sqrtq * TMath::Cos(th2/3.) - a/3.;
651 x3 = 2.*sqrtq * TMath::Cos(th3/3.) - a/3.;
652
653 return 3;
654 }
655
656 const TComplex sqrtq = TComplex::Sqrt(Q);
657 const Double_t rq = R/TMath::Abs(Q);
658
659 const TComplex th1 = TComplex::ACos(rq/sqrtq);
660 const TComplex th2 = th1 + TMath::TwoPi();
661 const TComplex th3 = th2 + TMath::TwoPi();
662
663 // For ReMul, see bove
664 x1 = ReMul(2.*sqrtq, th1) - a/3.;
665 x2 = ReMul(2.*sqrtq, th2) - a/3.;
666 x3 = ReMul(2.*sqrtq, th3) - a/3.;
667
668 return 3;
669}
Note: See TracBrowser for help on using the repository browser.