Page MenuHomec4science

numpy.hh
No OneTemporary

File Metadata

Created
Wed, May 1, 18:40

numpy.hh

/**
* @file
* @section LICENSE
*
* Copyright (©) 2016-2021 EPFL (École Polytechnique Fédérale de Lausanne),
* Laboratory (LSMS - Laboratoire de Simulation en Mécanique des Solides)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
/* -------------------------------------------------------------------------- */
#ifndef __NUMPY_HH__
#define __NUMPY_HH__
/* -------------------------------------------------------------------------- */
#include "grid_base.hh"
#include "tamaas.hh"
/* -------------------------------------------------------------------------- */
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
namespace tamaas {
namespace wrap {
namespace py = pybind11;
/// Type alias for usual numpy array type
template <typename T>
using numpy = py::array_t<T, py::array::c_style | py::array::forcecast>;
/// GridBase helper class wrapping numpy array
template <typename T>
class GridBaseNumpy : public GridBase<T> {
public:
GridBaseNumpy(numpy<T>& buffer) : GridBase<T>() {
this->nb_components = 1;
this->data.wrapMemory(buffer.mutable_data(), buffer.size());
}
};
/// Grid helper class wrapping numpy array
template <class Parent>
class GridNumpy : public Parent {
public:
GridNumpy(numpy<typename Parent::value_type>& buffer) : Parent() {
auto* array_shape = buffer.shape();
const UInt ndim = buffer.ndim();
if (ndim > Parent::dimension + 1 || ndim < Parent::dimension)
TAMAAS_EXCEPTION(
"Numpy array dimension do not match expected grid dimensions");
if (ndim == Parent::dimension + 1)
this->nb_components = array_shape[ndim - 1];
std::copy_n(array_shape, Parent::dimension, this->n.begin());
this->computeStrides();
this->data.wrapMemory(buffer.mutable_data(), this->computeSize());
}
};
/// Surface helper class wrapping numpy array
template <class Parent>
class SurfaceNumpy : public Parent {
public:
SurfaceNumpy(numpy<typename Parent::value_type>& buffer) : Parent() {
auto* array_shape = buffer.shape();
if (buffer.ndim() != 2)
TAMAAS_EXCEPTION(
"Numpy array dimension do not match expected surface dimensions");
std::copy_n(array_shape, Parent::dimension, this->n.begin());
this->computeStrides();
this->data.wrapMemory(buffer.mutable_data(), this->computeSize());
}
};
} // namespace wrap
} // namespace tamaas
#endif // __NUMPY_HH__

Event Timeline