def makeWeightStringFromHist(self, h, *variables, **kwargs): ''' Return a string that weights an event by the value of histogram h in the bin that would be filled by variables. ''' # make a copy so we can change directory, save it in global scope hCopy = h.clone() hCopy.SetDirectory(gROOT) #gROOT.GetListOfSpecials().Add(hCopy) self._hists.append(hCopy) iName = "{0}{1}".format(self.fName, self._counter) ROOTComp.register_code( self.codeBase.format(self._counter, ', '.join('double x%d'%i for i in range(len(variables))), hCopy.GetName(), ', '.join("x%d"%i for i in range(len(variables)))), [iName,]) out = '{0}({1})'.format(iName, ', '.join(variables)) # force system to compile code now arglebargle = getattr(ROOTComp, iName) self._counter += 1 return out
def compile(self): ROOTComp.register_code(___FRCodeToCompile___, ['lepFakeFactor', 'lepFakeFactorAdditive']) # force system to compile code now arglebargle = getattr(ROOTComp, 'lepFakeFactor') self.singleLepWeightTemp = ('(lepFakeFactor({f}, ' '{{0}}ZZTightID, ' '{{0}}ZZIsoPass))') self.zTemps = { lep : '*'.join([ self.singleLepWeightTemp.format(f=self.fakeRateStrs[lep]), self.singleLepWeightTemp.format( f=self.fakeRateStrs[lep]).format('{1}'), ]) for lep in ['e','m'] } self.corCondition = ( '((({{0}}ZZTightID + {{0}}ZZIsoPass + ' ' {{1}}ZZTightID + {{1}}ZZIsoPass) < 4.) && ' ' {{0}}_{{1}}_DR < 0.6 ? {0} : 1.)' ) self.corStrTemp3P1F = self.corCondition.format(0.) self.corStrTemp2P2F = self.corCondition.format(-1.) # To find 2P2F contribution to 3P1F region, we need F1+F2 instead of # F1*F2, so the 'identity' (for tight leptons) needs to be 0 self.singleLepWeightTempAdditive = ('(lepFakeFactorAdditive({f}, ' '{{0}}ZZTightID, ' '{{0}}ZZIsoPass))') self.zTempsAdditive = { lep : '(' + ('+'.join([ self.singleLepWeightTempAdditive.format( f=self.fakeRateStrs[lep] ), self.singleLepWeightTempAdditive.format( f=self.fakeRateStrs[lep] ).format('{1}'), ])) + ')' for lep in ['e','m'] }
def compile(self): ''' Compile the ROOT C macros needed for applying fake rates, put together the strings to apply them. ''' ROOTComp.register_code(___FRCodeToCompileFactorized___, ['overlapArea', 'isoNoOverlap', 'lepFakeFactor', 'zFakeFactorGeom']) # force system to compile code now arglebargle = getattr(ROOTComp, 'lepFakeFactor') self.singleLepWeightTemp = ('lepFakeFactor({fID}, ' '{{0}}ZZTightID > 0.5, ' '{fIso}, {{0}}ZZIsoPass > 0.5)') self.zTemps = { lep : '*'.join([ self.singleLepWeightTemp.format( fID=self.fakeRateStrs['ID'][lep], fIso=self.fakeRateStrs['Iso'][lep]), self.singleLepWeightTemp.format( fID=self.fakeRateStrs['ID'][lep], fIso=self.fakeRateStrs['Iso'][lep]).format('{1}') ]) for lep in ['e','m'] } self.zWeightTempCor = ( 'zFakeFactorGeom({fID0}, {{0}}ZZTightID > 0.5, ' '{fIso0}, {{0}}ZZIsoFSR, {{0}}Pt, ' '{fID1}, {{1}}ZZTightID > 0.5, {fIso1}, ' '{{1}}ZZIsoFSR, {{1}}Pt, {{0}}_{{1}}_DR)' ) self.zTempsCor = { lep : self.zWeightTempCor.format( fID0=self.fakeRateStrs['ID'][lep], fIso0=self.fakeRateStrs['Iso'][lep], fID1=self.fakeRateStrs['ID'][lep].format('{1}'), fIso1=self.fakeRateStrs['Iso'][lep].format('{1}') ) for lep in ['e','m'] }
# Copyright 2012 the rootpy developers # distributed under the terms of the GNU General Public License import rootpy.compiled as C C.register_file("test.cxx", ["AnswerToLtUaE", "RootpyTestCompiled"]) C.register_code( """ #include <string> std::string _rootpy_test() { return "Hello, world"; } """, "_rootpy_test".split()) def test_compiled(): assert C.AnswerToLtUaE() == 42 assert C.RootpyTestCompiled().blah() == 84 assert C._rootpy_test() == "Hello, world"
user-defined types. """ print(__doc__) from rootpy.tree import Tree, TreeModel, IntCol, ObjectCol from rootpy.io import root_open import rootpy.compiled as C from random import gauss # compile our new type C.register_code( """ class Thingy { public: int i; float x; double y; }; """, ["Thingy"], ) # alternatively you can ROOT.gSystem.Load() your library # define the model class Event(TreeModel): event_number = IntCol() thingy = ObjectCol(C.Thingy)
""" import ROOT import rootpy.compiled as C C.register_code( """ #include <TPython.h> #include <TPyDispatcher.h> class TPyDispatcherProcessedEvent : public TPyDispatcher { public: TPyDispatcherProcessedEvent(PyObject* callable) : TPyDispatcher(callable) {} PyObject* Dispatch(int p1, int p2, int p3, void* p4) { if (!p4) return NULL; PyObject* p4_aspyobj = TPython::ObjectProxy_FromVoidPtr(p4, reinterpret_cast<TObject*>(p4)->ClassName()); PyObject* result = DispatchVA("lllO", p1, p2, p3, p4_aspyobj); return result; } ClassDef(TPyDispatcherProcessedEvent, 0); }; ClassImp(TPyDispatcherProcessedEvent); """, ["TPyDispatcherProcessedEvent"]) def close_on_esc_or_middlemouse(event, x, y, obj): """ Closes canvases when escape is pressed or the canvas area is clicked with
C.register_code(""" #ifndef __CINT__ #include <Python.h> #endif #include <TObject.h> #include <TPython.h> class RootpyObjectCleanup : public TObject { public: typedef void (*CleanupCallback)(PyObject*); CleanupCallback _callback; RootpyObjectCleanup(CleanupCallback callback) : _callback(callback) {} virtual void RecursiveRemove(TObject* object) { // When arriving here, object->ClassName() will _always_ be TObject, // since we're called by ~TObject, and virtual method calls don't // work as expected from there. PyObject* o = TPython::ObjectProxy_FromVoidPtr(object, "TObject"); PyGILState_STATE gstate; gstate = PyGILState_Ensure(); PyObject *ptype, *pvalue, *ptraceback; PyErr_Fetch(&ptype, &pvalue, &ptraceback); _callback(o); PyErr_Restore(ptype, pvalue, ptraceback); PyGILState_Release(gstate); } ClassDef(RootpyObjectCleanup, 0); }; ClassImp(RootpyObjectCleanup); """, ["RootpyObjectCleanup"])
import rootpy.compiled as C C.register_file("test_compiled.cxx", ["AnswerToLtUaE", "RootpyTestCompiled"]) C.register_code(""" #include <string> std::string _rootpy_test() { return "Hello, world"; } """, "_rootpy_test".split()) def test_compiled(): assert C.AnswerToLtUaE() == 42 assert C.RootpyTestCompiled().blah() == 84 assert C._rootpy_test() == "Hello, world"
import rootpy.compiled as C C.register_code( """ double CentFrac_Cut(double pt_mev) { if (pt_mev < 30000.) { return 0.68; } else if (pt_mev > 30000 && pt_mev < 35000) { return 0.64; } else if (pt_mev > 35000 && pt_mev < 40000) { return 0.62; } else if (pt_mev > 40000 && pt_mev < 50000) { return 0.60; } else { return 0.57; } } """, ['CentFrac_Cut']) from rootpy.compiled import CentFrac_Cut
C.register_code( """ #ifndef PREFIT_ROOFITRESULT #define PREFIT_ROOFITRESULT #include <RooFitResult.h> #include <TMatrixDSym.h> #include <RooRealVar.h> #include <iostream> #include <algorithm> #include <math.h> class Prefit_RooFitResult: public RooFitResult { public: Prefit_RooFitResult(RooFitResult* _fitres, bool decorelate=false): RooFitResult(), fitres(_fitres) { RooFitResult::setConstParList(fitres->constPars()); RooFitResult::setInitParList(fitres->floatParsInit()); RooFitResult::setFinalParList(fitres->floatParsInit()); TMatrixDSym corr = fitres->correlationMatrix(); TMatrixDSym cov(corr.GetNrows()); for (int ii=0 ; ii<_finalPars->getSize() ; ii++){ for (int jj=0 ; jj<_finalPars->getSize() ; jj++){ //Double_t error_ii = std::max(fabs(((RooRealVar*)_finalPars->at(ii))->getErrorHi()), // fabs(((RooRealVar*)_finalPars->at(ii))->getErrorLo())); //Double_t error_jj = std::max(fabs(((RooRealVar*)_finalPars->at(jj))->getErrorHi()), // fabs(((RooRealVar*)_finalPars->at(jj))->getErrorLo())); Double_t error_ii = ((RooRealVar*)_finalPars->at(ii))->getError(); Double_t error_jj = ((RooRealVar*)_finalPars->at(jj))->getError(); cov(ii, jj) = corr(ii, jj)*error_ii*error_jj; if (decorelate) cov(ii, jj) = ii==jj ? cov(ii, jj)/corr(ii,jj):0.; } } RooFitResult::setCovarianceMatrix(cov); } virtual ~Prefit_RooFitResult() {delete fitres;} private: RooFitResult* fitres; protected: ClassDef(Prefit_RooFitResult, 5); }; #endif """, ["Prefit_RooFitResult"])
from ZZAnalyzer.utils.helpers import Z_MASS import rootpy.compiled as RC from rootpy.io import root_open import os RC.register_code(''' #include "TLorentzVector.h" float dileptonMass(float pt1, float eta1, float phi1, float m1, float pt2, float eta2, float phi2, float m2) { TLorentzVector v1, v2; if(abs(pt1) > 998. || abs(pt2) > 998.) return 9999.; v1.SetPtEtaPhiM(pt1, eta1, phi1, m1); v2.SetPtEtaPhiM(pt2, eta2, phi2, m2); return (v1 + v2).M(); } ''', ['dileptonMass']) # force to compile foo = getattr(RC, 'dileptonMass') tpVersionHash = 'v2.0-13-g36fc26c' #'v2.0-11-gafcf7cc' #'v1.1-4-ga295b14-extended' TP = TPFunctionManager(tpVersionHash)
C.register_code( """ #include <map> int get_bin(double pt_mev) { if (pt_mev < 30000.) return 0; else if (pt_mev > 30000. && pt_mev < 40000.) return 1; else if (pt_mev > 40000. && pt_mev < 50000.) return 2; else if (pt_mev > 50000. && pt_mev < 60000.) return 3; else if (pt_mev > 60000. && pt_mev < 70000.) return 4; else if (pt_mev > 70000. && pt_mev < 80000.) return 5; else if (pt_mev > 80000. && pt_mev < 90000.) return 6; else if (pt_mev > 90000. && pt_mev < 100000.) return 7; else return 8; } std::map<int, std::map<double, double> > get_table_1p() { std::map<int, std::map<double, double> > table_1p; table_1p[0][0.3] = 0.64425; table_1p[0][0.4] = 0.60925; table_1p[0][0.5] = 0.57525; table_1p[0][0.6] = 0.53775; table_1p[0][0.7] = 0.49825; table_1p[0][0.8] = 0.45175; table_1p[0][0.9] = 0.39425; table_1p[1][0.3] = 0.65375; table_1p[1][0.4] = 0.62025; table_1p[1][0.5] = 0.58575; table_1p[1][0.6] = 0.54975; table_1p[1][0.7] = 0.51025; table_1p[1][0.8] = 0.45775; table_1p[1][0.9] = 0.40075; table_1p[2][0.3] = 0.66175; table_1p[2][0.4] = 0.63275; table_1p[2][0.5] = 0.60175; table_1p[2][0.6] = 0.56525; table_1p[2][0.7] = 0.52825; table_1p[2][0.8] = 0.47775; table_1p[2][0.9] = 0.40925; table_1p[3][0.3] = 0.67075; table_1p[3][0.4] = 0.64325; table_1p[3][0.5] = 0.61425; table_1p[3][0.6] = 0.58125; table_1p[3][0.7] = 0.53875; table_1p[3][0.8] = 0.49075; table_1p[3][0.9] = 0.41475; table_1p[4][0.3] = 0.68325; table_1p[4][0.4] = 0.66125; table_1p[4][0.5] = 0.63625; table_1p[4][0.6] = 0.60725; table_1p[4][0.7] = 0.56575; table_1p[4][0.8] = 0.52225; table_1p[4][0.9] = 0.43125; table_1p[5][0.3] = 0.69175; table_1p[5][0.4] = 0.68075; table_1p[5][0.5] = 0.65775; table_1p[5][0.6] = 0.63125; table_1p[5][0.7] = 0.59675; table_1p[5][0.8] = 0.54825; table_1p[5][0.9] = 0.46675; table_1p[6][0.3] = 0.69575; table_1p[6][0.4] = 0.68775; table_1p[6][0.5] = 0.67375; table_1p[6][0.6] = 0.65325; table_1p[6][0.7] = 0.62475; table_1p[6][0.8] = 0.57925; table_1p[6][0.9] = 0.50875; table_1p[7][0.3] = 0.69725; table_1p[7][0.4] = 0.69125; table_1p[7][0.5] = 0.68075; table_1p[7][0.6] = 0.66075; table_1p[7][0.7] = 0.63625; table_1p[7][0.8] = 0.59975; table_1p[7][0.9] = 0.53425; table_1p[8][0.3] = 0.70025; table_1p[8][0.4] = 0.69175; table_1p[8][0.5] = 0.68475; table_1p[8][0.6] = 0.66975; table_1p[8][0.7] = 0.64675; table_1p[8][0.8] = 0.61475; table_1p[8][0.9] = 0.55475; return table_1p; } std::map<int, std::map<double, double> > get_table_mp() { std::map<int, std::map<double, double> > table_mp; table_mp[0][0.3] = 0.64925; table_mp[0][0.4] = 0.60725; table_mp[0][0.5] = 0.57225; table_mp[0][0.6] = 0.53375; table_mp[0][0.7] = 0.49325; table_mp[0][0.8] = 0.45075; table_mp[0][0.9] = 0.40025; table_mp[1][0.3] = 0.66375; table_mp[1][0.4] = 0.62425; table_mp[1][0.5] = 0.58625; table_mp[1][0.6] = 0.54875; table_mp[1][0.7] = 0.50875; table_mp[1][0.8] = 0.46575; table_mp[1][0.9] = 0.41075; table_mp[2][0.3] = 0.68425; table_mp[2][0.4] = 0.64925; table_mp[2][0.5] = 0.60925; table_mp[2][0.6] = 0.57175; table_mp[2][0.7] = 0.53225; table_mp[2][0.8] = 0.48825; table_mp[2][0.9] = 0.42925; table_mp[3][0.3] = 0.69725; table_mp[3][0.4] = 0.66525; table_mp[3][0.5] = 0.62725; table_mp[3][0.6] = 0.58875; table_mp[3][0.7] = 0.55075; table_mp[3][0.8] = 0.50625; table_mp[3][0.9] = 0.44525; table_mp[4][0.3] = 0.70675; table_mp[4][0.4] = 0.68675; table_mp[4][0.5] = 0.65375; table_mp[4][0.6] = 0.61225; table_mp[4][0.7] = 0.57375; table_mp[4][0.8] = 0.53275; table_mp[4][0.9] = 0.46925; table_mp[5][0.3] = 0.71225; table_mp[5][0.4] = 0.69725; table_mp[5][0.5] = 0.66625; table_mp[5][0.6] = 0.63225; table_mp[5][0.7] = 0.59225; table_mp[5][0.8] = 0.55375; table_mp[5][0.9] = 0.49825; table_mp[6][0.3] = 0.71475; table_mp[6][0.4] = 0.70175; table_mp[6][0.5] = 0.68225; table_mp[6][0.6] = 0.64725; table_mp[6][0.7] = 0.61175; table_mp[6][0.8] = 0.57125; table_mp[6][0.9] = 0.52125; table_mp[7][0.3] = 0.71875; table_mp[7][0.4] = 0.70575; table_mp[7][0.5] = 0.68925; table_mp[7][0.6] = 0.66025; table_mp[7][0.7] = 0.61725; table_mp[7][0.8] = 0.57925; table_mp[7][0.9] = 0.53625; table_mp[8][0.3] = 0.72225; table_mp[8][0.4] = 0.71125; table_mp[8][0.5] = 0.69925; table_mp[8][0.6] = 0.67875; table_mp[8][0.7] = 0.63575; table_mp[8][0.8] = 0.59775; table_mp[8][0.9] = 0.55625; return table_mp; } // BDT_Cut function double BDT_Cut(double pt_mev, int ntracks, double target) { std::map<int, std::map<double, double> > table_1p = get_table_1p(); std::map<int, std::map<double, double> > table_mp = get_table_mp(); if (ntracks < 2) { return table_1p[get_bin(pt_mev)][target]; } else { return table_mp[get_bin(pt_mev)][target]; } } """, ['BDT_Cut'])
C.register_code( """ #ifndef __CINT__ #include <Python.h> #endif #include <TObject.h> #include <TPython.h> class RootpyObjectCleanup : public TObject { public: typedef void (*CleanupCallback)(PyObject*); CleanupCallback _callback; RootpyObjectCleanup(CleanupCallback callback) : _callback(callback) {} virtual void RecursiveRemove(TObject* object) { // When arriving here, object->ClassName() will _always_ be TObject, // since we're called by ~TObject, and virtual method calls don't // work as expected from there. PyObject* o = TPython::ObjectProxy_FromVoidPtr(object, "TObject"); PyGILState_STATE gstate; gstate = PyGILState_Ensure(); PyObject *ptype, *pvalue, *ptraceback; PyErr_Fetch(&ptype, &pvalue, &ptraceback); _callback(o); PyErr_Restore(ptype, pvalue, ptraceback); PyGILState_Release(gstate); } ClassDef(RootpyObjectCleanup, 0); }; ClassImp(RootpyObjectCleanup); """, ["RootpyObjectCleanup"])
import rootpy.compiled as C C.register_code( """ #include "TH1F.h" #include "TGraph.h" class Weight { public: Weight(const TH1F* h) {m_gr = new TGraph(h);} ~Weight() {delete m_gr;} double w(const double & pt) {return m_gr->Eval(pt / 1000.);} private: TGraph * m_gr; }; """, ['Weight']) from rootpy.compiled import Weight
This function is intended for diagnostic purposes and is not guaranteed to keep working. """ import rootpy.compiled as C C.register_code( """ #include <sys/types.h> // for ssize_t struct _object; struct TFakeObjectProxy { ssize_t fRefCnt; // PyObject_HEAD void* fPyType; // PyObject_HEAD void* fRootObj; int fFlags; }; bool GetOwnership(_object* obj) { return (reinterpret_cast<TFakeObjectProxy*>(obj))->fFlags & 0x0001; } """, ["GetOwnership"], ) def GetOwnership(obj): """ This is not a straight assignment because C.GetOwnership causes finalsetup and compilation.
""" import ROOT import rootpy.compiled as C C.register_code(""" #include <TPython.h> #include <TPyDispatcher.h> class TPyDispatcherProcessedEvent : public TPyDispatcher { public: TPyDispatcherProcessedEvent(PyObject* callable) : TPyDispatcher(callable){} PyObject* Dispatch(int p1, int p2, int p3, void* p4) { if (!p4) return NULL; PyObject* p4_aspyobj = TPython::ObjectProxy_FromVoidPtr(p4, reinterpret_cast<TObject*>(p4)->ClassName()); PyObject* result = DispatchVA("lllO", p1, p2, p3, p4_aspyobj); return result; } ClassDef(TPyDispatcherProcessedEvent, 0); }; ClassImp(TPyDispatcherProcessedEvent); """, ["TPyDispatcherProcessedEvent"]) def close_on_esc_or_middlemouse(event, x, y, obj): """ Closes canvases when escape is pressed or the canvas area is clicked with
""" print __doc__ import rootpy rootpy.log.basic_config_colorized() from rootpy.tree import Tree, TreeModel, IntCol, ObjectCol from rootpy.io import root_open import rootpy.compiled as C from random import gauss # compile our new type C.register_code( """ class Thingy { public: int i; float x; double y; }; """, ["Thingy"]) # alternatively you can ROOT.gSystem.Load() your library # define the model class Event(TreeModel): event_number = IntCol() thingy = ObjectCol(C.Thingy)
ctx.pop() s_test_function = """ #include <math.h> void test_function(int *numTrials, float *aValues) { for (int i=0; i < *numTrials; i++) { aValues[i] = aValues[i] + 1; } } """ """ C.register_code(s_test_function, ['test_function']) c_test_function = C.test_function aValues = np.zeros(num_entries, dtype=np.float32) num_trials = np.asarray(num_entries, dtype=np.int32) startTime = time.time() c_test_function(num_trials, aValues) print 'C loop time: %f\n' % (time.time() - startTime) """ """ aEnergy = np.full(num_entries, 10, dtype=np.float32) aS1 = np.full(num_entries, -1, dtype=np.float32) aS2 = np.full(num_entries, -1, dtype=np.float32)