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

Last change on this file since 5660 was 3788, checked in by tbretz, 21 years ago
*** empty log message ***
File size: 22.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 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 parantheses:
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 parantheses
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 parantheses 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
367void MDataChain::SimplifyString(TString &txt) const
368{
369 while (txt.First("--")>=0 || txt.First("++")>=0 ||
370 txt.First("+-")>=0 || txt.First("-+")>=0)
371 {
372 txt.ReplaceAll("--", "+");
373 txt.ReplaceAll("++", "+");
374 txt.ReplaceAll("-+", "-");
375 txt.ReplaceAll("+-", "-");
376 }
377}
378
379// --------------------------------------------------------------------------
380//
381// Core of the data chain. Here the chain is constructed out of the rule.
382//
383MData *MDataChain::ParseString(TString txt, Int_t level)
384{
385 if (level==0)
386 SimplifyString(txt);
387
388 MData *member0=NULL;
389
390 char type=0;
391 int nlist = 0;
392
393 while (!txt.IsNull())
394 {
395 MData *newmember = NULL;
396
397 txt = txt.Strip(TString::kBoth);
398
399 switch (txt[0])
400 {
401 case '(':
402 {
403 //
404 // Search for the corresponding parantheses
405 //
406 const Int_t first=GetBracket(txt, '(', ')');
407 if (first==txt.Length())
408 {
409 *fLog << err << dbginf << "Syntax Error: ')' missing." << endl;
410 if (member0)
411 delete member0;
412 return NULL;
413 }
414
415 //
416 // Make a copy of the 'interieur' and delete the substring
417 // including the brackets
418 //
419 TString sub = txt(1, first-1);
420 txt.Remove(0, first+1);
421
422 //
423 // Parse the substring
424 //
425 newmember = ParseString(sub, level+1);
426 if (!newmember)
427 {
428 *fLog << err << dbginf << "Parsing '" << sub << "' failed." << endl;
429 if (member0)
430 delete member0;
431 return NULL;
432 }
433 }
434 break;
435
436 case ')':
437 *fLog << err << dbginf << "Syntax Error: Too many ')'" << endl;
438 if (member0)
439 delete member0;
440 return NULL;
441
442 case '+':
443 case '-':
444 case '*':
445 case '/':
446 case '%':
447 case '^':
448 if (member0)
449 {
450 //
451 // Check for the type of the symbol
452 //
453 char is = txt[0];
454 txt.Remove(0, 1);
455
456 //
457 // If no filter is available or the available filter
458 // is of a different symbols we have to create a new
459 // data list with the new symbol
460 //
461 if (/*!member0->InheritsFrom(MDataMember::Class()) ||*/ type!=is)
462 {
463 MDataList *list = new MDataList(is);
464 list->SetName(Form("List_%c_%d", is, 10*level+nlist++));
465
466 list->SetOwner();
467 list->AddToList(member0);
468
469 member0 = list;
470
471 type = is;
472 }
473 continue;
474 }
475
476 if (txt[0]!='-' && txt[0]!='+')
477 {
478 *fLog << err << dbginf << "Syntax Error: First argument of '";
479 *fLog << txt[0] << "' opartor missing." << endl;
480 if (member0)
481 delete member0;
482 return NULL;
483 }
484
485 // FALLTHROU
486
487 case '0':
488 case '1':
489 case '2':
490 case '3':
491 case '4':
492 case '5':
493 case '6':
494 case '7':
495 case '8':
496 case '9':
497 case '[':
498 case ']':
499 if ((txt[0]!='-' && txt[0]!='+') || isdigit(txt[1]) || txt[1]=='.')
500 {
501 if (!txt.IsNull() && txt[0]=='[')
502 {
503 Int_t first = GetBracket(txt, '[', ']');
504 TString op = txt(1, first-1);
505 txt.Remove(0, first+1);
506
507 newmember = new MDataValue(0, atoi(op));
508 break;
509 }
510
511 char *end;
512 Double_t num = strtod(txt.Data(), &end);
513 if (!end || txt.Data()==end)
514 {
515 *fLog << err << dbginf << "Error trying to convert '" << txt << "' to value." << endl;
516 if (member0)
517 delete member0;
518 return NULL;
519 }
520
521 txt.Remove(0, end-txt.Data());
522
523 newmember = new MDataValue(num);
524 break;
525 }
526
527 // FALLTHROUH
528
529 default:
530 int i = IsAlNum(txt);
531
532 if (i==0)
533 {
534 *fLog << err << dbginf << "Syntax Error: Name of data member missing in '" << txt << "'" << endl;
535 if (member0)
536 delete member0;
537 return NULL;
538 }
539
540 TString text = txt(0, i);
541
542 txt.Remove(0, i);
543 txt = txt.Strip(TString::kBoth);
544
545 if (!txt.IsNull() && txt[0]=='[')
546 {
547 Int_t first = GetBracket(txt, '[', ']');
548 TString op = txt(1, first-1);
549 txt.Remove(0, first+1);
550
551 newmember = new MDataElement(text, atoi(op));
552 break;
553 }
554 if ((txt.IsNull() || txt[0]!='(') && text[0]!='-' && text[0]!='+')
555 {
556 newmember = ParseDataMember(text.Data());
557 break;
558 }
559
560 OperatorType_t op = ParseOperator(text);
561
562 Int_t first = GetBracket(txt, '(', ')');
563 TString sub = op==kENegative || op==kEPositive ? text.Remove(0,1) + txt : txt(1, first-1);
564 txt.Remove(0, first+1);
565
566 if (op==kENoop)
567 {
568 newmember = new MDataFormula(Form("%s(%s)", (const char*)text, (const char*)sub));
569 if (newmember->IsValid())
570 break;
571
572 *fLog << err << dbginf << "Syntax Error: Operator '" << text << "' unknown." << endl;
573 if (member0)
574 delete member0;
575 return NULL;
576 }
577
578 newmember = new MDataChain(sub, op);
579 if (!newmember->IsValid())
580 {
581 *fLog << err << dbginf << "Syntax Error: Error parsing contents '" << sub << "' of operator " << text << endl;
582 delete newmember;
583 if (member0)
584 delete member0;
585 return NULL;
586 }
587 }
588
589 if (!member0)
590 {
591 member0 = newmember;
592 continue;
593 }
594
595 if (!member0->InheritsFrom(MDataList::Class()))
596 continue;
597
598 ((MDataList*)member0)->AddToList(newmember);
599 }
600
601 return member0;
602}
603
604// --------------------------------------------------------------------------
605//
606// Returns the value described by the rule
607//
608Double_t MDataChain::GetValue() const
609{
610 if (!fMember)
611 {
612 //*fLog << warn << "MDataChain not valid." << endl;
613 return 0;
614 }
615
616 const Double_t val = fMember->GetValue();
617
618 switch (fOperatorType)
619 {
620 case kEAbs: return TMath::Abs(val);
621 case kELog: return TMath::Log(val);
622 case kELog2: return TMath::Log2(val);
623 case kELog10: return TMath::Log10(val);
624 case kESin: return TMath::Sin(val);
625 case kECos: return TMath::Cos(val);
626 case kETan: return TMath::Tan(val);
627 case kESinH: return TMath::SinH(val);
628 case kECosH: return TMath::CosH(val);
629 case kETanH: return TMath::TanH(val);
630 case kEASin: return TMath::ASin(val);
631 case kEACos: return TMath::ACos(val);
632 case kEATan: return TMath::ATan(val);
633 case kEASinH: return TMath::ASinH(val);
634 case kEACosH: return TMath::ACosH(val);
635 case kEATanH: return TMath::ATanH(val);
636 case kESqrt: return TMath::Sqrt(val);
637 case kESqr: return val*val;
638 case kEExp: return TMath::Exp(val);
639 case kEPow10: return TMath::Power(10, val);
640 case kESgn: return val<0 ? -1 : 1;
641 case kENegative: return -val;
642 case kEPositive: return val;
643 case kEFloor: return TMath::Floor(val);
644 case kECeil: return TMath::Ceil(val);
645 case kERound: return TMath::Nint(val);
646 case kERad2Deg: return val*180/TMath::Pi();
647 case kEDeg2Rad: return val*TMath::Pi()/180;
648 case kERandom: return gRandom ? gRandom->Uniform(val) : 0;
649 case kERandomP: return gRandom ? gRandom->Poisson(val) : 0;
650 case kERandomE: return gRandom ? gRandom->Exp(val) : 0;
651 case kERandomI: return gRandom ? gRandom->Integer((int)val) : 0;
652 case kERandomG: return gRandom ? gRandom->Gaus(0, val) : 0;
653 case kERandomL: return gRandom ? gRandom->Landau(0, val) : 0;
654 case kEIsNaN: return TMath::IsNaN(val);
655 case kEFinite: return TMath::Finite(val);
656 case kENoop: return val;
657 }
658
659 *fLog << warn << "No Case for " << fOperatorType << " available." << endl;
660
661 return 0;
662}
663
664// --------------------------------------------------------------------------
665//
666// Builds a rule from all the chain members. This is a rule which could
667// be used to rebuild the chain.
668//
669TString MDataChain::GetRule() const
670{
671 if (!fMember)
672 return "<n/a>";
673
674 TString str;
675
676 Bool_t bracket = fOperatorType!=kENoop && !fMember->InheritsFrom(MDataList::Class());
677
678 switch (fOperatorType)
679 {
680 case kEAbs: str += "abs" ; break;
681 case kELog: str += "log" ; break;
682 case kELog2: str += "log2" ; break;
683 case kELog10: str += "log10" ; break;
684 case kESin: str += "sin" ; break;
685 case kECos: str += "cos" ; break;
686 case kETan: str += "tan" ; break;
687 case kESinH: str += "sinh" ; break;
688 case kECosH: str += "cosh" ; break;
689 case kETanH: str += "tanh" ; break;
690 case kEASin: str += "asin" ; break;
691 case kEACos: str += "acos" ; break;
692 case kEATan: str += "atan" ; break;
693 case kEASinH: str += "asinh" ; break;
694 case kEACosH: str += "acosh" ; break;
695 case kEATanH: str += "atanh" ; break;
696 case kESqrt: str += "sqrt" ; break;
697 case kESqr: str += "sqr" ; break;
698 case kEExp: str += "exp" ; break;
699 case kEPow10: str += "pow10" ; break;
700 case kESgn: str += "sgn" ; break;
701 case kENegative: str += "-" ; break;
702 case kEPositive: str += "+" ; break;
703 case kEFloor: str += "floor" ; break;
704 case kECeil: str += "ceil" ; break;
705 case kERound: str += "round" ; break;
706 case kERad2Deg: str += "r2d" ; break;
707 case kEDeg2Rad: str += "d2r" ; break;
708 case kERandom: str += "rand" ; break;
709 case kERandomP: str += "randp" ; break;
710 case kERandomE: str += "rande" ; break;
711 case kERandomI: str += "randi" ; break;
712 case kERandomG: str += "randg" ; break;
713 case kERandomL: str += "randl" ; break;
714 case kEIsNaN: str += "isnan" ; break;
715 case kEFinite: str += "finite"; break;
716 case kENoop:
717 break;
718 }
719
720 if (bracket)
721 str += "(";
722
723 str += fMember->GetRule();
724
725 if (bracket)
726 str += ")";
727
728 return str;
729}
730
731// --------------------------------------------------------------------------
732//
733// Return a comma seperated list of all data members used in the chain.
734// This is mainly used in MTask::AddToBranchList
735//
736TString MDataChain::GetDataMember() const
737{
738 return fMember->GetDataMember();
739}
740
741void MDataChain::SetVariables(const TArrayD &arr)
742{
743 return fMember->SetVariables(arr);
744}
Note: See TracBrowser for help on using the repository browser.