version 0.4.1
pythonautodiffdefinitions.hh
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2021-2024 The Ikarus Developers mueller@ibb.uni-stuttgart.de
2// SPDX-License-Identifier: LGPL-3.0-or-later
3
9#pragma once
10#include <cstddef>
11#include <Python.h>
12
13#include <dune/fufem/dunepython.hh>
14
15#include <autodiff/forward/real/real.hpp>
16
17namespace Python {
18// *****************************************************************************
19// specializations of Conversion that do the PyObject* <-> C++-type conversion
20// *****************************************************************************
21
27template <std::size_t order, class T>
28struct Conversion<autodiff::Real<order, T>>
29{
30 enum
31 {
32 useDefaultConstructorConversion = true
33 };
34
40 static void toC(PyObject* list, autodiff::Real<order, T>& v) {
41 auto rlist = Reference(Imp::inc(list));
42 // Reference is needed to enable the ".get()" function and "Imp::inc" is
43 // needed since Reference owns the PyObject pointer and decrements it at the end of the scope
44 // Imp::inc artificially increases the reference counter by one.
45 // When we return from this function, these two cancel out and the PyObject* is as before
46
47 auto wF = Callable(rlist.get("__getitem__"));
48 for (std::size_t i = 0; i < order + 1; ++i)
49 v[i] = PyFloat_AsDouble(wF(i));
50 }
51
57 static PyObject* toPy(const autodiff::Real<order, T>& v) {
58 auto pyMain = Python::main();
59 Python::Module module = pyMain.import("autodiff");
60
61 auto real1stClass = module.get("real1st");
62 auto real1st = Callable(Imp::inc(real1stClass))();
63 auto wF = Callable(Imp::inc(real1st).get("__setitem__"));
64 for (std::size_t i = 0; i < order + 1; ++i)
65 wF(i, v[i]); // real1st.__setitem__(i,v[i]);
66
67 return real1st;
68 }
69};
70} // namespace Python
Definition: pythonautodiffdefinitions.hh:17
static void toC(PyObject *list, autodiff::Real< order, T > &v)
Convert autodiff::Real to PyObject*.
Definition: pythonautodiffdefinitions.hh:40
static PyObject * toPy(const autodiff::Real< order, T > &v)
Convert PyObject* to autodiff::Real.
Definition: pythonautodiffdefinitions.hh:57