lunes, junio 28, 2010

Using the magic behind TFormula

I wanted to evaluate conditions at runtime and I'm a happy user of ROOT. So I was thinking to use the "magic" behind TFormula. But TFormula has some limitations: the name of the variables are "x, y z, t" and I need to use arbitrary names...

Doing some research I found RooFormulaVar, a class that is part of RooFit and it does the job :) I think that RooFormulaVar lacks proper documentation, so I'm going to describe briefly how to use it to evaluate mathematical and logic expressions at runtime. Using it is easy, if you know how :)

A simple example:


RooRealVar a("a","a",3.);
RooRealVar b("b","b",7.);
RooFormulaVar plus(“aplusb”,”a+b”,RooArgSet(a,b));
//10
cout << plus.getVal() << endl;


Evaluating bitwise operations and passing a set of arguments in a more dynamic way:

TClonesArray tca("RooRealVar",2)
RooRealVar *var1 = new (tca[1]) RooRealVar("var1","var2",0);
RooRealVar *var2 = new (tca[0]) RooRealVar("var2","var2",0);

RooFormulaVar opor("var1orvar2","var1&var2",RooArgSet(tca));

var1->setVal(2.);
var2->setVal(7.);
//2
cout << opor.getVal() << endl;

var1->setVal(5.);
var2->setVal(1.);
//1
cout << opor.getVal() << endl;

var1->setVal(8.);
var2->setVal(1.);
//0
cout << opor.getVal() << endl;

Finally, evaluating logical expressions:

TClonesArray tca("RooRealVar",2)
RooRealVar *var1 = new (tca[1]) RooRealVar("var1","var2",0);
RooRealVar *var2 = new (tca[0]) RooRealVar("var2","var2",0);

RooFormulaVar cond("var1littvar2big","var1<1 || var2>10",RooArgSet(tca));


var1->setVal(0.);
var2->setVal(17.);

//true
cout << cond.getVal() << endl;

var1->setVal(3.);
var2->setVal(11.);

//true
cout << cond.getVal() << endl;

var1->setVal(8.);
var2->setVal(1.);
//false
cout << cond.getVal() << endl;

I hope that this blog entry will be useful and someone will save time and code. Cheers and happy coding! :)

No hay comentarios: