PyWrap

From Mu2eWiki
Revision as of 01:39, 13 November 2021 by Rlc (talk | contribs) (Created page with "==Introduction== In some cases, it would be helpful to use a piece of c++ Offline code in a python script. A good example is importing the enums from Offline into a python an...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Introduction

In some cases, it would be helpful to use a piece of c++ Offline code in a python script. A good example is importing the enums from Offline into a python analysis routine, so numbers recorded in an ntuple could be interpreted.

Method

The wrappers are implemented using swig. This freeware package can interpret a c++ class header file and produce a piece of c++ code with hooks into the class, and piece of python code which can present the class to the user as a python class.

To active a wrapper, there must be a file, pywrap.i in the src (not inc) directory where the source class is created. For example

Offline/MCDataProducts/src/pywrap.i

This file is s wig interface file, and specifies the class to be wrapped. The content of this file is a bit arcane, and in order to try to reproduce the features of c++ in python, it can get complicated. The swig is complete and well-written content can be developed as needed. It is not unusual that one or two methods of the class will work, but maybe some don't and might require more work.

The creation of the wrapper is triggered by building with the switch

muse build -j 20 --mu2ePyWrap

The wrapper c code will land

build/.../Offline/tmp/MCDataProducts/src/pywrap/MCDataProducts_wrap.cpp

and the wrapper will land

build/.../Offline/pywrap/MCDataProducts.py
build/.../Offline/pywrap/_MCDataProducts.so

and Muse will add this directory to the PYTHONPATH

To use the wrapper, after "muse setup" of a build with the wrapper,

>>> import MCDataProducts
>>> gid=MCDataProducts.GenId()
>>> gid.name(1)
'particleGun'
>>> gid.findByName('particleGun').id()
1
>>> gid.particleGun
1
>>> 
>>> pc=MCDataProducts.ProcessCode()
>>> pc.name(14)
'Decay'
>>> pc.findByName('Decay').id()
14