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

Last change on this file since 2796 was 2573, checked in by moralejo, 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// 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 '.' and ';')
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]!=';' &&
219 /*txt[i]!='['&&txt[i]!=']'&&*/
220 ((txt[i]!='-' && txt[i]!='+') || i!=0))
221 return i;
222 }
223
224 return l;
225}
226
227Int_t MDataChain::GetBracket(TString txt, char open, char close)
228{
229 Int_t first=1;
230 for (int cnt=0; first<txt.Length(); first++)
231 {
232 if (txt[first]==open)
233 cnt++;
234 if (txt[first]==close)
235 cnt--;
236 if (cnt==-1)
237 break;
238 }
239 return first;
240}
241
242// --------------------------------------------------------------------------
243//
244// Compare a given text with the known operators. If no operator match
245// kENoop is retunred, otherwise the corresponding OperatorType_t
246//
247MDataChain::OperatorType_t MDataChain::ParseOperator(TString txt) const
248{
249 txt.ToLower();
250
251 if (txt=="abs") return kEAbs;
252 if (txt=="fabs") return kEAbs;
253 if (txt=="log") return kELog;
254 if (txt=="log2") return kELog2;
255 if (txt=="log10") return kELog10;
256 if (txt=="sin") return kESin;
257 if (txt=="cos") return kECos;
258 if (txt=="tan") return kETan;
259 if (txt=="sinh") return kESinH;
260 if (txt=="cosh") return kECosH;
261 if (txt=="tanh") return kETanH;
262 if (txt=="asin") return kEASin;
263 if (txt=="acos") return kEACos;
264 if (txt=="atan") return kEATan;
265 if (txt=="asinh") return kEASinH;
266 if (txt=="acosh") return kEACosH;
267 if (txt=="atanh") return kEATanH;
268 if (txt=="sqrt") return kESqrt;
269 if (txt=="sqr") return kESqr;
270 if (txt=="exp") return kEExp;
271 if (txt=="pow10") return kEPow10;
272 if (txt=="sgn") return kESgn;
273 if (txt=="floor") return kEFloor;
274 if (txt=="r2d") return kERad2Deg;
275 if (txt=="d2r") return kEDeg2Rad;
276 if (txt=="rand") return kERandom;
277 if (txt=="randp") return kERandomP;
278 if (txt=="rande") return kERandomE;
279 if (txt=="randi") return kERandomI;
280 if (txt=="randg") return kERandomG;
281 if (txt=="randl") return kERandomL;
282 if (txt=="isnan") return kEIsNaN;
283 if (txt=="finite") return kEFinite;
284 if (txt[0]=='-') return kENegative;
285 if (txt[0]=='+') return kEPositive;
286
287 return kENoop;
288}
289
290// --------------------------------------------------------------------------
291//
292// Here the names of data members are interpreted. This can be used to
293// check for constants.
294//
295MData *MDataChain::ParseDataMember(TString txt)
296{
297 //txt.ToLower();
298
299 if (txt=="kRad2Deg") return new MDataValue(kRad2Deg);
300 if (txt=="kDeg2Rad") return new MDataValue(1./kRad2Deg);
301
302 if (!txt.BeginsWith("k"))
303 return new MDataMember(txt.Data());
304
305 const TString name = txt(1, txt.Length());
306 TMethodCall call(TMath::Class(), name, "");
307 switch (call.ReturnType())
308 {
309 case TMethodCall::kLong:
310 Long_t l;
311 call.Execute(l);
312 return new MDataValue(l);
313 case TMethodCall::kDouble:
314 Double_t d;
315 call.Execute(d);
316 return new MDataValue(d);
317 default:
318 break;
319 }
320
321 return new MDataMember(txt.Data());
322}
323
324// --------------------------------------------------------------------------
325//
326// Core of the data chain. Here the chain is constructed out of the rule.
327//
328MData *MDataChain::ParseString(TString txt, Int_t level)
329{
330 MData *member0=NULL;
331
332 char type=0;
333 int nlist = 0;
334
335 while (!txt.IsNull())
336 {
337 MData *newmember = NULL;
338
339 txt = txt.Strip(TString::kBoth);
340
341 switch (txt[0])
342 {
343 case '(':
344 {
345 //
346 // Search for the corresponding bracket
347 //
348 Int_t first=GetBracket(txt, '(', ')');
349
350 if (first==txt.Length())
351 {
352 *fLog << err << dbginf << "Syntax Error: ')' missing." << endl;
353 if (member0)
354 delete member0;
355 return NULL;
356 }
357
358 //
359 // Make a copy of the 'interieur' and delete the substringä
360 // including the brackets
361 //
362 TString sub = txt(1, first-1);
363 txt.Remove(0, first+1);
364
365 //
366 // Parse the substring
367 //
368 newmember = ParseString(sub, level+1);
369 if (!newmember)
370 {
371 *fLog << err << dbginf << "Parsing '" << sub << "' failed." << endl;
372 if (member0)
373 delete member0;
374 return NULL;
375 }
376 }
377 break;
378
379 case ')':
380 *fLog << err << dbginf << "Syntax Error: Too many ')'" << endl;
381 if (member0)
382 delete member0;
383 return NULL;
384
385 case '+':
386 case '-':
387 case '*':
388 case '/':
389 if (member0)
390 {
391 //
392 // Check for the type of the symbol
393 //
394 char is = txt[0];
395 txt.Remove(0, 1);
396
397 //
398 // If no filter is available or the available filter
399 // is of a different symbols we have to create a new
400 // data list with the new symbol
401 //
402 if (/*!member0->InheritsFrom(MDataMember::Class()) ||*/ type!=is)
403 {
404 MDataList *list = new MDataList(is);
405 list->SetName(Form("List_%c_%d", is, 10*level+nlist++));
406
407 list->SetOwner();
408 list->AddToList(member0);
409
410 member0 = list;
411
412 type = is;
413 }
414 continue;
415 }
416
417 if (txt[0]!='-' && txt[0]!='+')
418 {
419 *fLog << err << dbginf << "Syntax Error: First argument of symbol '";
420 *fLog << txt[0] << "' missing." << endl;
421 if (member0)
422 delete member0;
423 return NULL;
424 }
425
426 // FALLTHROU
427
428 case '0':
429 case '1':
430 case '2':
431 case '3':
432 case '4':
433 case '5':
434 case '6':
435 case '7':
436 case '8':
437 case '9':
438 if ((txt[0]!='-' && txt[0]!='+') || isdigit(txt[1]) || txt[1]=='.')
439 {
440 char *end;
441 Double_t num = strtod(txt.Data(), &end);
442 if (!end || txt.Data()==end)
443 {
444 *fLog << err << dbginf << "Error trying to convert '" << txt << "' to value." << endl;
445 if (member0)
446 delete member0;
447 return NULL;
448 }
449
450 txt.Remove(0, end-txt.Data());
451
452 newmember = new MDataValue(num);
453 break;
454 }
455
456 // FALLTHROUH
457
458 default:
459 int i = IsAlNum(txt);
460
461 if (i==0)
462 {
463 *fLog << err << dbginf << "Syntax Error: Name of data member missing in '" << txt << "'" << endl;
464 if (member0)
465 delete member0;
466 return NULL;
467 }
468
469 TString text = txt(0, i);
470
471 txt.Remove(0, i);
472 txt = txt.Strip(TString::kBoth);
473
474 if (!txt.IsNull() && txt[0]=='[')
475 {
476 Int_t first = GetBracket(txt, '[', ']');
477 TString op = txt(1, first-1);
478 txt.Remove(0, first+1);
479
480 newmember = new MDataElement(text, atoi(op));
481 break;
482 }
483 if ((txt.IsNull() || txt[0]!='(') && text[0]!='-' && text[0]!='+')
484 {
485 newmember = ParseDataMember(text.Data());
486 break;
487 }
488
489 OperatorType_t op = ParseOperator(text);
490 if (op==kENoop)
491 {
492 *fLog << err << dbginf << "Syntax Error: Operator '" << text << "' unknown." << endl;
493 if (member0)
494 delete member0;
495 return NULL;
496 }
497
498 Int_t first = GetBracket(txt, '(', ')');
499 TString sub = op==kENegative || op==kEPositive ? text.Remove(0,1) + txt : txt(1, first-1);
500 txt.Remove(0, first+1);
501
502 newmember = new MDataChain(sub, op);
503 if (!newmember->IsValid())
504 {
505 *fLog << err << dbginf << "Syntax Error: Error parsing contents '" << sub << "' of operator " << text << endl;
506 delete newmember;
507 if (member0)
508 delete member0;
509 return NULL;
510 }
511 }
512
513 if (!member0)
514 {
515 member0 = newmember;
516 continue;
517 }
518
519 if (!member0->InheritsFrom(MDataList::Class()))
520 continue;
521
522 ((MDataList*)member0)->AddToList(newmember);
523 }
524
525 return member0;
526}
527
528// --------------------------------------------------------------------------
529//
530// Returns the value described by the rule
531//
532Double_t MDataChain::GetValue() const
533{
534 if (!fMember)
535 {
536 //*fLog << warn << "MDataChain not valid." << endl;
537 return 0;
538 }
539
540 const Double_t val = fMember->GetValue();
541
542 switch (fOperatorType)
543 {
544 case kEAbs: return TMath::Abs(val);
545 case kELog: return TMath::Log(val);
546 case kELog2: return TMath::Log2(val);
547 case kELog10: return TMath::Log10(val);
548 case kESin: return TMath::Sin(val);
549 case kECos: return TMath::Cos(val);
550 case kETan: return TMath::Tan(val);
551 case kESinH: return TMath::SinH(val);
552 case kECosH: return TMath::CosH(val);
553 case kETanH: return TMath::TanH(val);
554 case kEASin: return TMath::ASin(val);
555 case kEACos: return TMath::ACos(val);
556 case kEATan: return TMath::ATan(val);
557 case kEASinH: return TMath::ASinH(val);
558 case kEACosH: return TMath::ACosH(val);
559 case kEATanH: return TMath::ATanH(val);
560 case kESqrt: return TMath::Sqrt(val);
561 case kESqr: return val*val;
562 case kEExp: return TMath::Exp(val);
563 case kEPow10: return TMath::Power(10, val);
564 case kESgn: return val<0 ? -1 : 1;
565 case kENegative: return -val;
566 case kEPositive: return val;
567 case kEFloor: return TMath::Floor(val);
568 case kECeil: return TMath::Ceil(val);
569 case kERound: return TMath::Nint(val);
570 case kERad2Deg: return val*180/TMath::Pi();
571 case kEDeg2Rad: return val*TMath::Pi()/180;
572 case kERandom: return gRandom ? gRandom->Uniform(val) : 0;
573 case kERandomP: return gRandom ? gRandom->Poisson(val) : 0;
574 case kERandomE: return gRandom ? gRandom->Exp(val) : 0;
575 case kERandomI: return gRandom ? gRandom->Integer((int)val) : 0;
576 case kERandomG: return gRandom ? gRandom->Gaus(0, val) : 0;
577 case kERandomL: return gRandom ? gRandom->Landau(0, val) : 0;
578 case kEIsNaN: return TMath::IsNaN(val);
579 case kEFinite: return TMath::Finite(val);
580 case kENoop: return val;
581 }
582
583 *fLog << warn << "No Case for " << fOperatorType << " available." << endl;
584
585 return 0;
586}
587
588 /*
589void MDataChain::Print(Option_t *opt) const
590{
591 *fLog << GetRule() << flush;
592 Bool_t bracket = fOperatorType!=kENoop && !fMember->InheritsFrom(MDataList::Class());
593
594 switch (fOperatorType)
595 {
596 case kEAbs: *fLog << "abs" << flush; break;
597 case kELog: *fLog << "log" << flush; break;
598 case kELog10: *fLog << "log10" << flush; break;
599 case kESin: *fLog << "sin" << flush; break;
600 case kECos: *fLog << "cos" << flush; break;
601 case kETan: *fLog << "tan" << flush; break;
602 case kESinH: *fLog << "sinh" << flush; break;
603 case kECosH: *fLog << "cosh" << flush; break;
604 case kETanH: *fLog << "tanh" << flush; break;
605 case kEASin: *fLog << "asin" << flush; break;
606 case kEACos: *fLog << "acos" << flush; break;
607 case kEATan: *fLog << "atan" << flush; break;
608 case kESqrt: *fLog << "sqrt" << flush; break;
609 case kEExp: *fLog << "exp" << flush; break;
610 case kEPow10: *fLog << "pow10" << flush; break;
611 case kESgn: *fLog << "sgn" << flush; break;
612 case kENegative: *fLog << "-" << flush; break;
613 case kEPositive: *fLog << "+" << flush; break;
614 case kENoop:
615 break;
616 }
617
618 if (bracket)
619 *fLog << "(" << flush;
620
621 fMember->Print();
622
623 if (bracket)
624 *fLog << ")" << flush;
625 }
626 */
627
628// --------------------------------------------------------------------------
629//
630// Builds a rule from all the chain members. This is a rule which could
631// be used to rebuild the chain.
632//
633TString MDataChain::GetRule() const
634{
635 if (!fMember)
636 return "<n/a>";
637
638 TString str;
639
640 Bool_t bracket = fOperatorType!=kENoop && !fMember->InheritsFrom(MDataList::Class());
641
642 switch (fOperatorType)
643 {
644 case kEAbs: str += "abs" ; break;
645 case kELog: str += "log" ; break;
646 case kELog2: str += "log2" ; break;
647 case kELog10: str += "log10" ; break;
648 case kESin: str += "sin" ; break;
649 case kECos: str += "cos" ; break;
650 case kETan: str += "tan" ; break;
651 case kESinH: str += "sinh" ; break;
652 case kECosH: str += "cosh" ; break;
653 case kETanH: str += "tanh" ; break;
654 case kEASin: str += "asin" ; break;
655 case kEACos: str += "acos" ; break;
656 case kEATan: str += "atan" ; break;
657 case kEASinH: str += "asinh" ; break;
658 case kEACosH: str += "acosh" ; break;
659 case kEATanH: str += "atanh" ; break;
660 case kESqrt: str += "sqrt" ; break;
661 case kESqr: str += "sqr" ; break;
662 case kEExp: str += "exp" ; break;
663 case kEPow10: str += "pow10" ; break;
664 case kESgn: str += "sgn" ; break;
665 case kENegative: str += "-" ; break;
666 case kEPositive: str += "+" ; break;
667 case kEFloor: str += "floor" ; break;
668 case kECeil: str += "ceil" ; break;
669 case kERound: str += "round" ; break;
670 case kERad2Deg: str += "r2d" ; break;
671 case kEDeg2Rad: str += "d2r" ; break;
672 case kERandom: str += "rand" ; break;
673 case kERandomP: str += "randp" ; break;
674 case kERandomE: str += "rande" ; break;
675 case kERandomI: str += "randi" ; break;
676 case kERandomG: str += "randg" ; break;
677 case kERandomL: str += "randl" ; break;
678 case kEIsNaN: str += "isnan" ; break;
679 case kEFinite: str += "finite"; break;
680 case kENoop:
681 break;
682 }
683
684 if (bracket)
685 str += "(";
686
687 str += fMember->GetRule();
688
689 if (bracket)
690 str += ")";
691
692 return str;
693}
694
695// --------------------------------------------------------------------------
696//
697// Return a comma seperated list of all data members used in the chain.
698// This is mainly used in MTask::AddToBranchList
699//
700TString MDataChain::GetDataMember() const
701{
702 return fMember->GetDataMember();
703}
704
Note: See TracBrowser for help on using the repository browser.