Mantid
Loading...
Searching...
No Matches
Statistics.cpp
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
12
13#include <boost/python/class.hpp>
14#include <boost/python/def.hpp>
15#include <boost/python/overloads.hpp>
16#include <boost/python/return_value_policy.hpp>
17#include <boost/python/scope.hpp>
18
19// See
20// http://docs.scipy.org/doc/numpy/reference/c-api.array.html#PY_ARRAY_UNIQUE_SYMBOL
21#define PY_ARRAY_UNIQUE_SYMBOL KERNEL_ARRAY_API
22#define NO_IMPORT_ARRAY
23#include <numpy/arrayobject.h>
24
26using namespace Mantid::PythonInterface;
27using namespace boost::python;
28
29namespace {
31
32// Dummy class used to define Stats "namespace" in python
33class Stats {};
34
35// For all methods below we have to extract specific types from Python to C++.
36// We choose to support only Python float arrays (C++ double)
37
44bool isFloatArray(PyObject *obj) {
45#if NPY_API_VERSION >= 0x00000007 // 1.7
46 return PyArray_ISFLOAT((const PyArrayObject *)obj);
47#else
48 return PyArray_ISFLOAT((PyArrayObject *)obj);
49#endif
50}
51
60bool typesEqual(PyObject *first, PyObject *second) {
61#if NPY_API_VERSION >= 0x00000007 // 1.7
62 const auto *firstArray = reinterpret_cast<const PyArrayObject *>(first);
63 const auto *secondArray = reinterpret_cast<const PyArrayObject *>(second);
64#else
65 PyArrayObject *firstArray = (PyArrayObject *)first;
66 PyArrayObject *secondArray = (PyArrayObject *)second;
67#endif
68 return PyArray_TYPE(firstArray) != PyArray_TYPE(secondArray);
69}
70
72class UnknownDataType : public std::invalid_argument {
73public:
74 UnknownDataType()
75 : std::invalid_argument("Unknown datatype. Currently only arrays of "
76 "Python floats are supported ") {}
77};
78
79//============================ getStatistics
80//============================================
81
88Statistics getStatisticsNumpy(const NDArray &data, const bool sorted = false) {
92
93 if (isFloatArray(data.ptr())) {
94 unsigned int flags = StatOptions::AllStats;
95 if (sorted)
97 return getStatistics(NDArrayToVector<double>(data)(), flags);
98 } else {
99 throw UnknownDataType();
100 }
101}
102
103GNU_DIAG_OFF("unused-local-typedef")
104// Ignore -Wconversion warnings coming from boost::python
105// Seen with GCC 7.1.1 and Boost 1.63.0
106GNU_DIAG_OFF("conversion")
107
108// Define an overload to handle the default argument
109// cppcheck-suppress unknownMacro
110BOOST_PYTHON_FUNCTION_OVERLOADS(getStatisticsOverloads, getStatisticsNumpy, 1, 2)
111GNU_DIAG_ON("conversion")
112GNU_DIAG_ON("unused-local-typedef")
113//============================ Z score
114//============================================
115
116
121std::vector<double> getZscoreNumpy(const NDArray &data) {
124
125 if (isFloatArray(data.ptr())) {
126 return getZscore(NDArrayToVector<double>(data)());
127 } else {
128 throw UnknownDataType();
129 }
130}
131
137std::vector<double> getZscoreNumpyDeprecated(const NDArray &data, const bool sorted) {
138 UNUSED_ARG(sorted);
139 if (PyErr_Warn(PyExc_DeprecationWarning, "getZScore no longer requires the second sorted argument.") < 0)
140 throw boost::python::error_already_set();
141 return getZscoreNumpy(data);
142}
143
148std::vector<double> getModifiedZscoreNumpy(const NDArray &data, const bool sorted = false) {
149 UNUSED_ARG(sorted); // We explicitly check in the kernel now
152
153 if (isFloatArray(data.ptr())) {
154 return getModifiedZscore(NDArrayToVector<double>(data)());
155 } else {
156 throw UnknownDataType();
157 }
158}
159
160GNU_DIAG_OFF("unused-local-typedef")
161// Ignore -Wconversion warnings coming from boost::python
162// Seen with GCC 7.1.1 and Boost 1.63.0
163GNU_DIAG_OFF("conversion")
164
165// Define an overload to handle the default argument
166BOOST_PYTHON_FUNCTION_OVERLOADS(getModifiedZscoreOverloads, getModifiedZscoreNumpy, 1, 2)
167GNU_DIAG_ON("conversion")
168GNU_DIAG_ON("unused-local-typedef")
169
170//============================ getMoments
171//============================================
172
173// Function pointer to real implementation of getMoments
174using MomentsFunction = std::vector<double> (*)(const std::vector<double> &, const std::vector<double> &, const int);
175
187std::vector<double> getMomentsNumpyImpl(MomentsFunction momentsFunc, const NDArray &indep, const NDArray &depend,
188 const int maxMoment) {
190
191 // Both input arrays must have the same typed data
192 if (typesEqual(indep.ptr(), depend.ptr())) {
193 throw std::invalid_argument("Datatypes of input arrays must match.");
194 }
195
196 if (isFloatArray(indep.ptr()) && isFloatArray(indep.ptr())) {
197 return momentsFunc(NDArrayToVector<double>(indep)(), NDArrayToVector<double>(depend)(), maxMoment);
198 } else {
199 throw UnknownDataType();
200 }
201}
202
207std::vector<double> getMomentsAboutOriginNumpy(const NDArray &indep, const NDArray &depend, const int maxMoment = 3) {
209 return getMomentsNumpyImpl(&getMomentsAboutOrigin, indep, depend, maxMoment);
210}
211
212GNU_DIAG_OFF("unused-local-typedef")
213// Ignore -Wconversion warnings coming from boost::python
214// Seen with GCC 7.1.1 and Boost 1.63.0
215GNU_DIAG_OFF("conversion")
216// Define an overload to handle the default argument
217BOOST_PYTHON_FUNCTION_OVERLOADS(getMomentsAboutOriginOverloads, getMomentsAboutOriginNumpy, 2, 3)
218GNU_DIAG_ON("conversion")
219GNU_DIAG_ON("unused-local-typedef")
224std::vector<double> getMomentsAboutMeanNumpy(const NDArray &indep, NDArray &depend, const int maxMoment = 3) {
226 return getMomentsNumpyImpl(&getMomentsAboutMean, indep, depend, maxMoment);
227}
228
229GNU_DIAG_OFF("unused-local-typedef")
230// Ignore -Wconversion warnings coming from boost::python
231// Seen with GCC 7.1.1 and Boost 1.63.0
232GNU_DIAG_OFF("conversion")
233// Define an overload to handle the default argument
234BOOST_PYTHON_FUNCTION_OVERLOADS(getMomentsAboutMeanOverloads, getMomentsAboutMeanNumpy, 2, 3)
235GNU_DIAG_ON("conversion")
236GNU_DIAG_ON("unused-local-typedef")
237
238
239} // namespace
240
241// -------------------------------------- Exports start here
242// --------------------------------------
243
245 // typedef std::vector --> numpy array result converter
246 using ReturnNumpyArray = return_value_policy<Policies::VectorToNumpy>;
247
248 // define a new "Statistics" scope so that everything is called as
249 // Statistics.getXXX
250 // this affects everything defined within the lifetime of the scope object
251 scope stats =
252 class_<Stats>("Stats", no_init)
253 .def("getStatistics", &getStatisticsNumpy,
254 getStatisticsOverloads((arg("data"), arg("sorted")), "Determine the statistics for an array of data"))
255 .staticmethod("getStatistics")
256
257 .def("getZscore", &getZscoreNumpy, arg("data"), "Determine the Z score for an array of data")
258 .def("getZscore", &getZscoreNumpyDeprecated, (arg("data"), arg("sorted")),
259 "Determine the Z score for an array of "
260 "data (deprecated + ignored sorted argument)")
261 .staticmethod("getZscore")
262
263 .def("getModifiedZscore", &getModifiedZscoreNumpy,
264 getModifiedZscoreOverloads((arg("data"), arg("sorted")),
265 "Determine the modified Z score for an array of data"))
266 .staticmethod("getModifiedZscore")
267
268 .def("getMomentsAboutOrigin", &getMomentsAboutOriginNumpy,
269 getMomentsAboutOriginOverloads(
270 (arg("indep"), arg("depend"), arg("maxMoment")),
271 "Calculate the first n-moments (inclusive) about the origin")[ReturnNumpyArray()])
272 .staticmethod("getMomentsAboutOrigin")
273
274 .def("getMomentsAboutMean", &getMomentsAboutMeanNumpy,
275 getMomentsAboutMeanOverloads(
276 (arg("indep"), arg("depend"), arg("maxMoment")),
277 "Calculate the first n-moments (inclusive) about the mean")[ReturnNumpyArray()])
278 .staticmethod("getMomentsAboutMean");
279
280 // Want this in the same scope as above so must be here
281 class_<Statistics>("Statistics")
282 .add_property("minimum", &Statistics::minimum, "Minimum value of the data set")
283 .add_property("maximum", &Statistics::maximum, "Maximum value of the data set")
284 .add_property("mean", &Statistics::mean, "Simple mean, sum(data)/nvalues, of the data set")
285 .add_property("median", &Statistics::median, "Middle value of the data set")
286 .add_property("standard_deviation", &Statistics::standard_deviation, "Standard width of distribution");
287}
tagPyArrayObject PyArrayObject
void export_Statistics()
#define UNUSED_ARG(x)
Function arguments are sometimes unused in certain implmentations but are required for documentation ...
Definition System.h:44
double obj
the value of the quadratic function
#define GNU_DIAG_ON(x)
#define GNU_DIAG_OFF(x)
This is a collection of macros for turning compiler warnings off in a controlled manner.
Thin object wrapper around a numpy array.
Definition NDArray.h:31
std::vector< double > getModifiedZscore(const std::vector< TYPE > &data)
Return the modified Z score values for a dataset.
Statistics getStatistics(const std::vector< TYPE > &data, const unsigned int flags=StatOptions::AllStats)
Return a statistics object for the given data set.
std::vector< double > getZscore(const std::vector< TYPE > &data)
Return the Z score values for a dataset.
std::vector< double > getMomentsAboutMean(const std::vector< TYPE > &x, const std::vector< TYPE > &y, const int maxMoment=3)
Return the first n-moments of the supplied data.
std::vector< double > getMomentsAboutOrigin(const std::vector< TYPE > &x, const std::vector< TYPE > &y, const int maxMoment=3)
Return the first n-moments of the supplied data.
Controls the computation of statisical data.
Definition Statistics.h:53
Simple struct to store statistics.
Definition Statistics.h:36
double mean
Mean value.
Definition Statistics.h:42
double median
Median value.
Definition Statistics.h:44
double minimum
Minimum value.
Definition Statistics.h:38
double maximum
Maximum value.
Definition Statistics.h:40
double standard_deviation
standard_deviation of the values
Definition Statistics.h:46
Converter taking an input numpy array and converting it to a std::vector.