Belle II Software  release-06-02-00
Python.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 #include <mva/methods/Python.h>
10 
11 #include <boost/filesystem/convenience.hpp>
12 #include <numpy/npy_common.h>
13 #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
14 #include <numpy/arrayobject.h>
15 
16 #include <framework/logging/Logger.h>
17 #include <framework/utilities/FileSystem.h>
18 #include <fstream>
19 
20 namespace Belle2 {
25  namespace MVA {
26 
27  void PythonOptions::load(const boost::property_tree::ptree& pt)
28  {
29  int version = pt.get<int>("Python_version");
30  if (version < 1 or version > 2) {
31  B2ERROR("Unknown weightfile version " << std::to_string(version));
32  throw std::runtime_error("Unknown weightfile version " + std::to_string(version));
33  }
34  m_framework = pt.get<std::string>("Python_framework");
35  m_steering_file = pt.get<std::string>("Python_steering_file");
36  m_mini_batch_size = pt.get<unsigned int>("Python_mini_batch_size");
37  m_nIterations = pt.get<unsigned int>("Python_n_iterations");
38  m_config = pt.get<std::string>("Python_config");
39  m_training_fraction = pt.get<double>("Python_training_fraction");
40  if (version == 2) {
41  m_normalize = pt.get<bool>("Python_normalize");
42  } else {
43  m_normalize = false;
44  }
45 
46  }
47 
48  void PythonOptions::save(boost::property_tree::ptree& pt) const
49  {
50  pt.put("Python_version", 2);
51  pt.put("Python_framework", m_framework);
52  pt.put("Python_steering_file", m_steering_file);
53  pt.put("Python_mini_batch_size", m_mini_batch_size);
54  pt.put("Python_n_iterations", m_nIterations);
55  pt.put("Python_config", m_config);
56  pt.put("Python_training_fraction", m_training_fraction);
57  pt.put("Python_normalize", m_normalize);
58  }
59 
60  po::options_description PythonOptions::getDescription()
61  {
62  po::options_description description("Python options");
63  description.add_options()
64  ("framework", po::value<std::string>(&m_framework),
65  "Framework which should be used. Currently supported are sklearn, tensorflow and theano")
66  ("steering_file", po::value<std::string>(&m_steering_file), "Steering file which describes")
67  ("mini_batch_size", po::value<unsigned int>(&m_mini_batch_size), "Size of the mini batch given to partial_fit function")
68  ("nIterations", po::value<unsigned int>(&m_nIterations), "Number of iterations")
69  ("normalize", po::value<bool>(&m_normalize), "Normalize input data (shift mean to 0 and std to 1)")
70  ("training_fraction", po::value<double>(&m_training_fraction),
71  "Training fraction used to split up dataset in training and validation sample.")
72  ("config", po::value<std::string>(&m_config), "Json encoded python object passed to begin_fit function");
73  return description;
74  }
75 
81 
82  public:
87 
92 
93  private:
98  {
99  if (not Py_IsInitialized()) {
100  Py_Initialize();
101  // wchar_t* bla[] = {L""};
102  wchar_t** bla = nullptr;
103  PySys_SetArgvEx(0, bla, 0);
104  m_initialized_python = true;
105  }
106 
107  if (PyArray_API == nullptr) {
108  init_numpy();
109  }
110  }
111 
116  {
117  if (m_initialized_python) {
118  if (Py_IsInitialized()) {
119  // We don't finalize Python because this call only frees some memory,
120  // but can cause crashes in loaded python-modules like Theano
121  // https://docs.python.org/3/c-api/init.html
122  // Py_Finalize();
123  }
124  }
125  }
126 
132  void* init_numpy()
133  {
134  // Import array is a macro which returns NUMPY_IMPORT_ARRAY_RETVAL
135  import_array();
136  return nullptr;
137  }
138 
139  bool m_initialized_python = false;
140  };
141 
143  {
144  static PythonInitializerSingleton singleton;
145  return singleton;
146  }
147 
148 
150  const PythonOptions& specific_options) : Teacher(general_options),
151  m_specific_options(specific_options)
152  {
154  }
155 
156 
158  {
159 
160  Weightfile weightfile;
161  std::string custom_weightfile = weightfile.generateFileName();
162  std::string custom_steeringfile = weightfile.generateFileName();
163 
164  uint64_t numberOfFeatures = training_data.getNumberOfFeatures();
165  uint64_t numberOfSpectators = training_data.getNumberOfSpectators();
166  uint64_t numberOfEvents = training_data.getNumberOfEvents();
167 
168  auto numberOfValidationEvents = static_cast<uint64_t>(numberOfEvents * (1 - m_specific_options.m_training_fraction));
169  auto numberOfTrainingEvents = static_cast<uint64_t>(numberOfEvents * m_specific_options.m_training_fraction);
170 
171  uint64_t batch_size = m_specific_options.m_mini_batch_size;
172  if (batch_size == 0) {
173  batch_size = numberOfTrainingEvents;
174  }
175 
177  B2ERROR("Please provide a positive training fraction");
178  throw std::runtime_error("Please provide a training fraction between (0.0,1.0]");
179  }
180 
181  auto X = std::unique_ptr<float[]>(new float[batch_size * numberOfFeatures]);
182  auto S = std::unique_ptr<float[]>(new float[batch_size * numberOfSpectators]);
183  auto y = std::unique_ptr<float[]>(new float[batch_size]);
184  auto w = std::unique_ptr<float[]>(new float[batch_size]);
185  npy_intp dimensions_X[2] = {static_cast<npy_intp>(batch_size), static_cast<npy_intp>(numberOfFeatures)};
186  npy_intp dimensions_S[2] = {static_cast<npy_intp>(batch_size), static_cast<npy_intp>(numberOfSpectators)};
187  npy_intp dimensions_y[2] = {static_cast<npy_intp>(batch_size), 1};
188  npy_intp dimensions_w[2] = {static_cast<npy_intp>(batch_size), 1};
189 
190  auto X_v = std::unique_ptr<float[]>(new float[numberOfValidationEvents * numberOfFeatures]);
191  auto S_v = std::unique_ptr<float[]>(new float[numberOfValidationEvents * numberOfSpectators]);
192  auto y_v = std::unique_ptr<float[]>(new float[numberOfValidationEvents]);
193  auto w_v = std::unique_ptr<float[]>(new float[numberOfValidationEvents]);
194  npy_intp dimensions_X_v[2] = {static_cast<npy_intp>(numberOfValidationEvents), static_cast<npy_intp>(numberOfFeatures)};
195  npy_intp dimensions_S_v[2] = {static_cast<npy_intp>(numberOfValidationEvents), static_cast<npy_intp>(numberOfSpectators)};
196  npy_intp dimensions_y_v[2] = {static_cast<npy_intp>(numberOfValidationEvents), 1};
197  npy_intp dimensions_w_v[2] = {static_cast<npy_intp>(numberOfValidationEvents), 1};
198 
199  std::string steering_file_source_code;
202  std::ifstream steering_file(filename);
203  if (not steering_file) {
204  throw std::runtime_error(std::string("Couldn't open file ") + filename);
205  }
206  steering_file.seekg(0, std::ios::end);
207  steering_file_source_code.resize(steering_file.tellg());
208  steering_file.seekg(0, std::ios::beg);
209  steering_file.read(&steering_file_source_code[0], steering_file_source_code.size());
210  }
211 
212  std::vector<float> means(numberOfFeatures, 0.0);
213  std::vector<float> stds(numberOfFeatures, 0.0);
214 
216  // Stable calculation of mean and variance with weights
217  // see https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
218  auto weights = training_data.getWeights();
219  for (uint64_t iFeature = 0; iFeature < numberOfFeatures; ++iFeature) {
220  double wSum = 0.0;
221  double wSum2 = 0.0;
222  double mean = 0.0;
223  double running_std = 0.0;
224  auto feature = training_data.getFeature(iFeature);
225  for (uint64_t i = 0; i < weights.size(); ++i) {
226  wSum += weights[i];
227  wSum2 += weights[i] * weights[i];
228  double meanOld = mean;
229  mean += (weights[i] / wSum) * (feature[i] - meanOld);
230  running_std += weights[i] * (feature[i] - meanOld) * (feature[i] - mean);
231  }
232  means[iFeature] = mean;
233  stds[iFeature] = std::sqrt(running_std / (wSum - 1));
234  }
235  }
236 
237  try {
238  // Load python modules
239  auto json = boost::python::import("json");
240  auto builtins = boost::python::import("builtins");
241  auto inspect = boost::python::import("inspect");
242 
243  // Load framework
244  auto framework = boost::python::import((std::string("basf2_mva_python_interface.") + m_specific_options.m_framework).c_str());
245  // Overwrite framework with user-defined code from the steering file
246  builtins.attr("exec")(steering_file_source_code.c_str(), boost::python::object(framework.attr("__dict__")));
247 
248  // Call get_model with the parameters provided by the user
249  auto parameters = json.attr("loads")(m_specific_options.m_config.c_str());
250  auto model = framework.attr("get_model")(numberOfFeatures, numberOfSpectators,
251  numberOfEvents, m_specific_options.m_training_fraction, parameters);
252 
253  // Call begin_fit with validation sample
254  for (uint64_t iEvent = 0; iEvent < numberOfValidationEvents; ++iEvent) {
255  training_data.loadEvent(iEvent);
257  for (uint64_t iFeature = 0; iFeature < numberOfFeatures; ++iFeature)
258  X_v[iEvent * numberOfFeatures + iFeature] = (training_data.m_input[iFeature] - means[iFeature]) / stds[iFeature];
259  } else {
260  for (uint64_t iFeature = 0; iFeature < numberOfFeatures; ++iFeature)
261  X_v[iEvent * numberOfFeatures + iFeature] = training_data.m_input[iFeature];
262  }
263  for (uint64_t iSpectator = 0; iSpectator < numberOfSpectators; ++iSpectator)
264  S_v[iEvent * numberOfSpectators + iSpectator] = training_data.m_spectators[iSpectator];
265  y_v[iEvent] = training_data.m_target;
266  w_v[iEvent] = training_data.m_weight;
267  }
268 
269  auto ndarray_X_v = boost::python::handle<>(PyArray_SimpleNewFromData(2, dimensions_X_v, NPY_FLOAT32, X_v.get()));
270  auto ndarray_S_v = boost::python::handle<>(PyArray_SimpleNewFromData(2, dimensions_S_v, NPY_FLOAT32, S_v.get()));
271  auto ndarray_y_v = boost::python::handle<>(PyArray_SimpleNewFromData(2, dimensions_y_v, NPY_FLOAT32, y_v.get()));
272  auto ndarray_w_v = boost::python::handle<>(PyArray_SimpleNewFromData(2, dimensions_w_v, NPY_FLOAT32, w_v.get()));
273 
274  auto state = framework.attr("begin_fit")(model, ndarray_X_v, ndarray_S_v, ndarray_y_v, ndarray_w_v);
275 
276  uint64_t nBatches = std::floor(numberOfTrainingEvents / batch_size);
277  bool continue_loop = true;
278  for (uint64_t iIteration = 0; (iIteration < m_specific_options.m_nIterations or m_specific_options.m_nIterations == 0)
279  and continue_loop; ++iIteration) {
280  for (uint64_t iBatch = 0; iBatch < nBatches and continue_loop; ++iBatch) {
281 
282  // Release Global Interpreter Lock in python to allow multithreading while reading root files
283  // also see: https://docs.python.org/3.5/c-api/init.html
284  PyThreadState* m_thread_state = PyEval_SaveThread();
285  for (uint64_t iEvent = 0; iEvent < batch_size; ++iEvent) {
286  training_data.loadEvent(iEvent + iBatch * batch_size + numberOfValidationEvents);
288  for (uint64_t iFeature = 0; iFeature < numberOfFeatures; ++iFeature)
289  X[iEvent * numberOfFeatures + iFeature] = (training_data.m_input[iFeature] - means[iFeature]) / stds[iFeature];
290  } else {
291  for (uint64_t iFeature = 0; iFeature < numberOfFeatures; ++iFeature)
292  X[iEvent * numberOfFeatures + iFeature] = training_data.m_input[iFeature];
293  }
294  for (uint64_t iSpectator = 0; iSpectator < numberOfSpectators; ++iSpectator)
295  S[iEvent * numberOfSpectators + iSpectator] = training_data.m_spectators[iSpectator];
296  y[iEvent] = training_data.m_target;
297  w[iEvent] = training_data.m_weight;
298  }
299 
300  // Maybe slow, create ndarrays outside of loop?
301  auto ndarray_X = boost::python::handle<>(PyArray_SimpleNewFromData(2, dimensions_X, NPY_FLOAT32, X.get()));
302  auto ndarray_S = boost::python::handle<>(PyArray_SimpleNewFromData(2, dimensions_S, NPY_FLOAT32, S.get()));
303  auto ndarray_y = boost::python::handle<>(PyArray_SimpleNewFromData(2, dimensions_y, NPY_FLOAT32, y.get()));
304  auto ndarray_w = boost::python::handle<>(PyArray_SimpleNewFromData(2, dimensions_w, NPY_FLOAT32, w.get()));
305 
306  // Reactivate Global Interpreter Lock to safely execute python code
307  PyEval_RestoreThread(m_thread_state);
308  auto r = framework.attr("partial_fit")(state, ndarray_X, ndarray_S, ndarray_y,
309  ndarray_w, iIteration * nBatches + iBatch);
310  boost::python::extract<bool> proxy(r);
311  if (proxy.check())
312  continue_loop = static_cast<bool>(proxy);
313  }
314  }
315 
316  auto result = framework.attr("end_fit")(state);
317 
318  auto pickle = boost::python::import("pickle");
319  auto file = builtins.attr("open")(custom_weightfile.c_str(), "wb");
320  pickle.attr("dump")(result, file);
321 
322  auto steeringfile = builtins.attr("open")(custom_steeringfile.c_str(), "wb");
323  pickle.attr("dump")(steering_file_source_code.c_str(), steeringfile);
324 
325  auto importances = framework.attr("feature_importance")(state);
326  if (len(importances) == 0) {
327  B2INFO("Python method returned empty feature importance. There won't be any information about the feature importance in the weightfile.");
328  } else if (numberOfFeatures != static_cast<uint64_t>(len(importances))) {
329  B2WARNING("Python method didn't return the correct number of importance value. I ignore the importances");
330  } else {
331  std::map<std::string, float> feature_importances;
332  for (uint64_t iFeature = 0; iFeature < numberOfFeatures; ++iFeature) {
333  boost::python::extract<float> proxy(importances[iFeature]);
334  if (proxy.check()) {
335  feature_importances[m_general_options.m_variables[iFeature]] = static_cast<float>(proxy);
336  } else {
337  B2WARNING("Failed to convert importance output of the method to a float, using 0 instead");
338  feature_importances[m_general_options.m_variables[iFeature]] = 0.0;
339  }
340  }
341  weightfile.addFeatureImportance(feature_importances);
342  }
343 
344  } catch (...) {
345  PyErr_Print();
346  PyErr_Clear();
347  B2ERROR("Failed calling train in PythonTeacher");
348  throw std::runtime_error(std::string("Failed calling train in PythonTeacher"));
349  }
350 
351  weightfile.addOptions(m_general_options);
352  weightfile.addOptions(m_specific_options);
353  weightfile.addFile("Python_Weightfile", custom_weightfile);
354  weightfile.addFile("Python_Steeringfile", custom_steeringfile);
355  weightfile.addSignalFraction(training_data.getSignalFraction());
357  weightfile.addVector("Python_Means", means);
358  weightfile.addVector("Python_Stds", stds);
359  }
360 
361  return weightfile;
362 
363  }
364 
366  {
368  }
369 
370 
371  void PythonExpert::load(Weightfile& weightfile)
372  {
373 
374  std::string custom_weightfile = weightfile.generateFileName();
375  weightfile.getFile("Python_Weightfile", custom_weightfile);
376  weightfile.getOptions(m_general_options);
377  weightfile.getOptions(m_specific_options);
378 
380  m_means = weightfile.getVector<float>("Python_Means");
381  m_stds = weightfile.getVector<float>("Python_Stds");
382  }
383 
384  try {
385  auto pickle = boost::python::import("pickle");
386  auto builtins = boost::python::import("builtins");
387  m_framework = boost::python::import((std::string("basf2_mva_python_interface.") + m_specific_options.m_framework).c_str());
388 
389  if (weightfile.containsElement("Python_Steeringfile")) {
390  std::string custom_steeringfile = weightfile.generateFileName();
391  weightfile.getFile("Python_Steeringfile", custom_steeringfile);
392  auto steeringfile = builtins.attr("open")(custom_steeringfile.c_str(), "rb");
393  auto source_code = pickle.attr("load")(steeringfile);
394  builtins.attr("exec")(boost::python::object(source_code), boost::python::object(m_framework.attr("__dict__")));
395  }
396 
397  auto file = builtins.attr("open")(custom_weightfile.c_str(), "rb");
398  auto unpickled_fit_object = pickle.attr("load")(file);
399  m_state = m_framework.attr("load")(unpickled_fit_object);
400  } catch (...) {
401  PyErr_Print();
402  PyErr_Clear();
403  B2ERROR("Failed calling load in PythonExpert");
404  throw std::runtime_error("Failed calling load in PythonExpert");
405  }
406 
407  }
408 
409  std::vector<float> PythonExpert::apply(Dataset& test_data) const
410  {
411 
412  uint64_t numberOfFeatures = test_data.getNumberOfFeatures();
413  uint64_t numberOfEvents = test_data.getNumberOfEvents();
414 
415  auto X = std::unique_ptr<float[]>(new float[numberOfEvents * numberOfFeatures]);
416  npy_intp dimensions_X[2] = {static_cast<npy_intp>(numberOfEvents), static_cast<npy_intp>(numberOfFeatures)};
417 
418  for (uint64_t iEvent = 0; iEvent < numberOfEvents; ++iEvent) {
419  test_data.loadEvent(iEvent);
421  for (uint64_t iFeature = 0; iFeature < numberOfFeatures; ++iFeature)
422  X[iEvent * numberOfFeatures + iFeature] = (test_data.m_input[iFeature] - m_means[iFeature]) / m_stds[iFeature];
423  } else {
424  for (uint64_t iFeature = 0; iFeature < numberOfFeatures; ++iFeature)
425  X[iEvent * numberOfFeatures + iFeature] = test_data.m_input[iFeature];
426  }
427  }
428 
429  std::vector<float> probabilities(test_data.getNumberOfEvents());
430 
431  try {
432  auto ndarray_X = boost::python::handle<>(PyArray_SimpleNewFromData(2, dimensions_X, NPY_FLOAT32, X.get()));
433  auto result = m_framework.attr("apply")(m_state, ndarray_X);
434  for (uint64_t iEvent = 0; iEvent < numberOfEvents; ++iEvent) {
435  // We have to do some nasty casting here, because the Python C-Api uses structs which are binary compatible
436  // to a PyObject but do not inherit from it!
437  probabilities[iEvent] = static_cast<float>(*static_cast<float*>(PyArray_GETPTR1(reinterpret_cast<PyArrayObject*>(result.ptr()),
438  iEvent)));
439  }
440  } catch (...) {
441  PyErr_Print();
442  PyErr_Clear();
443  B2ERROR("Failed calling applying PythonExpert");
444  throw std::runtime_error("Failed calling applying PythonExpert");
445  }
446 
447  return probabilities;
448  }
449  }
451 }
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:145
Abstract base class of all Datasets given to the MVA interface The current event can always be access...
Definition: Dataset.h:31
GeneralOptions m_general_options
General options loaded from the weightfile.
Definition: Expert.h:69
General options which are shared by all MVA trainings.
Definition: Options.h:62
std::vector< std::string > m_variables
Vector of all variables (branch names) used in the training.
Definition: Options.h:86
PythonExpert()
Constructs a new Python Expert.
Definition: Python.cc:365
boost::python::object m_state
current state object of method
Definition: Python.h:135
std::vector< float > m_stds
Stds of all features for normalization.
Definition: Python.h:137
boost::python::object m_framework
Framework module.
Definition: Python.h:134
virtual std::vector< float > apply(Dataset &test_data) const override
Apply this expert onto a dataset.
Definition: Python.cc:409
PythonOptions m_specific_options
Method specific options.
Definition: Python.h:133
virtual void load(Weightfile &weightfile) override
Load the expert from a Weightfile.
Definition: Python.cc:371
std::vector< float > m_means
Means of all features for normalization.
Definition: Python.h:136
Singleton class which handles the initialization and finalization of Python and numpy.
Definition: Python.cc:80
void * init_numpy()
Helper function which initializes array system of numpy.
Definition: Python.cc:132
~PythonInitializerSingleton()
Destructor of PythonInitializerSingleton.
Definition: Python.cc:115
bool m_initialized_python
Member which keeps indicate if this class initialized python.
Definition: Python.cc:139
static PythonInitializerSingleton & GetInstance()
Return static instance of PythonInitializerSingleton.
Definition: Python.cc:142
PythonInitializerSingleton()
Constructor of PythonInitializerSingleton.
Definition: Python.cc:97
PythonInitializerSingleton(const PythonInitializerSingleton &)=delete
Forbid copy constructor of PythonInitializerSingleton.
Options for the Python MVA method.
Definition: Python.h:51
unsigned int m_nIterations
Number of iterations through the whole data.
Definition: Python.h:80
std::string m_steering_file
steering file provided by the user to override the functions in the framework
Definition: Python.h:77
std::string m_framework
framework to use e.g.
Definition: Python.h:76
std::string m_config
Config string in json, which is passed to the get model function.
Definition: Python.h:78
virtual po::options_description getDescription() override
Returns a program options description for all available options.
Definition: Python.cc:60
bool m_normalize
Normalize the inputs (shift mean to zero and std to 1)
Definition: Python.h:82
double m_training_fraction
Fraction of data passed as training data, rest is passed as test data.
Definition: Python.h:81
virtual void load(const boost::property_tree::ptree &pt) override
Load mechanism to load Options from a xml tree.
Definition: Python.cc:27
virtual void save(boost::property_tree::ptree &pt) const override
Save mechanism to store Options in a xml tree.
Definition: Python.cc:48
unsigned int m_mini_batch_size
Mini batch size, 0 passes the whole data in one call.
Definition: Python.h:79
PythonTeacher(const GeneralOptions &general_options, const PythonOptions &specific_options)
Constructs a new teacher using the GeneralOptions and specific options of this training.
Definition: Python.cc:149
PythonOptions m_specific_options
Method specific options.
Definition: Python.h:106
virtual Weightfile train(Dataset &training_data) const override
Train a mva method using the given dataset returning a Weightfile.
Definition: Python.cc:157
Abstract base class of all Teachers Each MVA library has its own implementation of this class,...
Definition: Teacher.h:29
GeneralOptions m_general_options
GeneralOptions containing all shared options.
Definition: Teacher.h:49
The Weightfile class serializes all information about a training into an xml tree.
Definition: Weightfile.h:38
void addFile(const std::string &identifier, const std::string &custom_weightfile)
Add a file (mostly a weightfile from a MVA library) to our Weightfile.
Definition: Weightfile.cc:114
bool containsElement(const std::string &identifier) const
Returns true if given element is stored in the property tree.
Definition: Weightfile.h:160
void addOptions(const Options &options)
Add an Option object to the xml tree.
Definition: Weightfile.cc:61
std::vector< T > getVector(const std::string &identifier) const
Returns a stored vector from the xml tree.
Definition: Weightfile.h:181
void getOptions(Options &options) const
Fills an Option object from the xml tree.
Definition: Weightfile.cc:66
void addSignalFraction(float signal_fraction)
Saves the signal fraction in the xml tree.
Definition: Weightfile.cc:94
void addFeatureImportance(const std::map< std::string, float > &importance)
Add variable importance.
Definition: Weightfile.cc:71
void addVector(const std::string &identifier, const std::vector< T > &vector)
Add a vector to the xml tree.
Definition: Weightfile.h:125
std::string generateFileName(const std::string &suffix="")
Returns a temporary filename with the given suffix.
Definition: Weightfile.cc:104
void getFile(const std::string &identifier, const std::string &custom_weightfile)
Creates a file from our weightfile (mostly this will be a weightfile of an MVA library)
Definition: Weightfile.cc:137
Abstract base class for different kinds of events.