Belle II Software  release-08-01-10
MVAExpert.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 #include <tracking/trackFindingCDC/mva/MVAExpert.h>
9 
11 #include <mva/dataobjects/DatabaseRepresentationOfWeightfile.h>
12 #include <mva/interface/Weightfile.h>
13 #include <mva/interface/Expert.h>
14 #include <framework/database/DBObjPtr.h>
15 #include <boost/algorithm/string/predicate.hpp>
16 
17 namespace Belle2 {
23  namespace MVA {
24  class Expert;
25  class SingleDataset;
26  class Weightfile;
27  }
28 
29  namespace TrackFindingCDC {
32 
33  public:
34  Impl(const std::string& identifier, std::vector<Named<Float_t*>> namedVariables);
35  void initialize();
36  void beginRun();
37  std::unique_ptr<MVA::Weightfile> getWeightFile();
38  double predict();
40  private:
42  std::vector<Named<Float_t*> > m_allNamedVariables;
43 
45  std::vector<Named<Float_t*> > m_selectedNamedVariables;
46 
48  std::unique_ptr<DBObjPtr<DatabaseRepresentationOfWeightfile> > m_weightfileRepresentation;
49 
51  std::unique_ptr<MVA::Expert> m_expert;
52 
54  std::unique_ptr<MVA::Dataset> m_dataset;
55 
57  std::string m_identifier;
58  };
59  }
61 }
62 
64 #include <mva/interface/Interface.h>
65 
66 #include <framework/utilities/FileSystem.h>
67 #include <framework/logging/Logger.h>
68 
69 #include <algorithm>
70 
71 using namespace Belle2;
72 using namespace TrackFindingCDC;
73 
74 MVAExpert::Impl::Impl(const std::string& identifier,
75  std::vector<Named<Float_t*> > namedVariables)
76  : m_allNamedVariables(std::move(namedVariables))
77  , m_identifier(identifier)
78 {
79 }
80 
82 {
84  using boost::algorithm::ends_with;
85  if (not m_weightfileRepresentation and
86  not(ends_with(m_identifier, ".root") or ends_with(m_identifier, ".xml"))) {
87  using DBWeightFileRepresentation = DBObjPtr<DatabaseRepresentationOfWeightfile>;
88  m_weightfileRepresentation = std::make_unique<DBWeightFileRepresentation>(m_identifier);
89  }
90 }
91 
93 {
94  std::unique_ptr<MVA::Weightfile> weightfile = getWeightFile();
95  if (weightfile) {
96  if (weightfile->getElement<std::string>("method") == "FastBDT" and
97  (weightfile->getElement<int>("FastBDT_version") == 1 or
98  weightfile->getElement<int>("FastBDT_version") == 2)) {
99 
100  int nExpectedVars = weightfile->getElement<int>("number_feature_variables");
101 
102  m_selectedNamedVariables.clear();
103  for (int iVar = 0; iVar < nExpectedVars; ++iVar) {
104  std::string variableElementName = "variable" + std::to_string(iVar);
105  std::string expectedName = weightfile->getElement<std::string>(variableElementName);
106  auto itNamedVariable = std::find_if(m_allNamedVariables.begin(),
107  m_allNamedVariables.end(),
108  [expectedName](const Named<Float_t*>& namedVariable) {
109  return namedVariable.getName() == expectedName;
110  });
111 
112  if (itNamedVariable == m_allNamedVariables.end()) {
113  B2ERROR("Variable name " << iVar << " mismatch for FastBDT. " <<
114  "Could not find expected variable '" << expectedName << "'");
115  }
116  m_selectedNamedVariables.push_back(*itNamedVariable);
117  }
118  B2ASSERT("Number of variables mismatch", nExpectedVars == static_cast<int>(m_selectedNamedVariables.size()));
119  } else {
120  B2WARNING("Unpacked new kind of classifier. Consider to extend the feature variable check. Identifier name: " << m_identifier
121  << "; method name: " << weightfile->getElement<std::string>("method"));
122  m_selectedNamedVariables = m_allNamedVariables;
123  }
124 
125  std::map<std::string, MVA::AbstractInterface*> supportedInterfaces =
127  MVA::GeneralOptions generalOptions;
128  weightfile->getOptions(generalOptions);
129  m_expert = supportedInterfaces[generalOptions.m_method]->getExpert();
130  m_expert->load(*weightfile);
131 
132  std::vector<float> dummy;
133  dummy.resize(m_selectedNamedVariables.size(), 0);
134  m_dataset = std::make_unique<MVA::SingleDataset>(generalOptions, std::move(dummy), 0);
135  } else {
136  B2ERROR("Could not find weight file for identifier " << m_identifier);
137  }
138 }
139 
140 std::unique_ptr<MVA::Weightfile> MVAExpert::Impl::getWeightFile()
141 {
142  if (m_weightfileRepresentation) {
143  std::stringstream ss((*m_weightfileRepresentation)->m_data);
144  return std::make_unique<MVA::Weightfile>(MVA::Weightfile::loadFromStream(ss));
145  } else {
146  std::string weightFilePath = FileSystem::findFile(m_identifier);
147  return std::make_unique<MVA::Weightfile>(MVA::Weightfile::loadFromFile(weightFilePath));
148  }
149 }
150 
152 {
153  if (not m_expert) {
154  B2ERROR("MVA Expert is not loaded! I will return 0");
155  return NAN;
156  }
157 
158  // Transfer the extracted values to the data set were the expert can find them
159  for (unsigned int i = 0; i < m_selectedNamedVariables.size(); ++i) {
160  m_dataset->m_input[i] = *m_selectedNamedVariables[i];
161  }
162  return m_expert->apply(*m_dataset)[0];
163 }
164 
166 // Silence Doxygen which is complaining that "no matching class member found for"
167 // But there should be a better way that I just don't know of / find
169 MVAExpert::MVAExpert(const std::string& identifier,
170  std::vector<Named<Float_t*> > namedVariables)
171  : m_impl(std::make_unique<MVAExpert::Impl>(identifier, std::move(namedVariables)))
173 {
174 }
175 
176 MVAExpert::~MVAExpert() = default;
177 
179 {
180  return m_impl->initialize();
181 }
182 
184 {
185  return m_impl->beginRun();
186 }
187 
189 {
190  return m_impl->predict();
191 }
Class for accessing objects in the database.
Definition: DBObjPtr.h:21
Database representation of a Weightfile object.
static std::string findFile(const std::string &path, bool silent=false)
Search for given file or directory in local or central release directory, and return absolute path if...
Definition: FileSystem.cc:148
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
std::string m_method
Name of the MVA method to use.
Definition: Options.h:82
virtual void load(const boost::property_tree::ptree &pt) override
Load mechanism (used by Weightfile) to load Options from a xml tree.
Definition: Options.cc:44
static Weightfile loadFromStream(std::istream &stream)
Static function which deserializes a Weightfile from a stream.
Definition: Weightfile.cc:251
static Weightfile loadFromFile(const std::string &filename)
Static function which loads a Weightfile from a file.
Definition: Weightfile.cc:206
Implementation of the class to interact with the MVA package.
Definition: MVAExpert.cc:31
void initialize()
Signal the beginning of the event processing.
Definition: MVAExpert.cc:81
void beginRun()
Called once before a new run begins.
Definition: MVAExpert.cc:92
Impl(const std::string &identifier, std::vector< Named< Float_t * >> namedVariables)
constructor
Definition: MVAExpert.cc:74
std::unique_ptr< DBObjPtr< DatabaseRepresentationOfWeightfile > > m_weightfileRepresentation
Database pointer to the Database representation of the weightfile.
Definition: MVAExpert.cc:48
std::unique_ptr< MVA::Weightfile > getWeightFile()
Get the weight file.
Definition: MVAExpert.cc:140
std::unique_ptr< MVA::Expert > m_expert
Pointer to the current MVA Expert.
Definition: MVAExpert.cc:51
std::vector< Named< Float_t * > > m_selectedNamedVariables
References to the selected named values from the source variable set.
Definition: MVAExpert.cc:45
std::unique_ptr< MVA::Dataset > m_dataset
Pointer to the current dataset.
Definition: MVAExpert.cc:54
std::vector< Named< Float_t * > > m_allNamedVariables
References to the all named values from the source variable set.
Definition: MVAExpert.cc:42
double predict()
Get the MVA prediction.
Definition: MVAExpert.cc:151
std::string m_identifier
DB identifier of the expert or file name.
Definition: MVAExpert.cc:57
Class to interact with the MVA package.
Definition: MVAExpert.h:26
void initialize()
Initialise the mva method.
Definition: MVAExpert.cc:178
MVAExpert(const std::string &identifier, std::vector< Named< Float_t * >> namedVariables)
Construct the Expert with the specified weight folder and the name of the training that was used in t...
void beginRun()
Update the mva method to the new run.
Definition: MVAExpert.cc:183
std::unique_ptr< Impl > m_impl
Pointer to implementation hiding the details.
Definition: MVAExpert.h:51
~MVAExpert()
Destructor must be defined in cpp because of PImpl pointer.
double predict()
Evaluate the MVA method and return the MVAOutput.
Definition: MVAExpert.cc:188
Filter based on a mva method.
Definition: MVAFilter.dcl.h:36
Abstract base class for different kinds of events.