Belle II Software  light-2205-abys
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/dataobjects/Particle.h>
13 #include <analysis/dataobjects/ParticleList.h>
14 #include <analysis/dataobjects/ParticleExtraInfoMap.h>
15 #include <analysis/dataobjects/EventExtraInfo.h>
16 
17 #include <mva/interface/Interface.h>
18 
19 #include <boost/algorithm/string/predicate.hpp>
20 #include <memory>
21 
22 #include <framework/logging/Logger.h>
23 
24 
25 using namespace Belle2;
26 
27 REG_MODULE(MVAExpert);
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*",
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.");
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  "If true, when the given extraInfo has already defined, the old extraInfo value is overwritten. If false, the original value is kept.",
45  true);
46 }
47 
49 {
50  // All specified ParticleLists are required to exist
51  for (auto& name : m_listNames) {
52  StoreObjPtr<ParticleList> list(name);
53  list.isRequired();
54  }
55 
56  if (m_listNames.empty()) {
58  extraInfo.registerInDataStore();
59  } else {
61  extraInfo.registerInDataStore();
62  }
63 
64  if (not(boost::ends_with(m_identifier, ".root") or boost::ends_with(m_identifier, ".xml"))) {
65  m_weightfile_representation = std::make_unique<DBObjPtr<DatabaseRepresentationOfWeightfile>>(
66  MVA::makeSaveForDatabase(m_identifier));
67  }
69 
70  m_existGivenExtraInfo = false;
71 }
72 
74 {
75 
77  if (m_weightfile_representation->hasChanged()) {
78  std::stringstream ss((*m_weightfile_representation)->m_data);
79  auto weightfile = MVA::Weightfile::loadFromStream(ss);
80  init_mva(weightfile);
81  }
82  } else {
84  init_mva(weightfile);
85  }
86 
87 }
88 
90 {
91 
92  auto supported_interfaces = MVA::AbstractInterface::getSupportedInterfaces();
93  MVA::GeneralOptions general_options;
94  weightfile.getOptions(general_options);
95 
96  // Overwrite signal fraction from training
99 
100  m_expert = supported_interfaces[general_options.m_method]->getExpert();
101  m_expert->load(weightfile);
102 
104  m_feature_variables = manager.getVariables(general_options.m_variables);
105  if (m_feature_variables.size() != general_options.m_variables.size()) {
106  B2FATAL("One or more feature variables could not be loaded via the Variable::Manager. Check the names!");
107  }
108 
109  std::vector<float> dummy;
110  dummy.resize(m_feature_variables.size(), 0);
111  m_dataset = std::make_unique<MVA::SingleDataset>(general_options, dummy, 0);
112 
113 }
114 
116 {
117  if (not m_expert) {
118  B2ERROR("MVA Expert is not loaded! I will return 0");
119  return 0.0;
120  }
121  for (unsigned int i = 0; i < m_feature_variables.size(); ++i) {
122  auto var_result = m_feature_variables[i]->function(particle);
123  if (std::holds_alternative<double>(var_result)) {
124  m_dataset->m_input[i] = std::get<double>(var_result);
125  } else if (std::holds_alternative<int>(var_result)) {
126  m_dataset->m_input[i] = std::get<int>(var_result);
127  } else if (std::holds_alternative<bool>(var_result)) {
128  m_dataset->m_input[i] = std::get<bool>(var_result);
129  }
130  }
131  return m_expert->apply(*m_dataset)[0];
132 }
133 
134 
136 {
137  for (auto& listName : m_listNames) {
138  StoreObjPtr<ParticleList> list(listName);
139  // Calculate target Value for Particles
140  for (unsigned i = 0; i < list->getListSize(); ++i) {
141  Particle* particle = list->getParticle(i);
142  float targetValue = analyse(particle);
143  if (particle->hasExtraInfo(m_extraInfoName)) {
144  if (particle->getExtraInfo(m_extraInfoName) != targetValue) {
145  m_existGivenExtraInfo = true;
147  particle->setExtraInfo(m_extraInfoName, targetValue);
148  }
149  } else {
150  particle->addExtraInfo(m_extraInfoName, targetValue);
151  }
152  }
153  }
154  if (m_listNames.empty()) {
155  StoreObjPtr<EventExtraInfo> eventExtraInfo;
156  if (not eventExtraInfo.isValid())
157  eventExtraInfo.create();
158 
159  float targetValue = analyse(nullptr);
160  if (eventExtraInfo->hasExtraInfo(m_extraInfoName)) {
161  m_existGivenExtraInfo = true;
163  eventExtraInfo->setExtraInfo(m_extraInfoName, targetValue);
164  } else {
165  eventExtraInfo->addExtraInfo(m_extraInfoName, targetValue);
166  }
167  }
168 }
169 
171 {
172  m_expert.reset();
173  m_dataset.reset();
174 
175  if (m_existGivenExtraInfo) {
177  B2WARNING("The extraInfo " << m_extraInfoName << " has already been set! It was overwritten by this module!");
178  else
179  B2WARNING("The extraInfo " << m_extraInfoName << " has already been set! "
180  << "The original value was kept and this module did not overwrite it!");
181  }
182 }
@ c_Event
Different object in each event, all objects/arrays are invalidated after event() function has been ca...
Definition: DataStore.h:59
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.
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::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.
bool m_existGivenExtraInfo
check if the given extraInfo is already defined.
float analyse(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.
bool m_overwriteExistingExtraInfo
if true, when the given extraInfo is already defined, the old extraInfo value is overwritten
std::string m_identifier
weight-file
static std::map< std::string, AbstractInterface * > getSupportedInterfaces()
Returns interfaces supported by the MVA Interface.
Definition: Interface.h:53
static void initSupportedInterfaces()
Static function which initliazes all supported interfaces, has to be called once before getSupportedI...
Definition: Interface.cc:45
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:250
void getOptions(Options &options) const
Fills an Option object from the xml tree.
Definition: Weightfile.cc:66
static Weightfile loadFromFile(const std::string &filename)
Static function which loads a Weightfile from a file.
Definition: Weightfile.cc:205
void addSignalFraction(float signal_fraction)
Saves the signal fraction in the xml tree.
Definition: Weightfile.cc:94
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:74
void setExtraInfo(const std::string &name, double value)
Sets the user-defined data of given name to the given value.
Definition: Particle.cc:1306
bool hasExtraInfo(const std::string &name) const
Return whether the extra info with the given name is set.
Definition: Particle.cc:1255
void addExtraInfo(const std::string &name, double value)
Sets the user-defined data of given name to the given value.
Definition: Particle.cc:1325
double getExtraInfo(const std::string &name) const
Return given value if set.
Definition: Particle.cc:1278
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:101
static Manager & Instance()
get singleton instance.
Definition: Manager.cc:25
REG_MODULE(B2BIIConvertBeamParams)
Register the module.
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:560
Abstract base class for different kinds of events.
Definition: ClusterUtils.h:23