Belle II Software light-2609-luna
__init__.py
1#!/usr/bin/env python3
2
9
10"""
11ModeSelector - Event-level B meson classification using neural networks.
12
13The FEI assigns a signal probability (sigProb) to each B candidate independently.
14ModeSelector uses the full set of FEI B candidates with sigProb > 0.001 simultaneously
15to classify the event and produce a refined score (BplusScore).
16
17Main components:
18
19- modeSelector(): main function to add ModeSelector to a basf2 path
20- addDstarVeto(): D* veto reconstruction (called automatically by modeSelector)
21
22See ``analysis/doc/ModeSelector.rst`` for usage instructions and
23``analysis/scripts/modeSelector/README.md`` for implementation details.
24"""
25
26from modeSelector import config
27from modeSelector.dstarVeto import addDstarVeto
28from modeSelector.generatedDecayWeights import (GeneratedDecayWeightModule,
29 addGeneratedDecayWeights)
30from modeSelector.ModeSelectorModule import ModeSelectorModule
31
32__all__ = [
33 'config',
34 'addGeneratedDecayWeights',
35 'modeSelector',
36 'addDstarVeto',
37 'GeneratedDecayWeightModule',
38 'ModeSelectorModule',
39]
40
41
42def modeSelector(
43 bp_list,
44 b0_list,
45 payload_cat_model=None,
46 payload_main_model=None,
47 output_variable='BplusScore',
48 cat_model_path=None,
49 main_model_path=None,
50 addDstarVetoReco=True,
51 training_mode=False,
52 skip_nn_evaluation=False,
53 store_fei_calib_weight=False,
54 debug=False,
55 debug_max_events=10,
56 path=None
57):
58 """
59 Add ModeSelector neural network evaluation to a basf2 path.
60
61 This function applies a two-stage neural network to FEI B meson candidates
62 to compute an improved signal probability score. The network considers
63 information from all B candidates in the event.
64
65 The main output score is stored in EventExtraInfo using output_variable.
66 Auxiliary category and per-candidate mode outputs are stored with the
67 fixed modeSelector_* names.
68
69 Parameters:
70 bp_list (str): B+ meson particle list name to process. Example: 'B+:feiHadronic'
71 b0_list (str): B0 meson particle list name to process. Example: 'B0:feiHadronic'
72 payload_cat_model (str): Conditions DB payload name for the category model.
73 Used only when cat_model_path is None. None (default) uses the name derived
74 from the contract version this release implements, and the training is chosen
75 by the performance globaltag. Passing a name always emits a warning that the
76 default payload is not used. A payload built for an older contract version runs
77 with that contract's behaviour if the version is in
78 config.SUPPORTED_CONTRACT_VERSIONS (with a warning); a newer or unsupported
79 version is fatal.
80 payload_main_model (str): Conditions DB payload name for the main model.
81 Used only when main_model_path is None. Same rules as payload_cat_model.
82 output_variable (str): Name of the ExtraInfo variable for the output score.
83 Default: 'BplusScore'
84 cat_model_path (str): Path to the basf2 MVA weightfile for the category network,
85 as produced by convert_to_onnx.py (a .root file, not a raw .onnx file).
86 If None, loads from conditions database.
87 main_model_path (str): Path to the basf2 MVA weightfile for the main network,
88 as produced by convert_to_onnx.py (a .root file, not a raw .onnx file).
89 If None, loads from conditions database.
90 skip_nn_evaluation (bool): If True, skip loading and evaluating the neural networks
91 and fill deterministic placeholder outputs instead. Intended for debugging or
92 timing studies and emits a warning at module initialization.
93 training_mode (bool): If True, skip NN inference and instead expose per-event
94 features and MC truth as EventExtraInfo/ExtraInfo (``modeSelector_feat_XXXX``,
95 ``modeSelector_tr_*``, ``modeSelector_trainSigInputId``) for a
96 variablesToNtuple call in the steering script to dump. See
97 ``analysis/examples/modeSelector/produceTrainingInputs.py``. Default: False.
98 addDstarVetoReco (bool): Whether to add D* veto reconstruction before the NN.
99 Default: True
100 debug (bool): If True, print the feature vector and network outputs for the first
101 few events. Intended for comparing against a reference implementation.
102 Default: False
103 debug_max_events (int): Number of events to print when debug is True. Default: 10
104 store_fei_calib_weight (bool): If True, compute and store modeSelector_feiCalibWeight
105 in EventExtraInfo using the reco path (truth-compatible tag PDG and
106 DeltaP < DELTA_P_THRESH). Returns NaN when reco conditions are not met.
107 Requires mostcommonBTagPDG and mostcommonBTagDeltaP to be defined.
108 Meaningful only on MC. Default: False.
109 path (basf2.Path): The basf2 path to add the module to.
110
111 Notes:
112 Candidate-level ``ExtraInfo`` (predicted sector only):
113
114 - ``modeSelector_eqSigProb``: main-network probability for the candidate's
115 specific decay mode.
116 - ``modeSelector_rank``: sector-local rank. Predicted sector ranked by
117 ``modeSelector_eqSigProb``; non-predicted sector ranked by ``sigProb``.
118
119 Event-level ``EventExtraInfo``:
120
121 - ``BplusScore`` (or the name given by ``output_variable``): signed score,
122 positive for B+ prediction, negative for B0.
123 - ``modeSelector_catB0``, ``modeSelector_catBp``, ``modeSelector_catCont``:
124 category network probabilities.
125
126 The D* veto reconstruction is added automatically (``addDstarVetoReco=True``).
127 Pass ``addDstarVetoReco=False`` to skip it if already added separately.
128 """
129 import basf2 as b2
130
131 if path is None:
132 b2.B2FATAL("Path is required for modeSelector")
133
134 if not isinstance(bp_list, str) or not bp_list:
135 b2.B2FATAL("ModeSelector: bp_list must be a non-empty string")
136 if not isinstance(b0_list, str) or not b0_list:
137 b2.B2FATAL("ModeSelector: b0_list must be a non-empty string")
138 if not bp_list.startswith('B+:'):
139 b2.B2FATAL(f"ModeSelector: bp_list must start with 'B+:'; got '{bp_list}'")
140 if not b0_list.startswith('B0:'):
141 b2.B2FATAL(f"ModeSelector: b0_list must start with 'B0:'; got '{b0_list}'")
142 particle_lists = [bp_list, b0_list]
143
144 if addDstarVetoReco:
145 # Add D* veto reconstruction (pi0 list created internally)
146 addDstarVeto(particle_lists, path=path)
147
148 # Add the ModeSelector module
149 module = ModeSelectorModule(
150 particle_lists=particle_lists,
151 payload_cat_model=payload_cat_model,
152 payload_main_model=payload_main_model,
153 output_variable=output_variable,
154 cat_model_path=cat_model_path,
155 main_model_path=main_model_path,
156 training_mode=training_mode,
157 skip_nn_evaluation=skip_nn_evaluation,
158 store_fei_calib_weight=store_fei_calib_weight,
159 debug=debug,
160 debug_max_events=debug_max_events,
161 )
162 path.add_module(module)
163
164 b2.B2INFO(f"ModeSelector: Added to path for particle lists: {particle_lists}")
165 b2.B2INFO(f"ModeSelector: Output variable: extraInfo({output_variable})")