Belle II Software development
PXDBackgroundGenerator Class Reference

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

Inheritance diagram for PXDBackgroundGenerator:

Public Member Functions

def __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.
 
def initialize (self)
 Method called before event processing to initialize the module.
 
def event (self)
 Method called each time an event is processed.
 

Public Attributes

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

Protected Attributes

 _generate_func
 Generation function applied on the model instance to return an output that is transcoded into digits.
 
 _generator
 Generator model instance.
 
 _vxdids
 Sequence of identifier objects for each PXD module.
 
 _pystorearray
 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 137 of file __init__.py.

Constructor & Destructor Documentation

◆ __init__()

def __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 191 of file __init__.py.

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

Member Function Documentation

◆ event()

def event (   self)

Method called each time an event is processed.

Definition at line 287 of file __init__.py.

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

◆ initialize()

def initialize (   self)

Method called before event processing to initialize the module.

Definition at line 224 of file __init__.py.

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

Member Data Documentation

◆ _generate_func

_generate_func
protected

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

Definition at line 238 of file __init__.py.

◆ _generator

_generator
protected

Generator model instance.

Definition at line 241 of file __init__.py.

◆ _pystorearray

_pystorearray
protected

Accessor for PXD background digits in the data store.

Definition at line 282 of file __init__.py.

◆ _vxdids

_vxdids
protected

Sequence of identifier objects for each PXD module.

Definition at line 272 of file __init__.py.

◆ checkpoint

checkpoint

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

Definition at line 205 of file __init__.py.

◆ globaltag

globaltag

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

Definition at line 217 of file __init__.py.

◆ model

model

Name of the generator model.

Definition at line 202 of file __init__.py.

◆ ninter

ninter

Number of inter-op threads utilized.

Definition at line 214 of file __init__.py.

◆ nintra

nintra

Number of intra-op threads utilized.

Definition at line 211 of file __init__.py.

◆ seed

seed

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

Definition at line 208 of file __init__.py.


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