source: trunk/MagicSoft/Mars/mdata/MDataChain.cc@ 2553

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