Belle II Software  release-05-01-25
register_pystorearray.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 
4 
8 
9 import os
10 import math
11 import random
12 import numpy as np
13 
14 import basf2
15 import ROOT
16 from ROOT import Belle2
17 
18 import simulation
19 
20 
21 class SillyGeneratorModule(basf2.Module):
22  """Small module to demonstrate how the registration of StoreArrays works from Python"""
23 
24  def initialize(self):
25  """ Register a StoreArray on the DataStore"""
26  mcParticles = Belle2.PyStoreArray(Belle2.MCParticle.Class())
27  mcParticles.registerInDataStore()
28 
29  def event(self):
30  """ Access and fill the registered StoreArray """
31  # Alternative access by name
32  mcParticles = Belle2.PyStoreArray("MCParticles")
33  mcParticle = mcParticles.appendNew()
34 
35  # Fill one test muon for demonstration
36  vertex = ROOT.TVector3(0, 0, 0)
37 
38  # Sample a random momentum vector of
39  # gaus distributed length and uniform distibuted direction
40  phi = ROOT.gRandom.Uniform(0.0, 2.0 * math.pi)
41  costheta = ROOT.gRandom.Uniform(-1.0, 1.0)
42  theta = math.acos(costheta)
43  r = max(0, ROOT.gRandom.Gaus(1, 0.2))
44  momentum = ROOT.TVector3(0, 0, 0)
45  momentum.SetMagThetaPhi(1, theta, phi)
46 
47  mcParticle.setPDG(13)
48  mcParticle.setMassFromPDG()
49  mcParticle.addStatus(Belle2.MCParticle.c_PrimaryParticle)
50  mcParticle.addStatus(Belle2.MCParticle.c_StableInGenerator)
51  mcParticle.setProductionVertex(vertex)
52  mcParticle.setMomentum(momentum)
53  m = mcParticle.getMass()
54  mcParticle.setEnergy(math.sqrt(momentum * momentum + m * m))
55  mcParticle.setDecayTime(float("inf"))
56 
57 
58 class ParticleStatisticsModule(basf2.Module):
59  """Collect statistics on particles - also parallel processable"""
60 
61  def __init__(self):
62  """set module flags"""
63  super().__init__()
64  self.set_property_flags(
65  basf2.ModulePropFlags.PARALLELPROCESSINGCERTIFIED |
66  basf2.ModulePropFlags.TERMINATEINALLPROCESSES)
67 
68  def initialize(self):
69  """init"""
70 
71  self.tfile = ROOT.TFile("ParticleStatistics.root", "recreate")
72 
73  ntuple = Belle2.PyStoreObj(Belle2.RootMergeable("TNtuple").Class(), "ParticleMomenta", Belle2.DataStore.c_Persistent)
74  ntuple.registerInDataStore()
75  print("IsValid", ntuple.isValid())
76  ntuple.create()
77  print("IsValid", ntuple.isValid())
78  ntuple.obj().assign(ROOT.TNtuple("Particles", # ROOT name
79  "Momentum compontents of the particles", # ROOT title
80  "px:py:pz" # Var list
81  ))
82 
83  hist = Belle2.PyStoreObj(Belle2.RootMergeable("TH1D").Class(), "AbsMomentum", Belle2.DataStore.c_Persistent)
84  hist.registerInDataStore()
85  print("IsValid", hist.isValid())
86  hist.create()
87  print("IsValid", hist.isValid())
88  hist.obj().assign(ROOT.TH1D("AbsMomentum", # ROOT name
89  "Absolute momentum of particles", # ROOT title
90  20, # n bins
91  0, # upper bound
92  2 # lower bound
93  ))
94 
95  print("IsValid", ntuple.isValid())
96  print("IsValid", hist.isValid())
97 
98  def event(self):
99  """actually collect info"""
100  ntuple = Belle2.PyStoreObj("ParticleMomenta", Belle2.DataStore.c_Persistent)
101  hist = Belle2.PyStoreObj("AbsMomentum", Belle2.DataStore.c_Persistent)
102 
103  mcParticles = Belle2.PyStoreArray(Belle2.MCParticle.Class())
104 
105  for mcParticle in mcParticles:
106  momentum = mcParticle.getMomentum()
107  ntuple.get().Fill(momentum.X(),
108  momentum.Y(),
109  momentum.Z())
110 
111  hist.get().Fill(momentum.Mag())
112 
113  def terminate(self):
114  """terminate"""
117  print("Writting objects")
118  ntuple = Belle2.PyStoreObj("ParticleMomenta", Belle2.DataStore.c_Persistent)
119  ntuple.write(self.tfile)
120 
121  hist = Belle2.PyStoreObj("AbsMomentum", Belle2.DataStore.c_Persistent)
122  hist.write(self.tfile)
123 
124  self.tfile.Close()
125 
126 
127 def main():
128  path = basf2.create_path()
129  path.add_module('EventInfoSetter',
130  evtNumList=[1000],
131  runList=[1],
132  expList=[1]
133  )
134 
135  path.add_module(SillyGeneratorModule())
136  path.add_module(ParticleStatisticsModule())
137 
138  basf2.process(path)
139 
140  # Print call statistics
141  print(basf2.statistics)
142 
143 
144 if __name__ == "__main__":
145  main()
register_pystorearray.ParticleStatisticsModule.__init__
def __init__(self)
Definition: register_pystorearray.py:61
Belle2::RootMergeable
Wrap a root histogram or TNtuple to make it mergeable.
Definition: RootMergeable.h:70
register_pystorearray.ParticleStatisticsModule.event
def event(self)
Definition: register_pystorearray.py:98
register_pystorearray.SillyGeneratorModule.initialize
def initialize(self)
Definition: register_pystorearray.py:24
Belle2::PyStoreObj
a (simplified) python wrapper for StoreObjPtr.
Definition: PyStoreObj.h:69
register_pystorearray.SillyGeneratorModule
Definition: register_pystorearray.py:21
basf2.process
def process(path, max_event=0)
Definition: __init__.py:25
Belle2::ProcHandler::isOutputProcess
static bool isOutputProcess()
Return true if the process is an output process.
Definition: ProcHandler.cc:227
register_pystorearray.ParticleStatisticsModule.initialize
def initialize(self)
Definition: register_pystorearray.py:68
register_pystorearray.ParticleStatisticsModule
Definition: register_pystorearray.py:58
main
int main(int argc, char **argv)
Run all tests.
Definition: test_main.cc:77
register_pystorearray.ParticleStatisticsModule.tfile
tfile
save statistics in here
Definition: register_pystorearray.py:71
register_pystorearray.SillyGeneratorModule.event
def event(self)
Definition: register_pystorearray.py:29
Belle2::PyStoreArray
a (simplified) python wrapper for StoreArray.
Definition: PyStoreArray.h:58
register_pystorearray.ParticleStatisticsModule.terminate
def terminate(self)
Definition: register_pystorearray.py:113
Belle2::ProcHandler::parallelProcessingUsed
static bool parallelProcessingUsed()
Returns true if multiple processes have been spawned, false in single-core mode.
Definition: ProcHandler.cc:221