Archive for February, 2010
TCanvases in PyROOT
When working with TCanvases in PyROOT[1], they can suddenly disappear. This seems to be due to Python’s garbage collection, i.e. when doing the following:
import ROOT ROOT.TCanvas()
Python at some point thinks, the newly created TCanvas object is not needed any more (i.e. there is no variable pointing to it) and seems to remove it. To illustrate this, I ran the garbage collector by hand:
import gc gc.collect()
and the TCanvas disappears from the screen.
I saw that one can fix this behavior by setting an object ownership flag[2] (on a per-instance basis) by doing:
canv = ROOT.TCanvas() ROOT.SetOwnership(canv,False)
Profiting from Python’s ability to redefine methods and classes at runtime, I have put the following code in one of my initialization files:
import ROOT # keep a pointer to the original TCanvas constructor oldinit = ROOT.TCanvas.__init__ # define a new TCanvas class (inheriting from the original one), # setting the memory ownership in the constructor class GarbageCollectionResistentCanvas(ROOT.TCanvas): def __init__(self, *args): oldinit(self,*args) ROOT.SetOwnership(self,False) # replace the old TCanvas class by the new one ROOT.TCanvas = GarbageCollectionResistentCanvas
Whenever I create a new TCanvas, the ownership flag is set automatically and the resulting canvas resists the garbage collection.
References:
[1] http://root.cern.ch/drupal/content/how-use-use-python-pyroot-interpreter
[2] http://root.cern.ch/phpBB2/viewtopic.php?t=9786&sid=039b50aac41b93648e49387f188ad741