Belle II Software development
MVAExpertModule.cc
1/**************************************************************************
2 * basf2 (Belle II Analysis Software Framework) *
3 * Author: The Belle II Collaboration *
4 * *
5 * See git log for contributors and copyright holders. *
6 * This file is licensed under LGPL-3.0, see LICENSE.md. *
7 **************************************************************************/
8
9
10#include <mva/modules/MVAExpert/MVAExpertModule.h>
11
12#include <analysis/DecayDescriptor/DecayDescriptorParticle.h>
13
14#include <analysis/dataobjects/Particle.h>
15#include <analysis/dataobjects/ParticleList.h>
16#include <analysis/dataobjects/ParticleExtraInfoMap.h>
17
18#include <mva/interface/Interface.h>
19
20#include <boost/algorithm/string/predicate.hpp>
21
22#include <framework/logging/Logger.h>
23
24
25using namespace Belle2;
26
28
30{
31 setDescription("Adds an ExtraInfo to the Particle objects in given ParticleLists which is calcuated by an expert defined by a weightfile.");
33
34 std::vector<std::string> empty;
35 addParam("listNames", m_listNames,
36 "Particles from these ParticleLists are used as input. If no name is given the expert is applied to every event once, and one can only use variables which accept nullptr as Particle*. Decay descriptor functionality is supported, which allows to run the module on daughter particles, e.g. Lambda0:my_list -> ^p+ pi-. One has to provide full name of the mother particle list and only one selected daughter is supported.",
37 empty);
38 addParam("extraInfoName", m_extraInfoName,
39 "Name under which the output of the expert is stored in the ExtraInfo of the Particle object. If the expert returns multiple values, the index of the value is appended to the name in the form '_0', '_1', ...");
40 addParam("identifier", m_identifier, "The database identifier which is used to load the weights during the training.");
41 addParam("signalFraction", m_signal_fraction_override,
42 "signalFraction to calculate probability (if -1 the signalFraction of the training data is used)", -1.0);
43 addParam("overwriteExistingExtraInfo", m_overwriteExistingExtraInfo,
44 "-1/0/1/2: Overwrite if lower / don't overwrite / overwrite if higher / always overwrite, in case the extra info with given name already exists",
45 2);
46}
47
49{
50 // All specified ParticleLists are required to exist
51 for (auto& name : m_listNames) {
53 bool valid = dd.init(name);
54 if (!valid) {
55 B2ERROR("Decay string " << name << " is invalid.");
56 }
57 const DecayDescriptorParticle* mother = dd.getMother();
58 unsigned int nSelectedDaughters = dd.getSelectionNames().size();
59 if (nSelectedDaughters > 1) {
60 B2ERROR("More than one daughter is selected in the decay string " << name << ".");
61 }
63 list.isRequired();
64 m_targetListNames.push_back(mother->getFullName());
65 m_decaydescriptors.insert(std::make_pair(mother->getFullName(), dd));
66 }
67
68 if (m_listNames.empty()) {
70 extraInfo.isRequired();
71 } else {
73 extraInfo.isRequired();
74 }
75
76 if (not(boost::ends_with(m_identifier, ".root") or boost::ends_with(m_identifier, ".xml"))) {
77 m_weightfile_representation = std::make_unique<DBObjPtr<DatabaseRepresentationOfWeightfile>>(
78 MVA::makeSaveForDatabase(m_identifier));
79 }
81
83}
84
86{
87
89 if (m_weightfile_representation->hasChanged()) {
90 std::stringstream ss((*m_weightfile_representation)->m_data);
91 auto weightfile = MVA::Weightfile::loadFromStream(ss);
92 init_mva(weightfile);
93 }
94 } else {
96 init_mva(weightfile);
97 }
98
99}
100
102{
103
104 auto supported_interfaces = MVA::AbstractInterface::getSupportedInterfaces();
105 MVA::GeneralOptions general_options;
106 weightfile.getOptions(general_options);
107
108 // Overwrite signal fraction from training
111
112 m_expert = supported_interfaces[general_options.m_method]->getExpert();
113 m_expert->load(weightfile);
114
116 m_feature_variables = manager.getVariables(general_options.m_variables);
117 if (m_feature_variables.size() != general_options.m_variables.size()) {
118 B2FATAL("One or more feature variables could not be loaded via the Variable::Manager. Check the names!");
119 }
120
121 std::vector<float> dummy;
122 dummy.resize(m_feature_variables.size(), 0);
123 m_dataset = std::make_unique<MVA::SingleDataset>(general_options, dummy, 0);
124 m_nClasses = general_options.m_nClasses;
125}
126
128{
129 for (unsigned int i = 0; i < m_feature_variables.size(); ++i) {
130 auto var_result = m_feature_variables[i]->function(particle);
131 if (std::holds_alternative<double>(var_result)) {
132 m_dataset->m_input[i] = std::get<double>(var_result);
133 } else if (std::holds_alternative<int>(var_result)) {
134 m_dataset->m_input[i] = std::get<int>(var_result);
135 } else if (std::holds_alternative<bool>(var_result)) {
136 m_dataset->m_input[i] = std::get<bool>(var_result);
137 }
138 }
139}
140
141float MVAExpertModule::analyse(const Particle* particle)
142{
143 if (not m_expert) {
144 B2ERROR("MVA Expert is not loaded! I will return 0");
145 return 0.0;
146 }
147 fillDataset(particle);
148 return m_expert->apply(*m_dataset)[0];
149}
150
151std::vector<float> MVAExpertModule::analyseMulticlass(const Particle* particle)
152{
153 if (not m_expert) {
154 B2ERROR("MVA Expert is not loaded! I will return 0");
155 return std::vector<float>(m_nClasses, 0.0);
156 }
157 fillDataset(particle);
158 return m_expert->applyMulticlass(*m_dataset)[0];
159}
160
161void MVAExpertModule::setExtraInfoField(Particle* particle, std::string extraInfoName, float responseValue)
162{
163 if (particle->hasExtraInfo(extraInfoName)) {
164 if (particle->getExtraInfo(extraInfoName) != responseValue) {
166 double current = particle->getExtraInfo(extraInfoName);
168 if (responseValue < current) particle->setExtraInfo(extraInfoName, responseValue);
169 } else if (m_overwriteExistingExtraInfo == 0) {
170 // don't overwrite!
171 } else if (m_overwriteExistingExtraInfo == 1) {
172 if (responseValue > current) particle->setExtraInfo(extraInfoName, responseValue);
173 } else if (m_overwriteExistingExtraInfo == 2) {
174 particle->setExtraInfo(extraInfoName, responseValue);
175 } else {
176 B2FATAL("m_overwriteExistingExtraInfo must be one of {-1,0,1,2}. Received '" << m_overwriteExistingExtraInfo << "'.");
177 }
178 }
179 } else {
180 particle->addExtraInfo(extraInfoName, responseValue);
181 }
182}
183
184void MVAExpertModule::setEventExtraInfoField(StoreObjPtr<EventExtraInfo> eventExtraInfo, std::string extraInfoName,
185 float responseValue)
186{
187 if (eventExtraInfo->hasExtraInfo(extraInfoName)) {
189 double current = eventExtraInfo->getExtraInfo(extraInfoName);
191 if (responseValue < current) eventExtraInfo->setExtraInfo(extraInfoName, responseValue);
192 } else if (m_overwriteExistingExtraInfo == 0) {
193 // don't overwrite!
194 } else if (m_overwriteExistingExtraInfo == 1) {
195 if (responseValue > current) eventExtraInfo->setExtraInfo(extraInfoName, responseValue);
196 } else if (m_overwriteExistingExtraInfo == 2) {
197 eventExtraInfo->setExtraInfo(extraInfoName, responseValue);
198 } else {
199 B2FATAL("m_overwriteExistingExtraInfo must be one of {-1,0,1,2}. Received '" << m_overwriteExistingExtraInfo << "'.");
200 }
201 } else {
202 eventExtraInfo->addExtraInfo(extraInfoName, responseValue);
203 }
204}
205
207{
208 for (auto& listName : m_targetListNames) {
209 StoreObjPtr<ParticleList> list(listName);
210 // Calculate target Value for Particles
211 for (unsigned i = 0; i < list->getListSize(); ++i) {
212 auto dd = m_decaydescriptors[listName];
213 unsigned int nSelectedDaughters = dd.getSelectionNames().size();
214 const Particle* particle = (nSelectedDaughters > 0) ? dd.getSelectionParticles(list->getParticle(i))[0] : list->getParticle(i);
215 if (m_nClasses == 2) {
216 float responseValue = analyse(particle);
217 setExtraInfoField(m_particles[particle->getArrayIndex()], m_extraInfoName, responseValue);
218 } else if (m_nClasses > 2) {
219 std::vector<float> responseValues = analyseMulticlass(particle);
220 if (responseValues.size() != m_nClasses) {
221 B2ERROR("Size of results returned by MVA Expert applyMulticlass (" << responseValues.size() <<
222 ") does not match the declared number of classes (" << m_nClasses << ").");
223 }
224 for (unsigned int iClass = 0; iClass < m_nClasses; iClass++) {
225 setExtraInfoField(m_particles[particle->getArrayIndex()], m_extraInfoName + "_" + std::to_string(iClass), responseValues[iClass]);
226 }
227 } else {
228 B2ERROR("Received a value of " << m_nClasses <<
229 " for the number of classes considered by the MVA Expert. This value should be >=2.");
230 }
231 }
232 }
233 if (m_listNames.empty()) {
234 StoreObjPtr<EventExtraInfo> eventExtraInfo;
235 if (not eventExtraInfo.isValid())
236 eventExtraInfo.create();
237
238 if (m_nClasses == 2) {
239 float responseValue = analyse(nullptr);
240 setEventExtraInfoField(eventExtraInfo, m_extraInfoName, responseValue);
241 } else if (m_nClasses > 2) {
242 std::vector<float> responseValues = analyseMulticlass(nullptr);
243 if (responseValues.size() != m_nClasses) {
244 B2ERROR("Size of results returned by MVA Expert applyMulticlass (" << responseValues.size() <<
245 ") does not match the declared number of classes (" << m_nClasses << ").");
246 }
247 for (unsigned int iClass = 0; iClass < m_nClasses; iClass++) {
248 setEventExtraInfoField(eventExtraInfo, m_extraInfoName + "_" + std::to_string(iClass), responseValues[iClass]);
249 }
250 } else {
251 B2ERROR("Received a value of " << m_nClasses <<
252 " for the number of classes considered by the MVA Expert. This value should be >=2.");
253 }
254 }
255}
256
258{
259 m_expert.reset();
260 m_dataset.reset();
261
264 B2WARNING("The extraInfo " << m_extraInfoName <<
265 " has already been set! It was overwritten by this module if the new value was lower than the previous!");
266 } else if (m_overwriteExistingExtraInfo == 0) {
267 B2WARNING("The extraInfo " << m_extraInfoName <<
268 " has already been set! The original value was kept and this module did not overwrite it!");
269 } else if (m_overwriteExistingExtraInfo == 1) {
270 B2WARNING("The extraInfo " << m_extraInfoName <<
271 " has already been set! It was overwritten by this module if the new value was higher than the previous!");
272 } else if (m_overwriteExistingExtraInfo == 2) {
273 B2WARNING("The extraInfo " << m_extraInfoName << " has already been set! It was overwritten by this module!");
274 }
275 }
276}
@ c_Event
Different object in each event, all objects/arrays are invalidated after event() function has been ca...
Definition: DataStore.h:59
Represents a particle in the DecayDescriptor.
std::string getFullName() const
returns the full name of the particle full_name = name:label
The DecayDescriptor stores information about a decay tree or parts of a decay tree.
bool init(const std::string &str)
Initialise the DecayDescriptor from given string.
std::vector< std::string > getSelectionNames()
Return list of human readable names of selected particles.
const DecayDescriptorParticle * getMother() const
return mother.
std::unordered_map< std::string, DecayDescriptor > m_decaydescriptors
Decay descriptor of decays to look for.
std::unique_ptr< MVA::SingleDataset > m_dataset
Pointer to the current dataset.
std::vector< const Variable::Manager::Var * > m_feature_variables
Pointers to the feature variables.
virtual void initialize() override
Initialize the module.
virtual void event() override
Called for each event.
void setEventExtraInfoField(StoreObjPtr< EventExtraInfo >, std::string, float)
Set the event extra info field.
StoreArray< Particle > m_particles
StoreArray of Particles.
virtual void terminate() override
Called at the end of the event processing.
std::unique_ptr< MVA::Expert > m_expert
Pointer to the current MVA Expert.
double m_signal_fraction_override
Signal Fraction which should be used.
std::vector< std::string > m_targetListNames
input particle list names after decay descriptor
std::unique_ptr< DBObjPtr< DatabaseRepresentationOfWeightfile > > m_weightfile_representation
Database pointer to the Database representation of the weightfile.
std::vector< std::string > m_listNames
input particle list names
virtual void beginRun() override
Called at the beginning of a new run.
MVAExpertModule()
Constructor.
float analyse(const Particle *)
Calculates expert output for given Particle pointer.
bool m_existGivenExtraInfo
check if the given extraInfo is already defined.
int m_overwriteExistingExtraInfo
-1/0/1/2: overwrite if lower/ don't overwrite / overwrite if higher/ always overwrite,...
std::vector< float > analyseMulticlass(const Particle *)
Calculates expert output for given Particle pointer.
void init_mva(MVA::Weightfile &weightfile)
Initialize mva expert, dataset and features Called every time the weightfile in the database changes ...
std::string m_extraInfoName
Name under which the SignalProbability is stored in the extraInfo of the Particle object.
unsigned int m_nClasses
number of classes (~outputs) of the current MVA Expert.
void setExtraInfoField(Particle *, std::string, float)
Set the extra info field.
void fillDataset(const Particle *)
Evaluate the variables and fill the Dataset to be used by the expert.
std::string m_identifier
weight-file
Class to interact with the MVA package, based on class with same name in CDC package.
Definition: MVAExpert.h:33
static void initSupportedInterfaces()
Static function which initliazes all supported interfaces, has to be called once before getSupportedI...
Definition: Interface.cc:45
static std::map< std::string, AbstractInterface * > getSupportedInterfaces()
Returns interfaces supported by the MVA Interface.
Definition: Interface.h:53
General options which are shared by all MVA trainings.
Definition: Options.h:62
The Weightfile class serializes all information about a training into an xml tree.
Definition: Weightfile.h:38
static Weightfile loadFromStream(std::istream &stream)
Static function which deserializes a Weightfile from a stream.
Definition: Weightfile.cc:251
void getOptions(Options &options) const
Fills an Option object from the xml tree.
Definition: Weightfile.cc:67
static Weightfile loadFromFile(const std::string &filename)
Static function which loads a Weightfile from a file.
Definition: Weightfile.cc:206
void addSignalFraction(float signal_fraction)
Saves the signal fraction in the xml tree.
Definition: Weightfile.cc:95
Base class for Modules.
Definition: Module.h:72
void setDescription(const std::string &description)
Sets the description of the module.
Definition: Module.cc:214
void setPropertyFlags(unsigned int propertyFlags)
Sets the flags for the module properties.
Definition: Module.cc:208
@ c_ParallelProcessingCertified
This module can be run in parallel processing mode safely (All I/O must be done through the data stor...
Definition: Module.h:80
Class to store reconstructed particles.
Definition: Particle.h:76
bool isRequired(const std::string &name="")
Ensure this array/object has been registered previously.
Type-safe access to single objects in the data store.
Definition: StoreObjPtr.h:95
Global list of available variables.
Definition: Manager.h:100
static Manager & Instance()
get singleton instance.
Definition: Manager.cc:26
void addParam(const std::string &name, T &paramVariable, const std::string &description, const T &defaultValue)
Adds a new parameter to the module.
Definition: Module.h:559
#define REG_MODULE(moduleName)
Register the given module (without 'Module' suffix) with the framework.
Definition: Module.h:649
Abstract base class for different kinds of events.