Mantid
Loading...
Searching...
No Matches
PyObjectToV3D.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 +
7//----------------------------------------------------------------------------
8// Includes
9//----------------------------------------------------------------------------
11#include <boost/python/extract.hpp>
12
13// See
14// http://docs.scipy.org/doc/numpy/reference/c-api.array.html#PY_ARRAY_UNIQUE_SYMBOL
15#define PY_ARRAY_UNIQUE_SYMBOL CORE_ARRAY_API
16#define NO_IMPORT_ARRAY
17#include <numpy/arrayobject.h>
18
19using boost::python::extract;
20using boost::python::handle;
21using boost::python::len;
22using boost::python::object;
23
32PyObjectToV3D::PyObjectToV3D(const object &p) : m_obj(p), m_alreadyV3D(false) {
33 // Is it an already wrapped V3D ?
34 extract<Kernel::V3D> converter(p);
35 if (converter.check()) {
36 m_alreadyV3D = true;
37 return;
38 }
39 // Is it a sequence
40 try {
41 const size_t length = len(p);
42 if (length != 3) {
43 throw std::invalid_argument("Incorrect length for conversion to V3D");
44 }
45 // Can we index the object
46 p.attr("__getitem__")(0);
47 } catch (boost::python::error_already_set &) {
48 throw std::invalid_argument(std::string("Cannot convert object to V3D. Expected a python sequence found ") +
49 p.ptr()->ob_type->tp_name);
50 }
51}
52
60 if (m_alreadyV3D) {
61 return extract<Kernel::V3D>(m_obj)();
62 }
63 auto toDouble = [](const object &obj) { return extract<double>(object(handle<>(PyNumber_Float(obj.ptr()))))(); };
64 return Kernel::V3D(toDouble(m_obj[0]), toDouble(m_obj[1]), toDouble(m_obj[2]));
65}
66} // namespace Mantid::PythonInterface::Converters
double obj
the value of the quadratic function
Class for 3D vectors.
Definition: V3D.h:34
const boost::python::object & m_obj
A reference to the object.
Definition: PyObjectToV3D.h:29
PyObjectToV3D(const boost::python::object &p)
Construct the converter object with the given Python object.
Kernel::V3D operator()()
Produces a V3D object from the given PyObject.
bool m_alreadyV3D
Is the object a wrapped instance of V3D.
Definition: PyObjectToV3D.h:31