Mantid
Loading...
Searching...
No Matches
MatrixWorkspace.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 +
8
9#include "MantidAPI/Axis.h"
10#include "MantidAPI/Run.h"
13#include "MantidHistogramData/HistogramDx.h"
14#include "MantidHistogramData/HistogramE.h"
15#include "MantidHistogramData/HistogramX.h"
16#include "MantidHistogramData/HistogramY.h"
17#include "MantidIndexing/IndexInfo.h"
20
29
30#include <boost/python/class.hpp>
31#include <boost/python/copy_const_reference.hpp>
32#include <boost/python/dict.hpp>
33#include <boost/python/implicit.hpp>
34#include <boost/python/list.hpp>
35#include <boost/python/overloads.hpp>
36#include <boost/python/register_ptr_to_python.hpp>
37#include <boost/python/suite/indexing/map_indexing_suite.hpp>
38#include <boost/python/tuple.hpp>
39
40#include <numeric>
41
42#define PY_ARRAY_UNIQUE_SYMBOL API_ARRAY_API
43#define NO_IMPORT_ARRAY
44#include <numpy/arrayobject.h>
45
46using namespace Mantid::API;
47using namespace Mantid::Geometry;
48using namespace Mantid::Kernel;
49using namespace Mantid::PythonInterface;
53using namespace boost::python;
54
56
57namespace {
59using return_readonly_numpy = return_value_policy<VectorRefToNumpy<WrapReadOnly>>;
61using return_readwrite_numpy = return_value_policy<VectorRefToNumpy<WrapReadWrite>>;
62
63//------------------------------- Overload macros ---------------------------
64GNU_DIAG_OFF("unused-local-typedef")
65// Ignore -Wconversion warnings coming from boost::python
66// Seen with GCC 7.1.1 and Boost 1.63.0
67GNU_DIAG_OFF("conversion")
68// Overloads for yIndexOfX function which has 2 optional argument
69// cppcheck-suppress unknownMacro
70BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(MatrixWorkspace_yIndexOfXOverloads, MatrixWorkspace::yIndexOfX, 1, 3)
71// Overloads for YUnitLabel which has 1 optional argument
72BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(MatrixWorkspace_YUnitLabelOverloads, YUnitLabel, 0, 1)
73GNU_DIAG_ON("conversion")
74GNU_DIAG_ON("unused-local-typedef")
75
76
87template <typename HistogramType>
88void setSpectrumFromPyObject(HistogramType &histogram, const boost::python::object &values) {
89 auto data = histogram.rawData();
90 if (NDArray::check(values)) {
91 NDArrayToVector<double> converter(values);
92 converter.copyTo(data);
93 } else {
94 PySequenceToVector<double> converter(values);
95 converter.copyTo(data);
96 }
97 histogram = HistogramType(std::move(data));
98}
99
106void setMonitorWorkspace(MatrixWorkspace &self, const boost::python::object &value) {
108 std::dynamic_pointer_cast<MatrixWorkspace>(Mantid::PythonInterface::ExtractSharedPtr<Workspace>(value)());
109 self.setMonitorWorkspace(monWS);
110}
116std::weak_ptr<Workspace> getMonitorWorkspace(MatrixWorkspace &self) {
117 return std::weak_ptr<Workspace>(self.monitorWorkspace());
118}
124void clearMonitorWorkspace(MatrixWorkspace &self) {
126 self.setMonitorWorkspace(monWS);
127}
128
134list getSpectrumNumbers(const MatrixWorkspace &self) {
135 const auto &spectrumNums = self.indexInfo().spectrumNumbers();
136 list spectra;
137
138 for (const auto &index : spectrumNums) {
139 spectra.append(static_cast<int32_t>(index));
140 }
141
142 return spectra;
143}
144
154const Mantid::MantidVec &xData(MatrixWorkspace &self, const size_t index) { return self.x(index).rawData(); }
155const Mantid::MantidVec &yData(MatrixWorkspace &self, const size_t index) { return self.y(index).rawData(); }
156const Mantid::MantidVec &eData(MatrixWorkspace &self, const size_t index) { return self.e(index).rawData(); }
157const Mantid::MantidVec &dxData(MatrixWorkspace &self, const size_t index) { return self.dx(index).rawData(); }
158
159const Mantid::MantidVec &mutableXData(MatrixWorkspace &self, const size_t index) {
160 return self.mutableX(index).rawData();
161}
162const Mantid::MantidVec &mutableYData(MatrixWorkspace &self, const size_t index) {
163 return self.mutableY(index).rawData();
164}
165const Mantid::MantidVec &mutableEData(MatrixWorkspace &self, const size_t index) {
166 return self.mutableE(index).rawData();
167}
168const Mantid::MantidVec &mutableDxData(MatrixWorkspace &self, const size_t index) {
169 return self.mutableDx(index).rawData();
170}
171
178const Mantid::MantidVec &readXDeprecated(MatrixWorkspace &self, const size_t index) {
179 if (PyErr_Warn(PyExc_DeprecationWarning,
180 "`MatrixWorkspace.readX()` is deprecated in Mantid 7.0, use `MatrixWorkspace.x()` instead. "
181 "For more information, see the Histogram data concept page: "
182 "https://docs.mantidproject.org/nightly/concepts/HistogramData.html") < 0)
183 throw boost::python::error_already_set();
184 return xData(self, index);
185}
186
193const Mantid::MantidVec &readYDeprecated(MatrixWorkspace &self, const size_t index) {
194 if (PyErr_Warn(PyExc_DeprecationWarning,
195 "`MatrixWorkspace.readY()` is deprecated in Mantid 7.0, use `MatrixWorkspace.y()` instead. "
196 "For more information, see the Histogram data concept page: "
197 "https://docs.mantidproject.org/nightly/concepts/HistogramData.html") < 0)
198 throw boost::python::error_already_set();
199 return yData(self, index);
200}
201
208const Mantid::MantidVec &readEDeprecated(MatrixWorkspace &self, const size_t index) {
209 if (PyErr_Warn(PyExc_DeprecationWarning,
210 "`MatrixWorkspace.readE()` is deprecated in Mantid 7.0, use `MatrixWorkspace.e()` instead. "
211 "For more information, see the Histogram data concept page: "
212 "https://docs.mantidproject.org/nightly/concepts/HistogramData.html") < 0)
213 throw boost::python::error_already_set();
214 return eData(self, index);
215}
216
223const Mantid::MantidVec &readDxDeprecated(MatrixWorkspace &self, const size_t index) {
224 if (PyErr_Warn(PyExc_DeprecationWarning,
225 "`MatrixWorkspace.readDx()` is deprecated in Mantid 7.0, use `MatrixWorkspace.dx()` instead. "
226 "For more information, see the Histogram data concept page: "
227 "https://docs.mantidproject.org/nightly/concepts/HistogramData.html") < 0)
228 throw boost::python::error_already_set();
229 return dxData(self, index);
230}
231
238const Mantid::MantidVec &dataXDeprecated(MatrixWorkspace &self, const size_t index) {
239 if (PyErr_Warn(PyExc_DeprecationWarning,
240 "`MatrixWorkspace.dataX()` is deprecated in Mantid 7.0, use `MatrixWorkspace.mutableX()` instead. "
241 "For more information, see the Histogram data concept page: "
242 "https://docs.mantidproject.org/nightly/concepts/HistogramData.html") < 0)
243 throw boost::python::error_already_set();
244 return mutableXData(self, index);
245}
246
253const Mantid::MantidVec &dataYDeprecated(MatrixWorkspace &self, const size_t index) {
254 if (PyErr_Warn(PyExc_DeprecationWarning,
255 "`MatrixWorkspace.dataY()` is deprecated in Mantid 7.0, use `MatrixWorkspace.mutableY()` instead. "
256 "For more information, see the Histogram data concept page: "
257 "https://docs.mantidproject.org/nightly/concepts/HistogramData.html") < 0)
258 throw boost::python::error_already_set();
259 return mutableYData(self, index);
260}
261
268const Mantid::MantidVec &dataEDeprecated(MatrixWorkspace &self, const size_t index) {
269 if (PyErr_Warn(PyExc_DeprecationWarning,
270 "`MatrixWorkspace.dataE()` is deprecated in Mantid 7.0, use `MatrixWorkspace.mutableE()` instead. "
271 "For more information, see the Histogram data concept page: "
272 "https://docs.mantidproject.org/nightly/concepts/HistogramData.html") < 0)
273 throw boost::python::error_already_set();
274 return mutableEData(self, index);
275}
276
283const Mantid::MantidVec &dataDxDeprecated(MatrixWorkspace &self, const size_t index) {
284 if (PyErr_Warn(PyExc_DeprecationWarning,
285 "`MatrixWorkspace.dataDx()` is deprecated in Mantid 7.0, use `MatrixWorkspace.mutableDx()` instead. "
286 "For more information, see the Histogram data concept page: "
287 "https://docs.mantidproject.org/nightly/concepts/HistogramData.html") < 0)
288 throw boost::python::error_already_set();
289 return mutableDxData(self, index);
290}
291
298void setXFromPyObject(MatrixWorkspace &self, const size_t wsIndex, const boost::python::object &values) {
299 setSpectrumFromPyObject(self.mutableX(wsIndex), values);
300}
301
308void setYFromPyObject(MatrixWorkspace &self, const size_t wsIndex, const boost::python::object &values) {
309 setSpectrumFromPyObject(self.mutableY(wsIndex), values);
310}
311
318void setEFromPyObject(MatrixWorkspace &self, const size_t wsIndex, const boost::python::object &values) {
319 setSpectrumFromPyObject(self.mutableE(wsIndex), values);
320}
321
328void setDxFromPyObject(MatrixWorkspace &self, const size_t wsIndex, const boost::python::object &values) {
329 setSpectrumFromPyObject(self.mutableDx(wsIndex), values);
330}
331
338void setXDeprecated(MatrixWorkspace &self, const size_t wsIndex, const boost::python::object &values) {
339 if (PyErr_Warn(PyExc_DeprecationWarning,
340 "`MatrixWorkspace.setX()` is deprecated in Mantid 7.0, use `MatrixWorkspace.setSharedX()` instead. "
341 "For more information, see the Histogram data concept page: "
342 "https://docs.mantidproject.org/nightly/concepts/HistogramData.html") < 0)
343 throw boost::python::error_already_set();
344 setXFromPyObject(self, wsIndex, values);
345}
346
353void setYDeprecated(MatrixWorkspace &self, const size_t wsIndex, const boost::python::object &values) {
354 if (PyErr_Warn(PyExc_DeprecationWarning,
355 "`MatrixWorkspace.setY()` is deprecated in Mantid 7.0, use `MatrixWorkspace.setSharedY()` instead. "
356 "For more information, see the Histogram data concept page: "
357 "https://docs.mantidproject.org/nightly/concepts/HistogramData.html") < 0)
358 throw boost::python::error_already_set();
359 setYFromPyObject(self, wsIndex, values);
360}
361
368void setEDeprecated(MatrixWorkspace &self, const size_t wsIndex, const boost::python::object &values) {
369 if (PyErr_Warn(PyExc_DeprecationWarning,
370 "`MatrixWorkspace.setE()` is deprecated in Mantid 7.0, use `MatrixWorkspace.setSharedE()` instead. "
371 "For more information, see the Histogram data concept page: "
372 "https://docs.mantidproject.org/nightly/concepts/HistogramData.html") < 0)
373 throw boost::python::error_already_set();
374 setEFromPyObject(self, wsIndex, values);
375}
376
383void setDxDeprecated(MatrixWorkspace &self, const size_t wsIndex, const boost::python::object &values) {
384 if (PyErr_Warn(PyExc_DeprecationWarning,
385 "`MatrixWorkspace.setDx()` is deprecated in Mantid 7.0, use `MatrixWorkspace.setSharedDx()` instead. "
386 "For more information, see the Histogram data concept page: "
387 "https://docs.mantidproject.org/nightly/concepts/HistogramData.html") < 0)
388 throw boost::python::error_already_set();
389 setDxFromPyObject(self, wsIndex, values);
390}
391
397std::vector<double> extractVectorFromPyObject(const boost::python::object &values) {
398 if (NDArray::check(values)) {
399 return NDArrayToVector<double>(values)();
400 }
401 return PySequenceToVector<double>(values)();
402}
403
410void setSharedXFromPyObject(MatrixWorkspace &self, const size_t wsIndex, const boost::python::object &values) {
411 self.setSharedX(wsIndex, make_cow<Mantid::HistogramData::HistogramX>(extractVectorFromPyObject(values)));
412}
413
420void setSharedYFromPyObject(MatrixWorkspace &self, const size_t wsIndex, const boost::python::object &values) {
421 self.setSharedY(wsIndex, make_cow<Mantid::HistogramData::HistogramY>(extractVectorFromPyObject(values)));
422}
423
430void setSharedEFromPyObject(MatrixWorkspace &self, const size_t wsIndex, const boost::python::object &values) {
431 self.setSharedE(wsIndex, make_cow<Mantid::HistogramData::HistogramE>(extractVectorFromPyObject(values)));
432}
433
440void setSharedDxFromPyObject(MatrixWorkspace &self, const size_t wsIndex, const boost::python::object &values) {
441 self.setSharedDx(wsIndex, make_cow<Mantid::HistogramData::HistogramDx>(extractVectorFromPyObject(values)));
442}
443
444std::vector<double> getIntegratedCountsForWorkspaceIndices(MatrixWorkspace &self,
445 const boost::python::object &workspaceIndices,
446 const size_t numberOfWorkspaces, const double minX,
447 const double maxX, const bool entireRange) {
448
449 std::vector<size_t> sWorkspaceIndices(numberOfWorkspaces);
450 if (NDArray::check(workspaceIndices)) {
451 NDArrayToVector<size_t> converter(workspaceIndices);
452 converter.copyTo(sWorkspaceIndices);
453 } else {
454 PySequenceToVector<size_t> converter(workspaceIndices);
455 converter.copyTo(sWorkspaceIndices);
456 }
457
458 return self.getIntegratedCountsForWorkspaceIndices(sWorkspaceIndices, minX, maxX, entireRange);
459}
460
461boost::python::tuple getXMinMaxForWorkspaceIndices(const MatrixWorkspace &self,
462 const boost::python::object &workspaceIndices,
463 const bool includeNonFiniteSpectra) {
464 std::vector<size_t> sWorkspaceIndices;
465 if (workspaceIndices.is_none()) {
466 sWorkspaceIndices.resize(self.getNumberHistograms());
467 std::iota(sWorkspaceIndices.begin(), sWorkspaceIndices.end(), 0);
468 } else if (NDArray::check(workspaceIndices)) {
469 NDArrayToVector<size_t> converter(workspaceIndices);
470 sWorkspaceIndices = converter();
471 } else {
472 PySequenceToVector<size_t> converter(workspaceIndices);
473 sWorkspaceIndices = converter();
474 }
475
476 const auto [xmin, xmax] = self.getXMinMax(sWorkspaceIndices, includeNonFiniteSpectra);
477 return make_tuple(xmin, xmax);
478}
479
486Mantid::API::Run &getSampleDetailsDeprecated(MatrixWorkspace &self) {
487 if (PyErr_Warn(PyExc_DeprecationWarning, "``getSampleDetails`` is deprecated, use ``getRun`` instead.") < 0)
488 throw boost::python::error_already_set();
489 return self.mutableRun();
490}
491
498std::size_t getNumberBinsDeprecated(MatrixWorkspace &self) {
499 if (PyErr_Warn(PyExc_DeprecationWarning, "``getNumberBins`` is deprecated, use ``blocksize`` instead.") < 0)
500 throw boost::python::error_already_set();
501 return self.blocksize();
502}
503
514std::size_t binIndexOfDeprecated(MatrixWorkspace &self, const double xValue, const std::size_t index = 0) {
515 if (PyErr_Warn(PyExc_DeprecationWarning, "``binIndexOf`` is deprecated, use ``yIndexOfX`` instead.") < 0)
516 throw boost::python::error_already_set();
517 return self.yIndexOfX(xValue, index);
518}
519
520GNU_DIAG_OFF("unused-local-typedef")
521// Ignore -Wconversion warnings coming from boost::python
522// Seen with GCC 7.1.1 and Boost 1.63.0
523GNU_DIAG_OFF("conversion")
524// Overloads for binIndexOfDeprecated function which has 1 optional argument
525BOOST_PYTHON_FUNCTION_OVERLOADS(binIndexOfDeprecatedOverloads, binIndexOfDeprecated, 2, 3)
526GNU_DIAG_ON("conversion")
527GNU_DIAG_ON("unused-local-typedef")
528
529
536std::vector<size_t> maskedBinsIndices(MatrixWorkspace &self, const int i) { return self.maskedBinsIndices(i); }
537
545void pythonReplaceAxis(MatrixWorkspace &self, const std::size_t &axisIndex, Axis *newAxis) {
546 self.replaceAxis(axisIndex, std::unique_ptr<Axis>(newAxis->clone(&self)));
547}
548
556object getSignalAtCoord(MatrixWorkspace &self, const NDArray &npCoords,
557 const Mantid::API::MDNormalization &normalization) {
558 if (npCoords.get_shape()[1] != 2) {
559 throw std::invalid_argument("MatrixWorkspace::getSignalAtCoord - Input "
560 "array must have shape (n, 2)");
561 }
562 // Create our output array
563 Py_intptr_t length = len(npCoords);
564 auto *signalValues = new Mantid::signal_t[length];
565
566 // Convert coords to a vector
567 std::vector<Mantid::coord_t> coords = NDArrayToVector<Mantid::coord_t>(npCoords)();
568
569 // Fill output array
570 for (int i = 0; i < length; ++i) {
571 std::array<Mantid::coord_t, 2> coord = {{coords[2 * i], coords[2 * i + 1]}};
572 signalValues[i] = self.getSignalAtCoord(coord.data(), normalization);
573 }
574 PyObject *npSignalArray =
575 Impl::wrapWithNDArray(signalValues, 1, &length, NumpyWrapMode::ReadOnly, OwnershipMode::Python);
576 return object(handle<>(npSignalArray));
577}
578
579boost::python::tuple findY(MatrixWorkspace &self, double value, tuple start) {
580 int64_t first = extract<int64_t>(start[0]);
581 int64_t second = extract<int64_t>(start[1]);
582 auto idx = self.findY(value, std::make_pair(first, second));
583 return make_tuple(idx.first, idx.second);
584}
585
594void applyBinEdgesFromAnotherWorkspace(MatrixWorkspace &self, const MatrixWorkspace &ws, const size_t getIndex,
595 const size_t setIndex) {
596 self.setBinEdges(setIndex, ws.binEdges(getIndex));
597}
598
607void applyPointsFromAnotherWorkspace(MatrixWorkspace &self, const MatrixWorkspace &ws, const size_t getIndex,
608 const size_t setIndex) {
609 self.setPoints(setIndex, ws.points(getIndex));
610}
611
612std::vector<size_t> getIndicesFromDetectorIDs(MatrixWorkspace &self, const boost::python::list &detIDs) {
614}
615
616boost::python::dict getDetectorIDToWorkspaceIndexMap(MatrixWorkspace &self, bool throwIfMultipleDets,
617 bool ignoreIfNoValidDets) {
618 const auto unorderedMap = self.getDetectorIDToWorkspaceIndexMap(throwIfMultipleDets, ignoreIfNoValidDets);
619 boost::python::dict pythonDict;
620 for (const auto &[key, value] : unorderedMap) {
621 pythonDict[key] = value;
622 }
623
624 return pythonDict;
625}
626
627} // namespace
628
633
634 class_<MatrixWorkspace, boost::python::bases<ExperimentInfo, IMDWorkspace>, boost::noncopyable>("MatrixWorkspace",
635 no_init)
636 //--------------------------------------- Meta information
637 //-----------------------------------------------------------------------
638 .def("isRaggedWorkspace", &MatrixWorkspace::isRaggedWorkspace, arg("self"),
639 "Returns true if the workspace is ragged (has differently sized "
640 "spectra).")
641 .def("blocksize", &MatrixWorkspace::blocksize, arg("self"), "Returns size of the Y data array")
642 .def("getNumberBins", &MatrixWorkspace::getNumberBins, (arg("self"), arg("index")),
643 "Returns the number of bins for a given histogram index.")
644 .def("getNumberBins", &getNumberBinsDeprecated, arg("self"),
645 "Returns size of the Y data array (deprecated, use "
646 ":class:`~mantid.api.MatrixWorkspace.blocksize` "
647 "instead)")
648 .def("getMaxNumberBins", &MatrixWorkspace::getMaxNumberBins, arg("self"),
649 "Returns the maximum number of bins in a workspace (works on ragged "
650 "data).")
651 .def("getNumberHistograms", &MatrixWorkspace::getNumberHistograms, arg("self"),
652 "Returns the number of spectra in the workspace")
653 .def("getPlotType", &MatrixWorkspace::getPlotType, arg("self"), "Returns the plot type of the workspace")
654 .def("getMarkerStyle", &MatrixWorkspace::getMarkerStyle, arg("self"), "Return the marker style for the workspace")
655 .def("getMarkerSize", &MatrixWorkspace::getMarkerSize, arg("self"), "Returns the marker size for the workspace")
656 .def("getSpectrumNumbers", &getSpectrumNumbers, arg("self"),
657 "Returns a list of all spectrum numbers in the workspace")
658 .def("yIndexOfX", &MatrixWorkspace::yIndexOfX,
659 MatrixWorkspace_yIndexOfXOverloads((arg("self"), arg("xvalue"), arg("workspaceIndex"), arg("tolerance")),
660 "Returns the y index which corresponds to the X Value provided. "
661 "The workspace_index [default=0] and tolerance [default=0.0] is "
662 "optional."))
663 .def("detectorTwoTheta", &MatrixWorkspace::detectorTwoTheta, (arg("self"), arg("det")),
664 "Returns the two theta value for a given detector")
665 .def("detectorSignedTwoTheta", &MatrixWorkspace::detectorSignedTwoTheta, (arg("self"), arg("det")),
666 "Returns the signed two theta value for given detector")
667 .def("getSpectrum", (ISpectrum & (MatrixWorkspace::*)(const size_t)) & MatrixWorkspace::getSpectrum,
668 (arg("self"), arg("workspaceIndex")), return_internal_reference<>(),
669 "Return the spectra at the given workspace index.")
670 .def("getIndexFromSpectrumNumber", &MatrixWorkspace::getIndexFromSpectrumNumber, (arg("self"), arg("spec_no")),
671 "Returns workspace index correspondent to the given spectrum "
672 "number. Throws if no such spectrum is present in the workspace")
673 .def("getIndicesFromDetectorIDs", &getIndicesFromDetectorIDs, (arg("self"), arg("detID_list")),
674 "Returns a list of workspace indices from the corrresponding "
675 "detector IDs.")
676 .def("getDetectorIDToWorkspaceIndexMap", &getDetectorIDToWorkspaceIndexMap,
677 (arg("self"), arg("throwIfMultipleDets"), arg("ignoreIfNoValidDets")),
678 " Return a map where the key is detector ID (pixel ID), and the value at that index = the corresponding "
679 "workspace index")
680 .def("getDetector", &MatrixWorkspace::getDetector, return_value_policy<RemoveConstSharedPtr>(),
681 (arg("self"), arg("workspaceIndex")),
682 "Return the :class:`~mantid.geometry.Detector` or "
683 ":class:`~mantid.geometry.DetectorGroup` that is linked to "
684 "the given workspace index")
685 .def("getRun", &MatrixWorkspace::mutableRun, arg("self"), return_internal_reference<>(),
686 "Return the :class:`~mantid.api.Run` object for this workspace")
687 .def("axes", &MatrixWorkspace::axes, arg("self"), "Returns the number of axes attached to the workspace")
688 .def("getAxis", &MatrixWorkspace::getAxis, (arg("self"), arg("axis_index")), return_internal_reference<>(),
689 "Get a pointer to a workspace axis")
690 .def("isHistogramData", &MatrixWorkspace::isHistogramData, arg("self"),
691 "Returns ``True`` if this is considered to be binned data.")
692 .def("isDistribution", (bool (MatrixWorkspace::*)() const) & MatrixWorkspace::isDistribution, arg("self"),
693 "Returns the status of the distribution flag")
694 .def("YUnit", &MatrixWorkspace::YUnit, arg("self"), return_value_policy<copy_const_reference>(),
695 "Returns the current Y unit for the data (Y axis) in the workspace")
696 .def("YUnitLabel", &MatrixWorkspace::YUnitLabel,
697 MatrixWorkspace_YUnitLabelOverloads((arg("self"), arg("useLatex")), "Returns the caption for the Y axis"))
698 .def("hasAnyMaskedBins", &MatrixWorkspace::hasAnyMaskedBins, (arg("self")),
699 "Returns true if any of the bins in this workspace are masked.")
700 .def("hasMaskedBins", &MatrixWorkspace::hasMaskedBins, (arg("self"), arg("workspaceIndex")),
701 "Returns true if this spectrum contains any masked bins")
702 .def("maskedBinsIndices", &maskedBinsIndices, (arg("self"), arg("workspaceIndex")),
703 "Returns all the masked bins' indices at the workspace index. "
704 ":class:`~mantid.api.MatrixWorkspace.hasMaskedBins` MUST be called "
705 "first to check if any bins are "
706 "masked, otherwise an exception will be thrown")
707 .def("findY", &findY, (arg("self"), arg("value"), arg("start") = make_tuple(0, 0)),
708 "Find first index in Y equal to value. Start may be specified to "
709 "begin at a specifc index. Returns tuple with the "
710 "histogram and bin indices.")
711 .def("getSampleDetails", &getSampleDetailsDeprecated, arg("self"), return_internal_reference<>(),
712 "Return the Run object for this workspace (deprecated, use "
713 ":class:`~mantid.api.MatrixWorkspace.getRun` "
714 "instead)")
715 .def("binIndexOf", &binIndexOfDeprecated,
716 binIndexOfDeprecatedOverloads((arg("self"), arg("xvalue"), arg("workspaceIndex")),
717 "Returns the index of the bin containing the given xvalue "
718 "(deprecated, use "
719 ":class:`~mantid.api.MatrixWorkspace.yIndexOfX` instead)"))
720
721 //--------------------------------------- Setters
722 //------------------------------------
723 .def("setPlotType", &MatrixWorkspace::setPlotType, (arg("self"), arg("newType")),
724 "Sets a new plot type for the workspace")
725 .def("setMarkerStyle", &MatrixWorkspace::setMarkerStyle, (arg("self"), arg("markerType")),
726 "Sets the marker type for the workspace")
727 .def("setMarkerSize", &MatrixWorkspace::setMarkerSize, (arg("self"), arg("markerSize")),
728 "Sets the size of the marker for the workspace")
729 .def("setYUnitLabel", &MatrixWorkspace::setYUnitLabel, (arg("self"), arg("newLabel")),
730 "Sets a new caption for the data (Y axis) in the workspace")
731 .def("setYUnit", &MatrixWorkspace::setYUnit, (arg("self"), arg("newUnit")),
732 "Sets a new unit for the data (Y axis) in the workspace")
733 .def("setDistribution", &MatrixWorkspace::setDistribution, (arg("self"), arg("newVal")),
734 "Set distribution flag. If True the workspace has been divided by "
735 "the bin-width.")
736 .def("replaceAxis", &pythonReplaceAxis, (arg("self"), arg("axisIndex"), arg("newAxis")),
737 "Replaces one of the workspace's axes with the new one provided. "
738 "The axis is cloned.")
739 .def("applyBinEdgesFromAnotherWorkspace", &applyBinEdgesFromAnotherWorkspace,
740 (arg("self"), arg("ws"), arg("getIndex"), arg("setIndex")),
741 "Sets the bin edges at setIndex to be the bin edges of ws at "
742 "getIndex.")
743 .def("applyPointsFromAnotherWorkspace", &applyPointsFromAnotherWorkspace,
744 (arg("self"), arg("ws"), arg("getIndex"), arg("setIndex")),
745 "Sets the points at setIndex to be the points of ws at getIndex.")
746
747 //--------------------------------------- Read spectrum data
748 //-------------------------
749 .def("x", &xData, return_readonly_numpy(), args("self", "workspaceIndex"),
750 "Creates a read-only numpy wrapper around the X data at the given index")
751 .def("y", &yData, return_readonly_numpy(), args("self", "workspaceIndex"),
752 "Creates a read-only numpy wrapper around the Y data at the given index")
753 .def("e", &eData, return_readonly_numpy(), args("self", "workspaceIndex"),
754 "Creates a read-only numpy wrapper around the E data at the given index")
755 .def("dx", &dxData, return_readonly_numpy(), args("self", "workspaceIndex"),
756 "Creates a read-only numpy wrapper around the Dx data at the given index. "
757 "If :class:`~mantid.api.MatrixWorkspace.hasDx` is False for this index, "
758 "the Dx data is first initialized to zeros.")
759 .def("readX", &readXDeprecated, (arg("self"), arg("workspaceIndex")), return_readonly_numpy(),
760 "Creates a read-only numpy wrapper "
761 "around the original X data at the "
762 "given index (deprecated, use "
763 ":class:`~mantid.api.MatrixWorkspace.x` instead)")
764 .def("readY", &readYDeprecated, return_readonly_numpy(), args("self", "workspaceIndex"),
765 "Creates a read-only numpy wrapper "
766 "around the original Y data at the "
767 "given index (deprecated, use "
768 ":class:`~mantid.api.MatrixWorkspace.y` instead)")
769 .def("readE", &readEDeprecated, return_readonly_numpy(), args("self", "workspaceIndex"),
770 "Creates a read-only numpy wrapper "
771 "around the original E data at the "
772 "given index (deprecated, use "
773 ":class:`~mantid.api.MatrixWorkspace.e` instead)")
774 .def("readDx", &readDxDeprecated, return_readonly_numpy(), args("self", "workspaceIndex"),
775 "Creates a read-only numpy wrapper "
776 "around the original Dx data at the "
777 "given index (deprecated, use "
778 ":class:`~mantid.api.MatrixWorkspace.dx` instead)")
779 .def("hasDx", &MatrixWorkspace::hasDx, args("self", "workspaceIndex"),
780 "Returns True if the spectrum uses the DX (X Error) array, else "
781 "False.")
782 //--------------------------------------- Write spectrum data
783 //------------------------
784 .def("mutableX", &mutableXData, return_readwrite_numpy(), args("self", "workspaceIndex"),
785 "Creates a writable numpy wrapper around the X data at the given index")
786 .def("mutableY", &mutableYData, return_readwrite_numpy(), args("self", "workspaceIndex"),
787 "Creates a writable numpy wrapper around the Y data at the given index. "
788 "Raises a RuntimeError for :class:`~mantid.api.IEventWorkspace`, since "
789 "non-const access to Y data is not possible for event data.")
790 .def("mutableE", &mutableEData, return_readwrite_numpy(), args("self", "workspaceIndex"),
791 "Creates a writable numpy wrapper around the E data at the given index. "
792 "Raises a RuntimeError for :class:`~mantid.api.IEventWorkspace`, since "
793 "non-const access to E data is not possible for event data.")
794 .def("mutableDx", &mutableDxData, return_readwrite_numpy(), args("self", "workspaceIndex"),
795 "Creates a writable numpy wrapper around the Dx data at the given index. "
796 "If :class:`~mantid.api.MatrixWorkspace.hasDx` is False for this index, "
797 "the Dx data is first initialized to zeros.")
798 .def("dataX", &dataXDeprecated, return_readwrite_numpy(), args("self", "workspaceIndex"),
799 "Creates a writable numpy wrapper around the original X data at the "
800 "given index (deprecated, use "
801 ":class:`~mantid.api.MatrixWorkspace.mutableX` instead)")
802 .def("dataY", &dataYDeprecated, return_readwrite_numpy(), args("self", "workspaceIndex"),
803 "Creates a writable numpy wrapper around the original Y data at the "
804 "given index (deprecated, use "
805 ":class:`~mantid.api.MatrixWorkspace.mutableY` instead)")
806 .def("dataE", &dataEDeprecated, return_readwrite_numpy(), args("self", "workspaceIndex"),
807 "Creates a writable numpy wrapper around the original E data at the "
808 "given index (deprecated, use "
809 ":class:`~mantid.api.MatrixWorkspace.mutableE` instead)")
810 .def("dataDx", &dataDxDeprecated, return_readwrite_numpy(), args("self", "workspaceIndex"),
811 "Creates a writable numpy wrapper around the original Dx data at "
812 "the given index (deprecated, use "
813 ":class:`~mantid.api.MatrixWorkspace.mutableDx` instead)")
814 .def("setX", &setXDeprecated, args("self", "workspaceIndex", "x"),
815 "Set X values from a python list or numpy array. It performs a "
816 "simple copy into the array (deprecated, use "
817 ":class:`~mantid.api.MatrixWorkspace.setSharedX` instead)")
818 .def("setY", &setYDeprecated, args("self", "workspaceIndex", "y"),
819 "Set Y values from a python list or numpy array. It performs a "
820 "simple copy into the array (deprecated, use "
821 ":class:`~mantid.api.MatrixWorkspace.setSharedY` instead)")
822 .def("setE", &setEDeprecated, args("self", "workspaceIndex", "e"),
823 "Set E values from a python list or numpy array. It performs a "
824 "simple copy into the array (deprecated, use "
825 ":class:`~mantid.api.MatrixWorkspace.setSharedE` instead)")
826 .def("setDx", &setDxDeprecated, args("self", "workspaceIndex", "dX"),
827 "Set Dx values from a python list or numpy array. It performs a "
828 "simple copy into the array (deprecated, use "
829 ":class:`~mantid.api.MatrixWorkspace.setSharedDx` instead)")
830 .def("setSharedX", &setSharedXFromPyObject, args("self", "workspaceIndex", "x"),
831 "Set the X data at the given index by building a new copy-on-write array "
832 "from a python list or numpy array and sharing it into the workspace.")
833 .def("setSharedY", &setSharedYFromPyObject, args("self", "workspaceIndex", "y"),
834 "Set the Y data at the given index by building a new copy-on-write array "
835 "from a python list or numpy array and sharing it into the workspace.")
836 .def("setSharedE", &setSharedEFromPyObject, args("self", "workspaceIndex", "e"),
837 "Set the E data at the given index by building a new copy-on-write array "
838 "from a python list or numpy array and sharing it into the workspace.")
839 .def("setSharedDx", &setSharedDxFromPyObject, args("self", "workspaceIndex", "dX"),
840 "Set the Dx data at the given index by building a new copy-on-write array "
841 "from a python list or numpy array and sharing it into the workspace.")
842
843 // --------------------------------------- Extract data
844 // ------------------------------
845 .def("extractX", Mantid::PythonInterface::cloneX, args("self"),
846 "Extracts (copies) the X data from the workspace into a 2D numpy array. "
847 "Note: This can fail for large workspaces as numpy will require a block of memory free that will fit all of "
848 "the data. "
849 "Note: This will fail for ragged workspaces.")
850 .def("extractY", Mantid::PythonInterface::cloneY, args("self"),
851 "Extracts (copies) the Y data from the workspace into a 2D numpy array. "
852 "Note: This can fail for large workspaces as numpy will require a block of memory free that will fit all of "
853 "the data. "
854 "Note: This will fail for ragged workspaces.")
855 .def("extractE", Mantid::PythonInterface::cloneE, args("self"),
856 "Extracts (copies) the E data from the workspace into a 2D numpy array. "
857 "Note: This can fail for large workspaces as numpy will require a block of memory free that will fit all of "
858 "the data. "
859 "Note: This will fail for ragged workspaces.")
860 .def("extractDx", Mantid::PythonInterface::cloneDx, args("self"),
861 "Extracts (copies) the Dx data from the workspace into a 2D numpy array. "
862 "Note: This can fail for large workspaces as numpy will require a block of memory free that will fit all of "
863 "the data. "
864 "Note: This will fail for ragged workspaces.")
865 .def("getSignalAtCoord", &getSignalAtCoord, args("self", "coords", "normalization"),
866 "Return signal for array of coordinates")
867 .def("getIntegratedCountsForWorkspaceIndices", &getIntegratedCountsForWorkspaceIndices,
868 args("self", "workspaceIndices", "numberOfWorkspaces", "minX", "maxX", "entireRange"),
869 "Return a vector with the integrated counts within the given range for the given workspace indices")
870 .def("getXMinMax", &getXMinMaxForWorkspaceIndices,
871 (arg("self"), arg("workspaceIndices") = boost::python::object(), arg("includeNonFiniteSpectra") = false),
872 "Return a tuple of the lowest and highest X values of the given workspace indices, or of all spectra if "
873 "workspaceIndices is None. A spectrum with a non-finite first or last value contributes its finite values "
874 "if includeNonFiniteSpectra is True, and is skipped otherwise. The lowest value is greater than the "
875 "highest if no spectrum contributes.")
876 //-------------------------------------- Operators
877 //-----------------------------------
878 .def("equals", &Mantid::API::equals, args("self", "other", "tolerance"),
879 "Performs a comparison operation on two workspaces, using the "
880 "CompareWorkspaces algorithm")
881 //--------- monitor workspace --------------------------------------
882 .def("getMonitorWorkspace", &getMonitorWorkspace, args("self"),
883 "Return internal monitor workspace bound to current workspace.")
884 .def("setMonitorWorkspace", &setMonitorWorkspace, args("self", "MonitorWS"),
885 "Set specified workspace as monitor workspace for"
886 "current workspace. "
887 "Note: The workspace does not have to contain monitors though "
888 "some subsequent algorithms may expect it to be "
889 "monitor workspace later.")
890 .def("clearMonitorWorkspace", &clearMonitorWorkspace, args("self"),
891 "Forget about monitor workspace, attached to the current workspace")
892 .def("isCommonBins", &MatrixWorkspace::isCommonBins, "Returns true if the workspace has common X bins.")
893 .def("isCommonLogBins", &MatrixWorkspace::isCommonLogBins,
894 "Returns true if the workspace has common X bins with log spacing.");
895
897}
double value
The value of the point.
Definition FitMW.cpp:51
#define GET_POINTER_SPECIALIZATION(TYPE)
Definition GetPointer.h:17
std::map< DeltaEMode::Type, std::string > index
void export_MatrixWorkspace()
Python exports of the Mantid::API::MatrixWorkspace class.
#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.
Class to represent the axis of a workspace.
Definition Axis.h:28
virtual Axis * clone(const MatrixWorkspace *const parentWorkspace)=0
Virtual constructor.
Run & mutableRun()
Writable version of the run object.
A "spectrum" is an object that holds the data for a particular spectrum, in particular:
Definition ISpectrum.h:38
Base MatrixWorkspace Abstract Class.
virtual std::pair< int64_t, int64_t > findY(double value, const std::pair< int64_t, int64_t > &idx={0, 0}) const
Find first index in Y equal to value.
void setMarkerStyle(const std::string &markerType)
Set the marker style for plotting.
void setSharedDx(const size_t index, const Kernel::cow_ptr< HistogramData::HistogramDx > &dx) &
virtual ISpectrum & getSpectrum(const size_t index)=0
Return the underlying ISpectrum ptr at the given workspace index.
const HistogramData::HistogramE & e(const size_t index) const
double detectorSignedTwoTheta(const Geometry::IDetector &det) const
Returns the signed 2Theta scattering angle for a detector.
void setSharedX(const size_t index, const Kernel::cow_ptr< HistogramData::HistogramX > &x) &
bool hasAnyMaskedBins() const
Does this workspace contain any masked bins.
virtual bool isCommonLogBins() const
Returns true if the workspace contains common X bins with log spacing.
HistogramData::BinEdges binEdges(const size_t index) const
void setPoints(const size_t index, T &&...data) &
HistogramData::Points points(const size_t index) const
double detectorTwoTheta(const Geometry::IDetector &det) const
Returns the 2Theta scattering angle for a detector.
HistogramData::HistogramX & mutableX(const size_t index) &
const HistogramData::HistogramDx & dx(const size_t index) const
virtual std::size_t blocksize() const =0
Returns the size of each block of data returned by the dataY accessors.
signal_t getSignalAtCoord(const coord_t *coords, const Mantid::API::MDNormalization &normalization) const override
Get the signal at a coordinate in the workspace.
virtual std::pair< double, double > getXMinMax() const
Get the X range of all spectra, skipping spectra with a non-finite first or last value.
virtual void setMonitorWorkspace(const std::shared_ptr< MatrixWorkspace > &monitorWS)
Sets the internal monitor workspace to the provided workspace.
virtual std::size_t getNumberHistograms() const =0
Returns the number of histograms in the workspace.
bool hasMaskedBins(const size_t &workspaceIndex) const
Does this spectrum contain any masked bins.
void setSharedE(const size_t index, const Kernel::cow_ptr< HistogramData::HistogramE > &e) &
const HistogramData::HistogramX & x(const size_t index) const
std::size_t yIndexOfX(const double xValue, const std::size_t &index=0, const double tolerance=0.0) const
Returns the y index which corresponds to the X Value provided.
void setSharedY(const size_t index, const Kernel::cow_ptr< HistogramData::HistogramY > &y) &
bool isDistribution() const
Are the Y-values dimensioned?
std::string getMarkerStyle() const
Get the marker style for plotting.
std::shared_ptr< MatrixWorkspace > monitorWorkspace() const
Returns a pointer to the internal monitor workspace.
virtual bool isRaggedWorkspace() const =0
Returns true if the workspace is ragged (has differently sized spectra).
std::vector< size_t > maskedBinsIndices(const size_t &workspaceIndex) const
std::vector< size_t > getIndicesFromDetectorIDs(const std::vector< detid_t > &detIdList) const
Converts a list of detector IDs to the corresponding workspace indices.
void setDistribution(bool newValue)
Set the flag for whether the Y-values are dimensioned.
const Indexing::IndexInfo & indexInfo() const
Returns a const reference to the IndexInfo object of the workspace.
float getMarkerSize() const
Get the size of the marker for plotting.
virtual bool hasDx(const std::size_t index) const
Probes if DX (X Error) values were set on a particular spectrum.
virtual std::size_t getMaxNumberBins() const =0
Returns the maximum number of bins in a workspace (works on ragged data).
const std::string & YUnit() const
std::string getPlotType() const
Gets MatrixWorkspace plot_type.
detid2index_map getDetectorIDToWorkspaceIndexMap(bool throwIfMultipleDets=false, bool ignoreIfNoValidDets=false) const
Return a map where: KEY is the DetectorID (pixel ID) VALUE is the Workspace Index.
virtual Axis * getAxis(const std::size_t &axisIndex) const
Get a non owning pointer to a workspace axis.
void setPlotType(const std::string &)
Sets MatrixWorkspace plot_type.
std::vector< double > getIntegratedCountsForWorkspaceIndices(const std::vector< size_t > &workspaceIndices, const double minX, const double maxX, const bool entireRange) const
virtual std::size_t getNumberBins(const std::size_t &index) const =0
Returns the number of bins for a given histogram index.
HistogramData::HistogramE & mutableE(const size_t index) &
HistogramData::HistogramDx & mutableDx(const size_t index) &
size_t getIndexFromSpectrumNumber(const specnum_t specNo) const
Given a spectrum number, find the corresponding workspace index.
void replaceAxis(const std::size_t &axisIndex, std::unique_ptr< Axis > newAxis)
Replaces one of the workspace's axes with the new one provided.
HistogramData::HistogramY & mutableY(const size_t index) &
std::string YUnitLabel(bool useLatex=false) const
Returns a caption for the units of the data in the workspace.
void setYUnitLabel(const std::string &newLabel)
Sets a new caption for the data (Y axis) in the workspace.
const HistogramData::HistogramY & y(const size_t index) const
void setMarkerSize(const float markerSize)
Set the size of the marker for plotting.
virtual bool isCommonBins() const
Returns true if the workspace contains common X bins.
std::shared_ptr< const Geometry::IDetector > getDetector(const size_t workspaceIndex) const
Get the effective detector for the given spectrum.
void setYUnit(const std::string &newUnit)
Sets a new unit for the data (Y axis) in the workspace.
virtual bool isHistogramData() const
Returns true if the workspace contains data in histogram form (as opposed to point-like)
void setBinEdges(const size_t index, T &&...data) &
This class stores information regarding an experimental run as a series of log entries.
Definition Run.h:36
Thin object wrapper around a numpy array.
Definition NDArray.h:31
static bool check(const boost::python::object &obj)
Check if a python object points to an array type object.
Definition NDArray.cpp:49
Py_intptr_t const * get_shape() const
Definition NDArray.cpp:61
bool MANTID_API_DLL equals(const MatrixWorkspace_sptr &lhs, const MatrixWorkspace_sptr &rhs, double tolerance=0.0)
Performs a comparison operation on two workspaces, using the CompareWorkspaces algorithm.
MDNormalization
Enum describing different ways to normalize the signal in a MDWorkspace.
Definition IMDIterator.h:25
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
PyObject * wrapWithNDArray(const ElementType *, const int ndims, Py_intptr_t *dims, const NumpyWrapMode mode, const OwnershipMode oMode=OwnershipMode::Cpp)
Defines the wrapWithNDArray specialization for C array types.
PyObject * cloneE(const API::MatrixWorkspace &self)
Create a numpy array from the E values of the given workspace reference.
PyObject * cloneY(const API::MatrixWorkspace &self)
Create a numpy array from the Y values of the given workspace reference.
PyObject * cloneDx(const API::MatrixWorkspace &self)
Create a numpy array from the E values of the given workspace reference.
PyObject * cloneX(const API::MatrixWorkspace &self)
double signal_t
Typedef for the signal recorded in a MDBox, etc.
Definition MDTypes.h:36
std::vector< double > MantidVec
typedef for the data storage used in Mantid matrix workspaces
Definition cow_ptr.h:172
Converter taking an input numpy array and converting it to a std::vector.
void copyTo(TypedVector &dest) const
Fill the container with data from the array.
Converts a Python sequence type to a C++ std::vector, where the element type is defined by the templa...
void copyTo(TypedVector &dest)
Fill the container with data from the array.
Encapsulates the registration required for an interface type T that sits on top of a Kernel::DataItem...