MaCh3  2.5.0
Reference Guide
splines.h
Go to the documentation of this file.
1 #pragma once
2 
5 
6 // pybind includes
7 #include <pybind11/pybind11.h>
8 #include <pybind11/stl.h>
9 #include <pybind11/numpy.h>
10 // MaCh3 includes
11 #include "Splines/SplineBase.h"
13 #include "Splines/SplineStructs.h"
14 #include "Samples/SampleStructs.h" // <- The spline stuff that's in here should really be moved to splineStructs.h but I ain't doing that right now
15 // ROOT includes
16 #include "TSpline.h"
17 
18 #pragma GCC diagnostic ignored "-Wuseless-cast"
19 #pragma GCC diagnostic ignored "-Wfloat-conversion"
20 
21 namespace py = pybind11;
22 
24 class PySplineBase : public SplineBase {
25 public:
26  /* Inherit the constructors */
28 
29  /* Trampoline (need one for each virtual function) */
30  void Evaluate() override {
31  PYBIND11_OVERRIDE_PURE_NAME(
32  void, /* Return type */
33  SplineBase, /* Parent class */
34  "evaluate", /* Name in python*/
35  Evaluate /* Name of function in C++ (must match Python name) */
36  );
37  }
38 
39  std::string GetName() const override {
40  PYBIND11_OVERRIDE_NAME(
41  std::string, /* Return type */
42  SplineBase, /* Parent class */
43  "get_name", /* Name in python*/
44  GetName /* Name of function in C++ (must match Python name) */
45  );
46  }
47 
49  PYBIND11_OVERRIDE_PURE_NAME(
50  void, /* Return type */
51  SplineBase, /* Parent class */
52  "find_segment", /* Name in python*/
53  FindSplineSegment /* Name of function in C++ (must match Python name) */
54  );
55  }
56 
57  void CalcSplineWeights() override {
58  PYBIND11_OVERRIDE_PURE_NAME(
59  void, /* Return type */
60  SplineBase, /* Parent class */
61  "calculate_weights", /* Name in python*/
62  CalcSplineWeights /* Name of function in C++ (must match Python name) */
63  );
64  }
65 };
66 
67 
68 void initSplinesModule(py::module &m_splines){
69 
70  // Bind the interpolation type enum that lets us set different interpolation types for our splines
71  py::enum_<SplineInterpolation>(m_splines, "InterpolationType")
72  .value("Linear", SplineInterpolation::kLinear, "Linear interpolation between the knots")
73  .value("Linear_Func", SplineInterpolation::kLinearFunc, "Same as 'Linear'")
74  .value("Cubic_TSpline3", SplineInterpolation::kTSpline3, "Use same coefficients as `ROOT's TSpline3 <https://root.cern.ch/doc/master/classTSpline3.html>`_ implementation")
75  .value("Cubic_Monotonic", SplineInterpolation::kMonotonic, "Coefficients are calculated such that the segments between knots are forced to be monotonic. The implementation we use is based on `this method <https://www.jstor.org/stable/2156610>`_ by Fritsch and Carlson.")
76  .value("Cubic_Akima", SplineInterpolation::kAkima, "The second derivative is not required to be continuous at the knots. This means that these splines are useful if the second derivative is rapidly varying. The implementation we used is based on `this paper <http://www.leg.ufpr.br/lib/exe/fetch.php/wiki:internas:biblioteca:akima.pdf>`_ by Akima.")
77  .value("N_Interpolation_Types", SplineInterpolation::kSplineInterpolations, "This is only to be used when iterating and is not a valid interpolation type.");
78 
79 
80  py::class_<SplineBase, PySplineBase /* <--- trampoline*/>(m_splines, "SplineBase");
81 
82  py::class_<TResponseFunction_red>(m_splines, "_ResponseFunctionBase")
83  .doc() = "Base class of the response function, this binding only exists for consistency with the inheritance structure of the c++ code. Just pretend it doesn't exist and don't worry about it...";
84 
85  // Bind the TSpline3_red class. Decided to go with a clearer name of ResponseFunction for the python binding
86  // and make the interface a bit more python-y. Additionally remove passing root stuff so we don't need to deal
87  // with root python binding and can just pass it native python objects.
88  py::class_<TSpline3_red, TResponseFunction_red, std::unique_ptr<TSpline3_red, py::nodelete>>(m_splines, "ResponseFunction")
89  .def(
90  // define a more python friendly constructor that massages the inputs and passes them
91  // through to the c++ constructor
92  py::init
93  (
94  // Just take in some vectors, then build a TSpline3 and pass this to the constructor
95  [](std::vector<double> &xVals, std::vector<double> &yVals, SplineInterpolation interpType)
96  {
97  if ( xVals.size() != yVals.size() )
98  {
99  throw MaCh3Exception(__FILE__, __LINE__, "Different number of x values and y values!");
100  }
101 
102  int length = int(xVals.size());
103 
104  if (length == 1)
105  {
106  M3::float_t xKnot = M3::float_t(xVals[0]);
107  M3::float_t yKnot = M3::float_t(yVals[0]);
108 
109  std::vector<M3::float_t *> pars;
110  pars.resize(3);
111  pars[0] = new M3::float_t(0.0);
112  pars[1] = new M3::float_t(0.0);
113  pars[2] = new M3::float_t(0.0);
114  delete pars[0];
115  delete pars[1];
116  delete pars[2];
117 
118  return new TSpline3_red(&xKnot, &yKnot, 1, pars.data());
119  }
120 
121  TSpline3 *splineTmp = new TSpline3( "spline_tmp", xVals.data(), yVals.data(), length );
122  return new TSpline3_red(splineTmp, interpType);
123  }
124  )
125  )
126 
127  .def(
128  "find_segment",
130  "Find the segment that a particular *value* lies in. \n"
131  ":param value: The value to test",
132  py::arg("value")
133  )
134 
135  .def(
136  "evaluate",
138  "Evaluate the response function at a particular *value*. \n"
139  ":param value: The value to evaluate at.",
140  py::arg("value")
141  )
142  ; // End of binding for ResponseFunction
143 
144  py::class_<UnbinnedSplineHandler, SplineBase>(m_splines, "EventSplineMonolith")
145  .def(
146  py::init(
147  [](std::vector<std::vector<TResponseFunction_red*>> &responseFns, const bool saveFlatTree)
148  {
149  std::vector<RespFuncType> respFnTypes;
150  for(uint i = 0; i < responseFns[0].size(); i++)
151  {
152  // ** WARNING **
153  // Right now I'm only pushing back TSpline3_reds as that's all that's supported right now
154  // In the future there might be more
155  // I think what would be best to do would be to store the interpolation type somehow in the ResponseFunction objects
156  // then just read them here and pass through to the constructor
157  respFnTypes.push_back(RespFuncType::kTSpline3_red);
158  }
159  return new UnbinnedSplineHandler(responseFns, respFnTypes, saveFlatTree);
160  }
161  ),
162  "Create an EventSplineMonolith \n"
163  ":param master_splines: These are the 'knot' values to make splines from. This should be an P x E 2D list where P is the number of parameters and E is the number of events. \n"
164  ":param save_flat_tree: Whether we want to save monolith into speedy flat tree",
165  py::arg("master_splines"),
166  py::arg("save_flat_tree") = false
167  )
168 
169  .def(
170  py::init<std::string>(),
171  "Constructor where you pass path to preprocessed root FileName which is generated by creating an EventSplineMonolith with the `save_flat_tree` flag set to True. \n"
172  ":param file_name: The name of the file to read from.",
173  py::arg("file_name")
174  )
175 
176  .def(
177  "evaluate",
179  "Evaluate the splines at their current values."
180  )
181 
182  .def(
183  "sync_mem_transfer",
185  "This is important when running on GPU. After calculations are done on GPU we copy memory to CPU. This operation is asynchronous meaning while memory is being copied some operations are being carried. Memory must be copied before actual reweight. This function make sure all has been copied."
186  )
187 
188  .def(
189  "get_event_weight",
191  py::return_value_policy::reference,
192  "Get the weight of a particular event. \n"
193  ":param event: The index of the event whose weight you would like.",
194  py::arg("event")
195  )
196 
197  .def(
198  "set_param_value_array",
199  // Wrap up the setSplinePointers method so that we can take in a numpy array and get
200  // pointers to it's sweet sweet data and use those pointers in the splineMonolith
201  [](UnbinnedSplineHandler &self, py::array_t<M3::float_t, py::array::c_style> &array)
202  {
203  py::buffer_info bufInfo = array.request();
204 
205  if ( bufInfo.ndim != 1)
206  {
207  throw MaCh3Exception(__FILE__, __LINE__, "Number of dimensions in parameter array must be one!");
208  }
209 
210  if ( bufInfo.shape[0] != self.GetNParams() )
211  {
212  throw MaCh3Exception(__FILE__, __LINE__, "Number of entries in parameter array must equal the number of parameters!");
213  }
214 
215  std::vector<const M3::float_t *> paramVec;
216  paramVec.resize(self.GetNParams());
217 
218  for( int idx = 0; idx < self.GetNParams(); idx++ )
219  {
220  // booooo pointer arithmetic
221  paramVec[idx] = array.data() + idx;
222  }
223 
224  self.setSplinePointers(paramVec);
225  },
226  "Set the array that the monolith should use to read parameter values from. \n"
227  "Usage of this might vary a bit from what you're used to in python. \n"
228  "Rather than just setting the values here, what you're really doing is setting pointers in the underlying c++ code. \n"
229  "What that means is that you pass an array to this function like:: \n"
230  "\n event_spline_monolith_instance.set_param_value_array(array) \n\n"
231  "Then when you set values in that array as normal, they will also be updated inside of the event_spline_monolith_instance.",
232  py::arg("array")
233 
234  )
235 
236  .doc() = "This 'monolith' deals with event by event weighting using splines."
237 
238  ; // End of binding for EventSplineMonolith
239 }
SplineInterpolation
Make an enum of the spline interpolation type.
@ kTSpline3
Default TSpline3 interpolation.
@ kMonotonic
EM: DOES NOT make the entire spline monotonic, only the segments.
@ kSplineInterpolations
This only enumerates.
@ kLinear
Linear interpolation between knots.
@ kLinearFunc
Liner interpolation using TF1 not spline.
@ kAkima
EM: Akima spline iis allowed to be discontinuous in 2nd derivative and coefficients in any segment.
@ kTSpline3_red
Uses TSpline3_red for interpolation.
Contains structures and helper functions for handling spline representations of systematic parameters...
Custom exception class used throughout MaCh3.
EW: As SplineBase is an abstract base class we have to do some gymnastics to get it to get it into py...
Definition: splines.h:24
std::string GetName() const override
Get class name.
Definition: splines.h:39
void FindSplineSegment()
Definition: splines.h:48
void CalcSplineWeights() override
CPU based code which eval weight for each spline.
Definition: splines.h:57
void Evaluate() override
CW: This Eval should be used when using two separate x,{y,a,b,c,d} arrays to store the weights; proba...
Definition: splines.h:30
Base class for calculating weight from spline.
Definition: SplineBase.h:27
SplineBase()
Constructor.
Definition: SplineBase.cpp:7
CW: Reduced TSpline3 class.
double Eval(double var) override
CW: Evaluate the weight from a variation.
int FindX(double x)
Find the segment relevant to this variation in x.
Even-by-event class calculating response for spline parameters. It is possible to use GPU acceleratio...
void Evaluate() final
CW: This Eval should be used when using two separate x,{y,a,b,c,d} arrays to store the weights; proba...
void SynchroniseMemTransfer() const final
KS: After calculations are done on GPU we copy memory to CPU. This operation is asynchronous meaning ...
const M3::float_t * RetPointer(const int event) const
KS: Get pointer to total weight to make fit faster wrooom!
double float_t
Definition: Core.h:37
void initSplinesModule(py::module &m_splines)
Definition: splines.h:68