source: trunk/MagicSoft/Mars/mbase/MMath.cc@ 7999

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