CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
cropTnPTrees.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 import ROOT
3 ROOT.gROOT.SetBatch(True)
4 
5 import sys
6 
7 from optparse import OptionParser
8 parser = OptionParser(usage = "usage: %prog [options] inputFile fraction outputFile",
9  version = "%prog $Id: cropTnPTrees.py,v 1.1 2010/05/07 14:22:37 gpetrucc Exp $")
10 (options, args) = parser.parse_args()
11 
12 if len(args) <= 2:
13  parser.print_usage()
14  sys.exit(2)
15 
16 try:
17  frac = float(args[1])
18 except TypeError:
19  parser.print_usage()
20  print "fraction must be a floating point number (e.g. 0.5)"
21  sys.exit(2)
22 
23 input = ROOT.TFile(args[0])
24 output = ROOT.TFile(args[2], "RECREATE")
25 for k in input.GetListOfKeys():
26  print k.GetName(), k.GetClassName()
27  if k.GetClassName() == "TDirectoryFile":
28  print " processing directory ",k.GetName()
29  din = input.Get(k.GetName())
30  dout = output.mkdir(k.GetName())
31  for i in din.GetListOfKeys():
32  if i.GetClassName() == "TTree":
33  src = din.Get(i.GetName()) #i.ReadObj(); # ReadObj doesn't work!!!
34  newEntries = int(src.GetEntries()*frac)
35  print " cropped TTree",i.GetName(),", original entries",src.GetEntries(), ", new entries",newEntries
36  cloned = src.CloneTree(newEntries)
37  dout.WriteTObject(cloned, i.GetName())
38  elif i.GetClassName() != "TDirectory":
39  dout.WriteTObject(i.ReadObj(), i.GetName())
40  print " copied ",i.GetClassName(),i.GetName()
41 
42