Belle II Software development
PXDBackgroundGenerator Class Reference

Class for the PXD background generator module. More...

Inheritance diagram for PXDBackgroundGenerator:

Public Member Functions

 __init__ (self, str model="convnet", Union[None, str, pathlib.Path] checkpoint=None, Union[None, int] seed=None, int nintra=1, int ninter=1, str globaltag="PXDBackgroundGenerator")
 Constructor for the PXD background generator module.
 
 initialize (self)
 Method called before event processing to initialize the module.
 
 event (self)
 Method called each time an event is processed.
 

Public Attributes

 model = _verify_model(model)
 Name of the generator model.
 
 checkpoint = _verify_checkpoint(checkpoint)
 Path to the checkpoint file with the pre-trained model weights.
 
 seed = _verify_seed(seed)
 Integer number in the interval $ [-2^{63}, 2^{63} - 1] $ set as the initial seed.
 
 nintra = _verify_nintra(nintra)
 Number of intra-op threads utilized.
 
 ninter = _verify_ninter(ninter)
 Number of inter-op threads utilized.
 
 globaltag = _verify_globaltag(globaltag)
 Global tag of the conditions database providing the default checkpoints stored as payloads.
 

Protected Attributes

 _generate_func = _get_generate_func(self.model)
 Generation function applied on the model instance to return an output that is transcoded into digits.
 
 _generator = _get_model_cls(self.model)()
 Generator model instance.
 
 _vxdids = tuple(VxdID(*arg) for arg in VXDID_ARGS)
 Sequence of identifier objects for each PXD module.
 
 _pystorearray = PyStoreArray("PXDDigits", DataStore.c_DontWriteOut)
 Accessor for PXD background digits in the data store.
 

Detailed Description

Class for the PXD background generator module.

Generates PXD background samples for background overlay on the fly.

:param model: Name of the generator model to use - either "convnet" or "resnet",
    defaults to "convnet" (optional)
:type model: str

:param checkpoint: Path to the checkpoint file with weights for the selected model,
    defaults to None - use the default checkpoint from the conditions database (optional)
:type checkpoint: str

:param seed: Integer number in the interval :math:`[-2^{63}, 2^{63} - 1]`
    used internally as the initial seed,
    defaults to None - derive a deterministic seed from the
    value returned by :py:func:`basf2.get_random_seed` (optional)
:type seed: int

:param nintra: Number of intra-op threads to be utilized for the generation,
    defaults to 1 (optional)
:type nintra: int

:param ninter: Number of inter-op threads to be utilized for the generation,
    defaults to 1 (optional)
:type ninter: int

:param globaltag: Global tag of the conditions database
    providing the default checkpoints stored as payloads,
    defaults to "PXDBackgroundGenerator" (optional)
:type globaltag: str

Definition at line 138 of file __init__.py.

Constructor & Destructor Documentation

◆ __init__()

__init__ ( self,
str model = "convnet",
Union[None, str, pathlib.Path] checkpoint = None,
Union[None, int] seed = None,
int nintra = 1,
int ninter = 1,
str globaltag = "PXDBackgroundGenerator" )

Constructor for the PXD background generator module.

Parameters
modelName of the generator model to use - either "convnet" or "resnet", defaults to "convnet"
checkpointPath to the checkpoint file with weights for the selected model, defaults to None - use the default checkpoint from the conditions database
seedInteger number in the interval $ [-2^{63}, 2^{63} - 1] $ used internally as the initial seed, defaults to None - derive a deterministic seed from the value returned by basf2.get_random_seed()
nintraNumber of intra-op threads to be utilized for the generation, defaults to 1
ninterNumber of inter-op threads to be utilized for the generation, defaults to 1
globaltagGlobal tag of the conditions database providing the default checkpoints stored as payloads, defaults to "PXDBackgroundGenerator"

Definition at line 192 of file __init__.py.

200 ):
201 super().__init__()
202 # process `model`
203 self.model = _verify_model(model)
204
205 # process `checkpoint`
206 self.checkpoint = _verify_checkpoint(checkpoint)
207
208 # process `seed`
209 self.seed = _verify_seed(seed)
210
211 # process `nintra`
212 self.nintra = _verify_nintra(nintra)
213
214 # process `ninter`
215 self.ninter = _verify_ninter(ninter)
216
217 # process `globaltag`
218 self.globaltag = _verify_globaltag(globaltag)
219
220 # enable the specified global tag
221 basf2.conditions.append_globaltag(self.globaltag)
222

Member Function Documentation

◆ event()

event ( self)

Method called each time an event is processed.

Definition at line 288 of file __init__.py.

288 def event(self):
289 # get the low-level array accessor
290 digit_array = self._pystorearray.getPtr()
291
292 # clear digits stored by BGOverlayInput
293 digit_array.Clear()
294
295 # generate a batch of images - one image for each PXD module
296 x = self._generate_func(self._generator)
297
298 # locate indices of pixels with non-zero values - pixel hits
299 nonzero = x.nonzero(as_tuple=True)
300 args = [indices.tolist() for indices in nonzero]
301 vals = x[nonzero].tolist()
302
303 # store indices and pixel values into the data store as background digits
304 for n, (idx, ucell, vcell, charge) in enumerate(zip(*args, vals)):
305 # append a new default digit to expand the array
306 self._pystorearray.appendNew()
307 # modify the array to point to the correct digit
308 digit_array[n] = PXDDigit(self._vxdids[idx], ucell, vcell, charge)
309
310 # delete references to release memory
311 del x, nonzero, args, vals
312

◆ initialize()

initialize ( self)

Method called before event processing to initialize the module.

Definition at line 225 of file __init__.py.

225 def initialize(self):
226 try:
227 import torch
228 except ImportError as exc:
229 exc.msg = "please install PyTorch: `pip3 install torch==1.4.0`"
230 raise
231
232 # set the number of inter-op CPU threads
233 torch.set_num_interop_threads(self.ninter)
234
235 # set the number of intra-op CPU threads
236 torch.set_num_threads(self.nintra)
237
238 # get the generation function for the selected model
239 self._generate_func = _get_generate_func(self.model)
240
241 # instantiate the generator model
242 self._generator = _get_model_cls(self.model)()
243
244 # initialize the model weights
245 checkpoint = self.checkpoint
246 if self.checkpoint is None:
247 # use the default checkpoint from the conditions database
248 payload = f"PXDBackgroundGenerator_{self.model}"
249 accessor = DBAccessorBase(DBStoreEntry.c_RawFile, payload, True)
250 checkpoint = accessor.getFilename()
251 self._generator.load_state_dict(torch.load(checkpoint, map_location="cpu"))
252
253 # set mode of operation to inference
254 self._generator.eval()
255
256 # disable the computation of gradients
257 for param in self._generator.parameters():
258 param.requires_grad = False
259
260 # initialize the seed
261 seed = self.seed
262 if seed is None:
263 # derive from the basf2 seed value
264 obj = basf2.get_random_seed()
265 func = hashlib.sha512()
266 func.update(bytes(str(obj), "utf-8"))
267 digest = func.digest()[:8]
268 seed = int.from_bytes(digest, "big", signed=True)
269 basf2.B2INFO(f"PXD background generator seed initialized to {seed}")
270 torch.manual_seed(seed)
271
272 # instantiate objects for specifying distinct PXD modules
273 self._vxdids = tuple(VxdID(*arg) for arg in VXDID_ARGS)
274
275 # get the name of the extension used by BGOverlayInput for background collections
276 bkginfo = PyStoreObj("BackgroundInfo", DataStore.c_Persistent)
277 if not bkginfo.isValid():
278 # no information about background overlay input available
279 basf2.B2ERROR("path must contain the BGOverlayInput module")
280 extension = bkginfo.getExtensionName()
281
282 # register the PXD background digit collection - array - in the data store
283 self._pystorearray = PyStoreArray("PXDDigits", DataStore.c_DontWriteOut)
284 self._pystorearray.registerInDataStore(f"PXDDigits{extension}")
285

Member Data Documentation

◆ _generate_func

_generate_func = _get_generate_func(self.model)
protected

Generation function applied on the model instance to return an output that is transcoded into digits.

Definition at line 239 of file __init__.py.

◆ _generator

_generator = _get_model_cls(self.model)()
protected

Generator model instance.

Definition at line 242 of file __init__.py.

◆ _pystorearray

_pystorearray = PyStoreArray("PXDDigits", DataStore.c_DontWriteOut)
protected

Accessor for PXD background digits in the data store.

Definition at line 283 of file __init__.py.

◆ _vxdids

_vxdids = tuple(VxdID(*arg) for arg in VXDID_ARGS)
protected

Sequence of identifier objects for each PXD module.

Definition at line 273 of file __init__.py.

◆ checkpoint

checkpoint = _verify_checkpoint(checkpoint)

Path to the checkpoint file with the pre-trained model weights.

Definition at line 206 of file __init__.py.

◆ globaltag

globaltag = _verify_globaltag(globaltag)

Global tag of the conditions database providing the default checkpoints stored as payloads.

Definition at line 218 of file __init__.py.

◆ model

model = _verify_model(model)

Name of the generator model.

Definition at line 203 of file __init__.py.

◆ ninter

ninter = _verify_ninter(ninter)

Number of inter-op threads utilized.

Definition at line 215 of file __init__.py.

◆ nintra

nintra = _verify_nintra(nintra)

Number of intra-op threads utilized.

Definition at line 212 of file __init__.py.

◆ seed

seed = _verify_seed(seed)

Integer number in the interval $ [-2^{63}, 2^{63} - 1] $ set as the initial seed.

Definition at line 209 of file __init__.py.


The documentation for this class was generated from the following file: