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

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