source: tags/Mars-V0.8.4/mdata/MDataChain.cc

Last change on this file was 3666, checked in by tbretz, 21 years ago
*** empty log message ***
File size: 22.1 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 04/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
19!
20! Copyright: MAGIC Software Development, 2000-2004
21!
22!
23\* ======================================================================== */
24
25/////////////////////////////////////////////////////////////////////////////
26//
27// MDataChain
28// ==========
29//
30// With this chain you can concatenate simple mathematical operations on
31// members of mars containers.
32//
33//
34// Rules
35// -----
36//
37// In the constructor you can give rule, like
38// "HillasSource.fDist / MHillas.fLength"
39// Where MHillas/HillasSource is the name of the parameter container in
40// the parameter list and fDist/fLength is the name of the data members
41// in the containers. The result will be fDist divided by fLength.
42//
43// In case you want to access a data-member which is a data member object
44// you can acces it with (Remark: it must derive from MParContainer):
45// "MCameraLV.fPowerSupplyA.fVoltagePos5V"
46//
47// You can also use brackets:
48// "HillasDource.fDist / (MHillas.fLength + MHillas.fWidth)"
49//
50//
51// Operators
52// ---------
53//
54// The allowed operations are: +, -, *, /, %, ^
55//
56// While a%b returns the floating point reminder of a/b.
57// While a^b returns a to the power of b
58//
59// Warning: There is no priority rule build in. So better use brackets
60// to get correct results. The rule is parsed/evaluated from the left
61// to the right, which means:
62//
63// "MHillas.fWidth + MHillas.fLength / HillasSource.fDist"
64//
65// is parses as
66//
67// "(MHillas.fWidth + MHillas.fLength) / HillasSource.fDist"
68//
69// You can also use mathmatical operators, eg:
70// "5*log10(MMcEvt.fEnergy*MHillas.fSize)"
71//
72// The allowed operators are:
73// exp(x) e^x
74// log(x) natural logarithm of x
75// pow10(x) 10^x
76// log2(x) logarithm of x to base two
77// log10(x) logarithm of x to base ten
78// cos(x) cosine of x
79// sin(x) sine of x
80// tan(x) tangent of x
81// cosh(x) hyperbolic cosine of x
82// sinh(x) hyperbolic sine of x
83// tanh(x) hyperbolic tangent of x
84// acosh(x) arc hyperbolic cosine of x
85// asinh(x) arc hyperbolic sine of x
86// atanh(x) arc hyperbolic tangent of x
87// acos(x) arc cosine (inverse cosine) of x
88// asin(x) arc sine (inverse sine) of x
89// atan(x) arc tangent (inverse tangent) of x
90// sqrt(x) square root of x
91// sqr(x) square of x
92// abs(x) absolute value of x, |x|
93// floor(x) round down to the nearest integer (floor(9.9)=9)
94// ceil(x) round up to the nearest integer (floor(9.1)=10)
95// round(x) round to the nearest integer
96// r2d(x) transform radians to degrees
97// d2r(x) transform degrees to radians
98// rand(x) returns a uniform deviate on the interval ( 0, x ].
99// (gRandom->Uniform(x) is returned)
100// randp(x) returns gRandom->Poisson(x)
101// rande(x) returns gRandom->Exp(x)
102// randi(x) returns gRandom->Integer(x)
103// randg(x) returns gRandom->Gaus(0, x)
104// randl(x) returns gRandom->Landau(0, x)
105// isnan(x) return 1 if x is NaN (Not a Number) otherwise 0
106// finite(x) return 1 if the number is a valid double (not NaN, inf)
107//
108// NaN (Not a Number) means normally a number which is to small to be
109// stored in a floating point variable (eg. 0<x<1e-56 or similar) or
110// a number which function is not defined (like asin(1.5))
111//
112// inf is the symbol for an infinite number.
113//
114//
115// Constants
116// ---------
117//
118// Constants are implemented in ParseDataMember, namely:
119// kPi: TMath::Pi()
120// kRad2Deg: 180/kPi
121// kDeg2Rad: kPi/180
122//
123// You can also defined constants which are defined in TMath by:
124// kLn10 for static Double_t TMath::Ln10();
125// kLogE for static Double_t TMath::LogE();
126// kRadToDeg for static Double_t TMath::RadToDeg();
127// kDegToRad for static Double_t TMath::DegToRad();
128// ...
129//
130// Remark:
131// In older root versions only Pi() and E() are implemented
132// in TMath.
133//
134//
135// Variable Parameters
136// ------------------------
137// If you want to use variables, eg for fits you can use [0], [1], ...
138// These values are initialized with 0 and set by calling
139// SetVariables().
140//
141//
142// Multi-argument functions
143// ------------------------
144// You can use multi-argument functions, too. The access is implemented
145// via TFormula, which slows down thing a lot. If you can avoid usage
146// of such expression you accelerate the access a lot. Example:
147// "TMath::Hypot(MHillas.fMeanX, MHillas.MeanY)"
148// "pow(MHillas.fMeanX*MHillas.MeanY, -1.2)"
149// It should be possible to use all functions which are accessible
150// via the root-dictionary.
151//
152//
153// REMARK:
154// - All the random functions are returning 0 if gRandom==0
155// - You may get better results if you are using a TRandom3
156//
157// To Do:
158// - The possibility to use other objects inheriting from MData
159// is missing.
160// - By automatic pre-adding brackets to the rule it would be possible
161// to implement priorities for operators.
162//
163/////////////////////////////////////////////////////////////////////////////
164
165#include "MDataChain.h"
166
167#include <ctype.h> // isalnum, ...
168#include <stdlib.h> // strtod, ...
169
170#include <TRandom.h>
171#include <TMethodCall.h>
172
173#include "MLog.h"
174#include "MLogManip.h"
175
176#include "MDataList.h"
177#include "MDataValue.h"
178#include "MDataMember.h"
179#include "MDataFormula.h"
180#include "MDataElement.h"
181
182ClassImp(MDataChain);
183
184using namespace std;
185
186// --------------------------------------------------------------------------
187//
188// Constructor which takes a rule and a surrounding operator as argument
189//
190MDataChain::MDataChain(const char *rule, OperatorType_t op)
191 : fOperatorType(op)
192{
193 fName = "MDataChain";
194 fTitle = rule;
195
196 fMember=ParseString(rule, 1);
197}
198
199// --------------------------------------------------------------------------
200//
201// Constructor taking a rule as an argument. For more details see
202// class description
203//
204MDataChain::MDataChain(const char *rule, const char *name, const char *title)
205 : fMember(NULL), fOperatorType(kENoop)
206{
207 fName = name ? name : "MDataChain";
208 fTitle = title ? title : rule;
209
210 if (TString(rule).IsNull())
211 return;
212
213 *fLog << inf << "Trying to resolve rule... " << flush;
214 if (!(fMember=ParseString(rule, 1)))
215 {
216 *fLog << err << dbginf << "Parsing '" << rule << "' failed." << endl;
217 return;
218 }
219 *fLog << inf << "found: " << GetRule() << endl;
220}
221
222// --------------------------------------------------------------------------
223//
224// PreProcesses all members in the list
225//
226Bool_t MDataChain::PreProcess(const MParList *pList)
227{
228 return fMember ? fMember->PreProcess(pList) : kFALSE;
229}
230
231// --------------------------------------------------------------------------
232//
233// Checks whether at least one member has the ready-to-save flag.
234//
235Bool_t MDataChain::IsReadyToSave() const
236{
237 *fLog << all << "fM=" << fMember << "/" << (int)fMember->IsReadyToSave() << " " << endl;
238 return fMember ? fMember->IsReadyToSave() : kFALSE;
239}
240
241// --------------------------------------------------------------------------
242//
243// Destructor. Delete filters.
244//
245MDataChain::~MDataChain()
246{
247 if (fMember)
248 delete fMember;
249}
250
251// --------------------------------------------------------------------------
252//
253// Returns the number of alphanumeric characters (including '.' and ';')
254// in the given string
255//
256Int_t MDataChain::IsAlNum(TString txt)
257{
258 int l = txt.Length();
259 for (int i=0; i<l; i++)
260 {
261 if (!isalnum(txt[i]) && txt[i]!='.' && txt[i]!=':' && txt[i]!=';' &&
262 /*txt[i]!='['&&txt[i]!=']'&&*/
263 ((txt[i]!='-' && txt[i]!='+') || i!=0))
264 return i;
265 }
266
267 return l;
268}
269
270Int_t MDataChain::GetBracket(TString txt, char open, char close)
271{
272 Int_t first=1;
273 for (int cnt=0; first<txt.Length(); first++)
274 {
275 if (txt[first]==open)
276 cnt++;
277 if (txt[first]==close)
278 cnt--;
279 if (cnt==-1)
280 break;
281 }
282 return first;
283}
284
285// --------------------------------------------------------------------------
286//
287// Compare a given text with the known operators. If no operator match
288// kENoop is retunred, otherwise the corresponding OperatorType_t
289//
290MDataChain::OperatorType_t MDataChain::ParseOperator(TString txt) const
291{
292 txt.ToLower();
293
294 if (txt=="abs") return kEAbs;
295 if (txt=="fabs") return kEAbs;
296 if (txt=="log") return kELog;
297 if (txt=="log2") return kELog2;
298 if (txt=="log10") return kELog10;
299 if (txt=="sin") return kESin;
300 if (txt=="cos") return kECos;
301 if (txt=="tan") return kETan;
302 if (txt=="sinh") return kESinH;
303 if (txt=="cosh") return kECosH;
304 if (txt=="tanh") return kETanH;
305 if (txt=="asin") return kEASin;
306 if (txt=="acos") return kEACos;
307 if (txt=="atan") return kEATan;
308 if (txt=="asinh") return kEASinH;
309 if (txt=="acosh") return kEACosH;
310 if (txt=="atanh") return kEATanH;
311 if (txt=="sqrt") return kESqrt;
312 if (txt=="sqr") return kESqr;
313 if (txt=="exp") return kEExp;
314 if (txt=="pow10") return kEPow10;
315 if (txt=="sgn") return kESgn;
316 if (txt=="floor") return kEFloor;
317 if (txt=="r2d") return kERad2Deg;
318 if (txt=="d2r") return kEDeg2Rad;
319 if (txt=="rand") return kERandom;
320 if (txt=="randp") return kERandomP;
321 if (txt=="rande") return kERandomE;
322 if (txt=="randi") return kERandomI;
323 if (txt=="randg") return kERandomG;
324 if (txt=="randl") return kERandomL;
325 if (txt=="isnan") return kEIsNaN;
326 if (txt=="finite") return kEFinite;
327 if (txt[0]=='-') return kENegative;
328 if (txt[0]=='+') return kEPositive;
329
330 return kENoop;
331}
332
333// --------------------------------------------------------------------------
334//
335// Here the names of data members are interpreted. This can be used to
336// check for constants.
337//
338MData *MDataChain::ParseDataMember(TString txt)
339{
340 //txt.ToLower();
341
342 if (txt=="kRad2Deg") return new MDataValue(kRad2Deg);
343 if (txt=="kDeg2Rad") return new MDataValue(1./kRad2Deg);
344
345 if (!txt.BeginsWith("k"))
346 return new MDataMember(txt.Data());
347
348 const TString name = txt(1, txt.Length());
349 TMethodCall call(TMath::Class(), name, "");
350 switch (call.ReturnType())
351 {
352 case TMethodCall::kLong:
353 Long_t l;
354 call.Execute(l);
355 return new MDataValue(l);
356 case TMethodCall::kDouble:
357 Double_t d;
358 call.Execute(d);
359 return new MDataValue(d);
360 default:
361 break;
362 }
363
364 return new MDataMember(txt.Data());
365}
366
367// --------------------------------------------------------------------------
368//
369// Core of the data chain. Here the chain is constructed out of the rule.
370//
371MData *MDataChain::ParseString(TString txt, Int_t level)
372{
373 MData *member0=NULL;
374
375 char type=0;
376 int nlist = 0;
377
378 while (!txt.IsNull())
379 {
380 MData *newmember = NULL;
381
382 txt = txt.Strip(TString::kBoth);
383
384 switch (txt[0])
385 {
386 case '(':
387 {
388 //
389 // Search for the corresponding bracket
390 //
391 Int_t first=GetBracket(txt, '(', ')');
392
393 if (first==txt.Length())
394 {
395 *fLog << err << dbginf << "Syntax Error: ')' missing." << endl;
396 if (member0)
397 delete member0;
398 return NULL;
399 }
400
401 //
402 // Make a copy of the 'interieur' and delete the substringä
403 // including the brackets
404 //
405 TString sub = txt(1, first-1);
406 txt.Remove(0, first+1);
407
408 //
409 // Parse the substring
410 //
411 newmember = ParseString(sub, level+1);
412 if (!newmember)
413 {
414 *fLog << err << dbginf << "Parsing '" << sub << "' failed." << endl;
415 if (member0)
416 delete member0;
417 return NULL;
418 }
419 }
420 break;
421
422 case ')':
423 *fLog << err << dbginf << "Syntax Error: Too many ')'" << endl;
424 if (member0)
425 delete member0;
426 return NULL;
427
428 case '+':
429 case '-':
430 case '*':
431 case '/':
432 case '%':
433 case '^':
434 if (member0)
435 {
436 //
437 // Check for the type of the symbol
438 //
439 char is = txt[0];
440 txt.Remove(0, 1);
441
442 //
443 // If no filter is available or the available filter
444 // is of a different symbols we have to create a new
445 // data list with the new symbol
446 //
447 if (/*!member0->InheritsFrom(MDataMember::Class()) ||*/ type!=is)
448 {
449 MDataList *list = new MDataList(is);
450 list->SetName(Form("List_%c_%d", is, 10*level+nlist++));
451
452 list->SetOwner();
453 list->AddToList(member0);
454
455 member0 = list;
456
457 type = is;
458 }
459 continue;
460 }
461
462 if (txt[0]!='-' && txt[0]!='+')
463 {
464 *fLog << err << dbginf << "Syntax Error: First argument of symbol '";
465 *fLog << txt[0] << "' missing." << endl;
466 if (member0)
467 delete member0;
468 return NULL;
469 }
470
471 // FALLTHROU
472
473 case '0':
474 case '1':
475 case '2':
476 case '3':
477 case '4':
478 case '5':
479 case '6':
480 case '7':
481 case '8':
482 case '9':
483 case '[':
484 case ']':
485 if ((txt[0]!='-' && txt[0]!='+') || isdigit(txt[1]) || txt[1]=='.')
486 {
487 if (!txt.IsNull() && txt[0]=='[')
488 {
489 Int_t first = GetBracket(txt, '[', ']');
490 TString op = txt(1, first-1);
491 txt.Remove(0, first+1);
492
493 newmember = new MDataValue(0, atoi(op));
494 break;
495 }
496
497 char *end;
498 Double_t num = strtod(txt.Data(), &end);
499 if (!end || txt.Data()==end)
500 {
501 *fLog << err << dbginf << "Error trying to convert '" << txt << "' to value." << endl;
502 if (member0)
503 delete member0;
504 return NULL;
505 }
506
507 txt.Remove(0, end-txt.Data());
508
509 newmember = new MDataValue(num);
510 break;
511 }
512
513 // FALLTHROUH
514
515 default:
516 int i = IsAlNum(txt);
517
518 if (i==0)
519 {
520 *fLog << err << dbginf << "Syntax Error: Name of data member missing in '" << txt << "'" << endl;
521 if (member0)
522 delete member0;
523 return NULL;
524 }
525
526 TString text = txt(0, i);
527
528 txt.Remove(0, i);
529 txt = txt.Strip(TString::kBoth);
530
531 if (!txt.IsNull() && txt[0]=='[')
532 {
533 Int_t first = GetBracket(txt, '[', ']');
534 TString op = txt(1, first-1);
535 txt.Remove(0, first+1);
536
537 newmember = new MDataElement(text, atoi(op));
538 break;
539 }
540 if ((txt.IsNull() || txt[0]!='(') && text[0]!='-' && text[0]!='+')
541 {
542 newmember = ParseDataMember(text.Data());
543 break;
544 }
545
546 OperatorType_t op = ParseOperator(text);
547
548 Int_t first = GetBracket(txt, '(', ')');
549 TString sub = op==kENegative || op==kEPositive ? text.Remove(0,1) + txt : txt(1, first-1);
550 txt.Remove(0, first+1);
551
552 if (op==kENoop)
553 {
554 newmember = new MDataFormula(Form("%s(%s)", (const char*)text, (const char*)sub));
555 if (newmember->IsValid())
556 break;
557
558 *fLog << err << dbginf << "Syntax Error: Operator '" << text << "' unknown." << endl;
559 if (member0)
560 delete member0;
561 return NULL;
562 }
563
564 newmember = new MDataChain(sub, op);
565 if (!newmember->IsValid())
566 {
567 *fLog << err << dbginf << "Syntax Error: Error parsing contents '" << sub << "' of operator " << text << endl;
568 delete newmember;
569 if (member0)
570 delete member0;
571 return NULL;
572 }
573 }
574
575 if (!member0)
576 {
577 member0 = newmember;
578 continue;
579 }
580
581 if (!member0->InheritsFrom(MDataList::Class()))
582 continue;
583
584 ((MDataList*)member0)->AddToList(newmember);
585 }
586
587 return member0;
588}
589
590// --------------------------------------------------------------------------
591//
592// Returns the value described by the rule
593//
594Double_t MDataChain::GetValue() const
595{
596 if (!fMember)
597 {
598 //*fLog << warn << "MDataChain not valid." << endl;
599 return 0;
600 }
601
602 const Double_t val = fMember->GetValue();
603
604 switch (fOperatorType)
605 {
606 case kEAbs: return TMath::Abs(val);
607 case kELog: return TMath::Log(val);
608 case kELog2: return TMath::Log2(val);
609 case kELog10: return TMath::Log10(val);
610 case kESin: return TMath::Sin(val);
611 case kECos: return TMath::Cos(val);
612 case kETan: return TMath::Tan(val);
613 case kESinH: return TMath::SinH(val);
614 case kECosH: return TMath::CosH(val);
615 case kETanH: return TMath::TanH(val);
616 case kEASin: return TMath::ASin(val);
617 case kEACos: return TMath::ACos(val);
618 case kEATan: return TMath::ATan(val);
619 case kEASinH: return TMath::ASinH(val);
620 case kEACosH: return TMath::ACosH(val);
621 case kEATanH: return TMath::ATanH(val);
622 case kESqrt: return TMath::Sqrt(val);
623 case kESqr: return val*val;
624 case kEExp: return TMath::Exp(val);
625 case kEPow10: return TMath::Power(10, val);
626 case kESgn: return val<0 ? -1 : 1;
627 case kENegative: return -val;
628 case kEPositive: return val;
629 case kEFloor: return TMath::Floor(val);
630 case kECeil: return TMath::Ceil(val);
631 case kERound: return TMath::Nint(val);
632 case kERad2Deg: return val*180/TMath::Pi();
633 case kEDeg2Rad: return val*TMath::Pi()/180;
634 case kERandom: return gRandom ? gRandom->Uniform(val) : 0;
635 case kERandomP: return gRandom ? gRandom->Poisson(val) : 0;
636 case kERandomE: return gRandom ? gRandom->Exp(val) : 0;
637 case kERandomI: return gRandom ? gRandom->Integer((int)val) : 0;
638 case kERandomG: return gRandom ? gRandom->Gaus(0, val) : 0;
639 case kERandomL: return gRandom ? gRandom->Landau(0, val) : 0;
640 case kEIsNaN: return TMath::IsNaN(val);
641 case kEFinite: return TMath::Finite(val);
642 case kENoop: return val;
643 }
644
645 *fLog << warn << "No Case for " << fOperatorType << " available." << endl;
646
647 return 0;
648}
649
650// --------------------------------------------------------------------------
651//
652// Builds a rule from all the chain members. This is a rule which could
653// be used to rebuild the chain.
654//
655TString MDataChain::GetRule() const
656{
657 if (!fMember)
658 return "<n/a>";
659
660 TString str;
661
662 Bool_t bracket = fOperatorType!=kENoop && !fMember->InheritsFrom(MDataList::Class());
663
664 switch (fOperatorType)
665 {
666 case kEAbs: str += "abs" ; break;
667 case kELog: str += "log" ; break;
668 case kELog2: str += "log2" ; break;
669 case kELog10: str += "log10" ; break;
670 case kESin: str += "sin" ; break;
671 case kECos: str += "cos" ; break;
672 case kETan: str += "tan" ; break;
673 case kESinH: str += "sinh" ; break;
674 case kECosH: str += "cosh" ; break;
675 case kETanH: str += "tanh" ; break;
676 case kEASin: str += "asin" ; break;
677 case kEACos: str += "acos" ; break;
678 case kEATan: str += "atan" ; break;
679 case kEASinH: str += "asinh" ; break;
680 case kEACosH: str += "acosh" ; break;
681 case kEATanH: str += "atanh" ; break;
682 case kESqrt: str += "sqrt" ; break;
683 case kESqr: str += "sqr" ; break;
684 case kEExp: str += "exp" ; break;
685 case kEPow10: str += "pow10" ; break;
686 case kESgn: str += "sgn" ; break;
687 case kENegative: str += "-" ; break;
688 case kEPositive: str += "+" ; break;
689 case kEFloor: str += "floor" ; break;
690 case kECeil: str += "ceil" ; break;
691 case kERound: str += "round" ; break;
692 case kERad2Deg: str += "r2d" ; break;
693 case kEDeg2Rad: str += "d2r" ; break;
694 case kERandom: str += "rand" ; break;
695 case kERandomP: str += "randp" ; break;
696 case kERandomE: str += "rande" ; break;
697 case kERandomI: str += "randi" ; break;
698 case kERandomG: str += "randg" ; break;
699 case kERandomL: str += "randl" ; break;
700 case kEIsNaN: str += "isnan" ; break;
701 case kEFinite: str += "finite"; break;
702 case kENoop:
703 break;
704 }
705
706 if (bracket)
707 str += "(";
708
709 str += fMember->GetRule();
710
711 if (bracket)
712 str += ")";
713
714 return str;
715}
716
717// --------------------------------------------------------------------------
718//
719// Return a comma seperated list of all data members used in the chain.
720// This is mainly used in MTask::AddToBranchList
721//
722TString MDataChain::GetDataMember() const
723{
724 return fMember->GetDataMember();
725}
726
727void MDataChain::SetVariables(const TArrayD &arr)
728{
729 return fMember->SetVariables(arr);
730}
Note: See TracBrowser for help on using the repository browser.