TCanvases in PyROOT

Posted on February 16, 2010. Filed under: Uncategorized | Tags: , , , , , |

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

Advertisements

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Liked it here?
Why not try sites on the blogroll...

%d bloggers like this: