HepMC is a standard format for Monte Carlo event records. It has a native C++ interface for reading, manipulating, and writing. If you’re like me and sometimes like to try an idea quickly and dirtily without knowing if it will lead anywhere (fun, exciting results, fan mail, Nobel prize), you may prefer using Python as a more high-level and agile alternative to C++. Luckily for you and me, Andy Buckley has created a nifty Python interface for HepMC, which you can find here. Just install, import hepmc, and start having fun!

I’d just like to supply a hint or two about pyhepmc here.

To open files in read mode, use the 'r' argument:

fpath = 'foo/bar.hepmc'
reader = hepmc.IO_GenEvent(fpath, 'r')

This is exactly as in Python’s native open(), but it might not be entirely obvious to a new user.

The default is to open files in write mode, 'w'. This will overwrite any existing files with empty ones.

Iterating

To cleanly iterate over events in a file, I recommend writing a generator. Mine is similar to Igor Babuschkin’s here:

def iterate_events(fpath):
    reader = hepmc.IO_GenEvent(fpath, 'r')
    evt = reader.get_next_event()
    while evt.is_valid():
        yield evt
        evt = reader.get_next_event()

You can then loop over events like this:

for evt in iterate_events(fpath):
	# do something
	pass

Neat!

Without writing any generators yourself, you can iterate over e.g. the particles in a HepMC event:

for p in evt.particles():
	# use e.g. p.status(), p.pdg_id(), p.momentum()
	pass

I hope you enjoy pythonic HepMC as much as I do!