|
2 | 2 | #include <nanobind/operators.h> |
3 | 3 | #include <nanobind/stl/vector.h> |
4 | 4 | #include <nanobind/stl/optional.h> |
| 5 | +#include <nanobind/ndarray.h> |
5 | 6 |
|
6 | 7 | #include "pyoptinterface/core.hpp" |
7 | 8 | #include "pyoptinterface/container.hpp" |
8 | 9 |
|
| 10 | +#include <span> |
| 11 | +#include <algorithm> |
| 12 | + |
9 | 13 | namespace nb = nanobind; |
10 | 14 |
|
| 15 | +using CoeffNdarrayT = nb::ndarray<const double, nb::ndim<1>, nb::any_contig>; |
| 16 | +using IndexNdarrayT = nb::ndarray<int, nb::ndim<1>, nb::any_contig>; |
| 17 | + |
11 | 18 | NB_MODULE(core_ext, m) |
12 | 19 | { |
13 | 20 | nb::set_leak_warnings(false); |
@@ -74,6 +81,51 @@ NB_MODULE(core_ext, m) |
74 | 81 | nb::arg("variables")) |
75 | 82 | .def(nb::init<const Vector<CoeffT> &, const Vector<IndexT> &, CoeffT>(), |
76 | 83 | nb::arg("coefficients"), nb::arg("variables"), nb::arg("constant")) |
| 84 | + |
| 85 | + // ndarray constructor |
| 86 | + .def_static( |
| 87 | + "from_numpy", |
| 88 | + [](CoeffNdarrayT coefficients, IndexNdarrayT variables) { |
| 89 | + auto *expr = new ScalarAffineFunction(); |
| 90 | + |
| 91 | + auto n = coefficients.size(); |
| 92 | + |
| 93 | + expr->coefficients.resize(n); |
| 94 | + std::span<const double> coeffs(coefficients.data(), n); |
| 95 | + std::ranges::copy(coeffs, expr->coefficients.begin()); |
| 96 | + |
| 97 | + n = variables.size(); |
| 98 | + expr->variables.resize(n); |
| 99 | + std::span<const int> vars(variables.data(), n); |
| 100 | + std::ranges::copy(vars, expr->variables.begin()); |
| 101 | + |
| 102 | + expr->constant.reset(); |
| 103 | + |
| 104 | + return expr; |
| 105 | + }, |
| 106 | + nb::arg("coefficients"), nb::arg("variables")) |
| 107 | + .def_static( |
| 108 | + "from_numpy", |
| 109 | + [](CoeffNdarrayT coefficients, IndexNdarrayT variables, CoeffT constant) { |
| 110 | + auto *expr = new ScalarAffineFunction(); |
| 111 | + |
| 112 | + auto n = coefficients.size(); |
| 113 | + |
| 114 | + expr->coefficients.resize(n); |
| 115 | + std::span<const double> coeffs(coefficients.data(), n); |
| 116 | + std::ranges::copy(coeffs, expr->coefficients.begin()); |
| 117 | + |
| 118 | + n = variables.size(); |
| 119 | + expr->variables.resize(n); |
| 120 | + std::span<const int> vars(variables.data(), n); |
| 121 | + std::ranges::copy(vars, expr->variables.begin()); |
| 122 | + |
| 123 | + expr->constant = constant; |
| 124 | + |
| 125 | + return expr; |
| 126 | + }, |
| 127 | + nb::arg("coefficients"), nb::arg("variables"), nb::arg("constant")) |
| 128 | + |
77 | 129 | .def(nb::init<const ExprBuilder &>()) |
78 | 130 | .def_ro("coefficients", &ScalarAffineFunction::coefficients) |
79 | 131 | .def_ro("variables", &ScalarAffineFunction::variables) |
|
0 commit comments