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

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