MaCh3  2.2.3
Reference Guide
Classes | Functions
splines.cpp File Reference
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include "Splines/SplineBase.h"
#include "Splines/SplineMonolith.h"
#include "Splines/SplineStructs.h"
#include "Samples/SampleStructs.h"
#include "TSpline.h"
Include dependency graph for splines.cpp:

Go to the source code of this file.

Classes

class  PySplineBase
 EW: As SplineBase is an abstract base class we have to do some gymnastics to get it to get it into python. More...
 

Functions

void initSplines (py::module &m)
 

Function Documentation

◆ initSplines()

void initSplines ( py::module &  m)

Definition at line 72 of file splines.cpp.

72  {
73 
74  auto m_splines = m.def_submodule("splines");
75  m_splines.doc() =
76  "This is a Python binding of MaCh3s C++ based spline library.";
77 
78  // Bind the interpolation type enum that lets us set different interpolation types for our splines
79  py::enum_<SplineInterpolation>(m_splines, "InterpolationType")
80  .value("Linear", SplineInterpolation::kLinear, "Linear interpolation between the knots")
81  .value("Linear_Func", SplineInterpolation::kLinearFunc, "Same as 'Linear'")
82  .value("Cubic_TSpline3", SplineInterpolation::kTSpline3, "Use same coefficients as `ROOT's TSpline3 <https://root.cern.ch/doc/master/classTSpline3.html>`_ implementation")
83  .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.")
84  .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.")
85  .value("N_Interpolation_Types", SplineInterpolation::kSplineInterpolations, "This is only to be used when iterating and is not a valid interpolation type.");
86 
87 
88  py::class_<SplineBase, PySplineBase /* <--- trampoline*/>(m_splines, "SplineBase");
89 
90  py::class_<TResponseFunction_red>(m_splines, "_ResponseFunctionBase")
91  .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...";
92 
93  // Bind the TSpline3_red class. Decided to go with a clearer name of ResponseFunction for the python binding
94  // and make the interface a bit more python-y. Additionally remove passing root stuff so we don't need to deal
95  // with root python binding and can just pass it native python objects.
96  py::class_<TSpline3_red, TResponseFunction_red, std::unique_ptr<TSpline3_red, py::nodelete>>(m_splines, "ResponseFunction")
97  .def(
98  // define a more python friendly constructor that massages the inputs and passes them
99  // through to the c++ constructor
100  py::init
101  (
102  // Just take in some vectors, then build a TSpline3 and pass this to the constructor
103  [](std::vector<double> &xVals, std::vector<double> &yVals, SplineInterpolation interpType)
104  {
105  if ( xVals.size() != yVals.size() )
106  {
107  throw MaCh3Exception(__FILE__, __LINE__, "Different number of x values and y values!");
108  }
109 
110  int length = int(xVals.size());
111 
112  if (length == 1)
113  {
114  M3::float_t xKnot = M3::float_t(xVals[0]);
115  M3::float_t yKnot = M3::float_t(yVals[0]);
116 
117  std::vector<M3::float_t *> pars;
118  pars.resize(3);
119  pars[0] = new M3::float_t(0.0);
120  pars[1] = new M3::float_t(0.0);
121  pars[2] = new M3::float_t(0.0);
122  delete pars[0];
123  delete pars[1];
124  delete pars[2];
125 
126  return new TSpline3_red(&xKnot, &yKnot, 1, pars.data());
127  }
128 
129  TSpline3 *splineTmp = new TSpline3( "spline_tmp", xVals.data(), yVals.data(), length );
130  return new TSpline3_red(splineTmp, interpType);
131  }
132  )
133  )
134 
135  .def(
136  "find_segment",
138  "Find the segment that a particular *value* lies in. \n"
139  ":param value: The value to test",
140  py::arg("value")
141  )
142 
143  .def(
144  "evaluate",
146  "Evaluate the response function at a particular *value*. \n"
147  ":param value: The value to evaluate at.",
148  py::arg("value")
149  )
150  ; // End of binding for ResponseFunction
151 
152  py::class_<SMonolith, SplineBase>(m_splines, "EventSplineMonolith")
153  .def(
154  py::init(
155  [](std::vector<std::vector<TResponseFunction_red*>> &responseFns, const bool saveFlatTree)
156  {
157  std::vector<RespFuncType> respFnTypes;
158  for(uint i = 0; i < responseFns[0].size(); i++)
159  {
160  // ** WARNING **
161  // Right now I'm only pushing back TSpline3_reds as that's all that's supported right now
162  // In the future there might be more
163  // I think what would be best to do would be to store the interpolation type somehow in the ResponseFunction objects
164  // then just read them here and pass through to the constructor
165  respFnTypes.push_back(RespFuncType::kTSpline3_red);
166  }
167  return new SMonolith(responseFns, respFnTypes, saveFlatTree);
168  }
169  ),
170  "Create an EventSplineMonolith \n"
171  ":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"
172  ":param save_flat_tree: Whether we want to save monolith into speedy flat tree",
173  py::arg("master_splines"),
174  py::arg("save_flat_tree") = false
175  )
176 
177  .def(
178  py::init<std::string>(),
179  "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"
180  ":param file_name: The name of the file to read from.",
181  py::arg("file_name")
182  )
183 
184  .def(
185  "evaluate",
187  "Evaluate the splines at their current values."
188  )
189 
190  .def(
191  "sync_mem_transfer",
193  "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."
194  )
195 
196  .def(
197  "get_event_weight",
199  py::return_value_policy::reference,
200  "Get the weight of a particular event. \n"
201  ":param event: The index of the event whose weight you would like.",
202  py::arg("event")
203  )
204 
205  .def(
206  "set_param_value_array",
207  // Wrap up the setSplinePointers method so that we can take in a numpy array and get
208  // pointers to it's sweet sweet data and use those pointers in the splineMonolith
209  [](SMonolith &self, py::array_t<double, py::array::c_style> &array)
210  {
211  py::buffer_info bufInfo = array.request();
212 
213  if ( bufInfo.ndim != 1)
214  {
215  throw MaCh3Exception(__FILE__, __LINE__, "Number of dimensions in parameter array must be one!");
216  }
217 
218  if ( bufInfo.shape[0] != self.GetNParams() )
219  {
220  throw MaCh3Exception(__FILE__, __LINE__, "Number of entries in parameter array must equal the number of parameters!");
221  }
222 
223  std::vector<const double *> paramVec;
224  paramVec.resize(self.GetNParams());
225 
226  for( int idx = 0; idx < self.GetNParams(); idx++ )
227  {
228  // booooo pointer arithmetic
229  paramVec[idx] = array.data() + idx;
230  }
231 
232  self.setSplinePointers(paramVec);
233  },
234  "Set the array that the monolith should use to read parameter values from. \n"
235  "Usage of this might vary a bit from what you're used to in python. \n"
236  "Rather than just setting the values here, what you're really doing is setting pointers in the underlying c++ code. \n"
237  "What that means is that you pass an array to this function like:: \n"
238  "\n event_spline_monolith_instance.set_param_value_array(array) \n\n"
239  "Then when you set values in that array as normal, they will also be updated inside of the event_spline_monolith_instance.",
240  py::arg("array")
241 
242  )
243 
244  .doc() = "This 'monolith' deals with event by event weighting using splines."
245 
246  ; // End of binding for EventSplineMonolith
247 }
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.
Custom exception class for MaCh3 errors.
EW: As SplineBase is an abstract base class we have to do some gymnastics to get it to get it into py...
Definition: splines.cpp:19
Even-by-event class calculating response for spline parameters. It is possible to use GPU acceleratio...
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...
void SynchroniseMemTransfer()
KS: After calculations are done on GPU we copy memory to CPU. This operation is asynchronous meaning ...
const float * retPointer(const int event)
KS: Get pointer to total weight to make fit faster wrooom!
Base class for calculating weight from spline.
Definition: SplineBase.h:25
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.
double float_t
Definition: Core.h:30