Skip to content

Commit

Permalink
Refs #4399. Move Matrix->numpy functions to templated objects.
Browse files Browse the repository at this point in the history
As with the vector converters this will provide much more flexibility
in the conversion.
  • Loading branch information
martyngigg committed Feb 20, 2012
1 parent 6a60c84 commit b7049d7
Show file tree
Hide file tree
Showing 7 changed files with 182 additions and 39 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
#ifndef MANTID_PYTHONINTERFACE_MATRIXTONDARRAY_H_
#define MANTID_PYTHONINTERFACE_MATRIXTONDARRAY_H_
/**
Copyright © 2012 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory
This file is part of Mantid.
Mantid is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
Mantid is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
File change history is stored at: <https://svn.mantidproject.org/mantid/trunk/Code/Mantid>
Code Documentation is available at: <http://doxygen.mantidproject.org>
*/
#include "MantidKernel/System.h"
#include "MantidKernel/Matrix.h"
#include <boost/python/detail/prefix.hpp>

namespace Mantid
{
namespace PythonInterface
{
namespace Converters
{
//-----------------------------------------------------------------------
// Converter implementation
//-----------------------------------------------------------------------
/**
* Converter that takes a Mantid Matrix and converts it into a
* numpy array.
*
* The type of conversion is specified by another struct/class that
* contains a static member create.
*/
template<typename ElementType, typename ConversionPolicy>
struct DLLExport MatrixToNDArray
{
inline PyObject * operator()(const Kernel::Matrix<ElementType> & cmatrix) const
{
typedef typename ConversionPolicy::template apply<ElementType> policy;
return policy::create(cmatrix);
}
};

//-----------------------------------------------------------------------
// Conversion Policies
//-----------------------------------------------------------------------
namespace Impl
{
enum WrapMode { ReadOnly, ReadWrite };
/**
* Helper functions to keep the numpy arrayobject header out
* the header file
*/
/// Wrap a numpy array around existing data
template<typename ElementType>
PyObject *wrapWithNDArray(const Kernel::Matrix<ElementType>&, const WrapMode);
}

/**
* WrapReadOnly is a policy for VectorToNDArray
* to wrap the vector in a read-only numpy array
* that looks at the original data. No copy is performed
*/
struct WrapReadOnly
{
template<typename ElementType>
struct apply
{
/**
* Returns a read-only Numpy array wrapped around an existing vector
* @param cvector
* @return
*/
static PyObject * create(const Kernel::Matrix<ElementType> & cmatrix)
{
return Impl::wrapWithNDArray(cmatrix, Impl::ReadOnly);
}
};
};

/**
* WrapReadWrite is a policy for MatrixToNDArray
* to wrap the vector in a read-write numpy array
* that looks at the original data. No copy is performed
*/
struct WrapReadWrite
{
template<typename ElementType>
struct apply
{
/**
* Returns a read-write Numpy array wrapped around an existing vector
* @param cvector
* @return
*/
static PyObject * create(const Kernel::Matrix<ElementType> & cmatrix)
{
return Impl::wrapWithNDArray(cmatrix, Impl::ReadWrite);
}
};
};

}
}
}

#endif /// MANTID_PYTHONINTERFACE_MATRIXTONDARRAY_H_
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,6 @@ namespace Mantid
{
namespace Numpy
{
/** @name Create Numpy arrays */
//@{
/// Create a read-only array wrapper around a double Matrix
DLLExport PyObject *wrapWithNumpy(const Kernel::DblMatrix & data);
/// Create a read-only array wrapper around a double Matrix
DLLExport PyObject *wrapWithReadOnlyNumpy(const Kernel::DblMatrix & data);
//@}

/** @name Create Mantid objects from python sequences */
//@{
/// Try and create a Mantid V3D object from the given PyObject.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "MantidGeometry/Crystal/OrientedLattice.h"
#include "MantidPythonInterface/kernel/Converters/MatrixToNDArray.h"
#include "MantidPythonInterface/kernel/NumpyConverters.h"
#include <boost/python/class.hpp>

Expand All @@ -14,7 +15,7 @@ namespace //<unnamed>
/// Return the U matrix as a 2D numpy array
PyObject * getU(OrientedLattice &self)
{
return Numpy::wrapWithReadOnlyNumpy(self.getU());
return Converters::MatrixToNDArray<double, Converters::WrapReadOnly>()(self.getU());
}

/// Set the U vector via a numpy array
Expand All @@ -26,7 +27,7 @@ namespace //<unnamed>
/// Return the U matrix as a 2D numpy array
PyObject * getUB(OrientedLattice &self)
{
return Numpy::wrapWithReadOnlyNumpy(self.getUB());
return Converters::MatrixToNDArray<double, Converters::WrapReadOnly>()(self.getUB());
}

/// Set the U vector via a numpy array
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "MantidGeometry/Crystal/UnitCell.h"
#include "MantidPythonInterface/kernel/Converters/MatrixToNDArray.h"
#include "MantidPythonInterface/kernel/NumpyConverters.h"
#include <boost/python/class.hpp>
#include <boost/python/enum.hpp>
Expand All @@ -20,20 +21,20 @@ namespace //<unnamed>
/// Pass-through function to return the B matrix as a numpy array
PyObject * getB(UnitCell& self)
{
return Numpy::wrapWithReadOnlyNumpy(self.getB());
return Converters::MatrixToNDArray<double, Converters::WrapReadOnly>()(self.getB());
}

/// Pass-through function to return the B matrix as a numpy array
PyObject * getG(UnitCell& self)
{
return Numpy::wrapWithReadOnlyNumpy(self.getG());
return Converters::MatrixToNDArray<double, Converters::WrapReadOnly>()(self.getG());
}


/// Pass-through function to return the B matrix as a numpy array
PyObject * getGstar(UnitCell& self)
{
return Numpy::wrapWithReadOnlyNumpy(self.getGstar());
return Converters::MatrixToNDArray<double, Converters::WrapReadOnly>()(self.getGstar());
}

/// Pass-through function to set the unit cell from a 2D numpy array
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ set ( EXPORT_FILES
)

set ( SRC_FILES
src/Converters/MatrixToNDArray.cpp
src/Converters/NDArrayToVector.cpp
src/Converters/NDArrayTypeIndex.cpp
src/Converters/PyArrayType.cpp
Expand All @@ -39,6 +40,7 @@ set ( SRC_FILES
)

set ( INC_FILES
${HEADER_DIR}/kernel/Converters/MatrixToNDArray.h
${HEADER_DIR}/kernel/Converters/NDArrayToVector.h
${HEADER_DIR}/kernel/Converters/NDArrayTypeIndex.h
${HEADER_DIR}/kernel/Converters/VectorToNDArray.h
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
#include "MantidPythonInterface/kernel/Converters/MatrixToNDArray.h"
#include "MantidPythonInterface/kernel/Converters/NDArrayTypeIndex.h"

#define PY_ARRAY_UNIQUE_SYMBOL KERNEL_ARRAY_API
#define NO_IMPORT_ARRAY
#include <numpy/arrayobject.h>

namespace Mantid { namespace PythonInterface
{
namespace Converters
{
namespace Impl
{
/**
* Wraps a vector in a numpy array structure without copying the data
* @param cvector :: A reference to the std::vector to wrap
* @param mode :: A mode switch to define whether the final array is read only/read-write
* @return A pointer to a numpy ndarray object
*/
template<typename ElementType>
PyObject *wrapWithNDArray(const Kernel::Matrix<ElementType> & cmatrix, const WrapMode mode)
{
std::pair<size_t,size_t> matrixDims = cmatrix.size();
npy_intp dims[2] = {matrixDims.first, matrixDims.second};
int datatype = NDArrayTypeIndex<ElementType>::typenum;
PyObject * ndarray = PyArray_SimpleNewFromData(2, dims, datatype,(void*)&(cmatrix[0][0]));
if( mode == ReadOnly )
{
PyArrayObject * np = (PyArrayObject *)ndarray;
np->flags &= ~NPY_WRITEABLE;
}
return ndarray;
}
//-----------------------------------------------------------------------
// Explicit instantiations
//-----------------------------------------------------------------------
#define INSTANTIATE(ElementType) \
template DLLExport PyObject * wrapWithNDArray<ElementType>(const Kernel::Matrix<ElementType> &, const WrapMode);

INSTANTIATE(int16_t);
INSTANTIATE(uint16_t);
INSTANTIATE(int32_t);
INSTANTIATE(uint32_t);
INSTANTIATE(int64_t);
INSTANTIATE(uint64_t);
#ifdef __APPLE__
INSTANTIATE(unsigned long);
#endif
INSTANTIATE(double);

}
}
}}
Original file line number Diff line number Diff line change
Expand Up @@ -16,32 +16,6 @@ namespace Mantid
namespace Numpy
{

/**
* Create a numpy array wrapper around a Matrix.
* @param data :: A const reference to an existing Matrix
* @return A numpy wrapper around the existing data, no copy is performed. It is left in a read-write state.
*/
PyObject *wrapWithNumpy(const Kernel::DblMatrix & data)
{
std::pair<size_t,size_t> matrixSize = data.size();
npy_intp dims[2] = {matrixSize.first, matrixSize.second};
PyArrayObject * ndarray =
(PyArrayObject*)PyArray_SimpleNewFromData(2, dims, NPY_DOUBLE,(void*)&(data[0][0]));
return (PyObject*)ndarray;
}

/**
* Create a read-only numpy array wrapper around a Matrix
* @param data :: A const reference to an existing Matrix
* @return A numpy wrapper around the existing data, no copy is performed. It is marked read-only.
*/
PyObject *wrapWithReadOnlyNumpy(const Kernel::DblMatrix& data)
{
PyArrayObject *nparray = (PyArrayObject*)wrapWithNumpy(data);
nparray->flags &= ~NPY_WRITEABLE;
return (PyObject*)nparray;
}

//--------------------------------------------------------------------------------------------
// Creation of Mantid objects
//--------------------------------------------------------------------------------------------
Expand Down

0 comments on commit b7049d7

Please sign in to comment.