version 0.4
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
27 template <std::size_t order, class T>
28 struct Conversion<autodiff::Real<order, T>> {
29 enum { useDefaultConstructorConversion = true };
30
36 static void toC(PyObject* list, autodiff::Real<order, T>& v) {
37 auto rlist = Reference(Imp::inc(list));
38 // Reference is needed to enable the ".get()" function and "Imp::inc" is
39 // needed since Reference owns the PyObject pointer and decrements it at the end of the scope
40 // Imp::inc artificially increases the reference counter by one.
41 // When we return from this function, these two cancel out and the PyObject* is as before
42
43 auto wF = Callable(rlist.get("__getitem__"));
44 for (std::size_t i = 0; i < order + 1; ++i)
45 v[i] = PyFloat_AsDouble(wF(i));
46 }
47
53 static PyObject* toPy(const autodiff::Real<order, T>& v) {
54 auto pyMain = Python::main();
55 Python::Module module = pyMain.import("autodiff");
56
57 auto real1stClass = module.get("real1st");
58 auto real1st = Callable(Imp::inc(real1stClass))();
59 auto wF = Callable(Imp::inc(real1st).get("__setitem__"));
60 for (std::size_t i = 0; i < order + 1; ++i)
61 wF(i, v[i]); // real1st.__setitem__(i,v[i]);
62
63 return real1st;
64 }
65 };
66} // namespace Python
Definition: pythonautodiffdefinitions.hh:17
static void toC(PyObject *list, autodiff::Real< order, T > &v)
Convert autodiff::Real to PyObject*.
Definition: pythonautodiffdefinitions.hh:36
static PyObject * toPy(const autodiff::Real< order, T > &v)
Convert PyObject* to autodiff::Real.
Definition: pythonautodiffdefinitions.hh:53