Skip to content

Commit 98c47b9

Browse files
authored
add python interop example (#33)
1 parent bc12a59 commit 98c47b9

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

src/SUMMARY.md

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
- [Forward Mode](./usage/fwd.md)
99
- [Reverse Mode](./usage/rev.md)
1010
- [Higher Order Derivatives](./usage/higher.md)
11+
- [Python Integration](./usage/python.md)
1112
- [Current Limitations](./limitations.md)
1213
- [Future Work](./future_work.md)
1314
- [History and ecosystem](./ecosystem.md)

src/usage/python.md

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
### Python Integration
2+
3+
std::autodiff is fully handled by the Rust compiler and therefore should not cause any issues with Python integration.
4+
An example for maturin/PyO3 is provided below. You will still need to enable `lto=fat` in your Cargo.toml and adjust
5+
the module name to match your project, otherwise python won't be able to find your functions.
6+
The first `#[pyfunction]` macro will only be applied to the original function `f`.
7+
We therefore add a small wrapper function `df_py` and apply the `#[pyfunction]` macro to it.
8+
9+
```toml
10+
11+
```rs
12+
#![feature(autodiff)]
13+
use std::autodiff::autodiff;
14+
use pyo3::prelude::*;
15+
16+
#[pyfunction]
17+
#[autodiff(df, Reverse, Active, Active)]
18+
fn f(x: f32) -> f32 {
19+
x * x
20+
}
21+
22+
// Will return x*x and 2*x
23+
#[pyfunction]
24+
fn df_py(x: f32) -> (f32, f32) {
25+
df(x, 1.0)
26+
}
27+
28+
// Remember to adjust the name of the module to match your project
29+
#[pymodule]
30+
fn my_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
31+
m.add_function(wrap_pyfunction!(f_py, m)?)?;
32+
m.add_function(wrap_pyfunction!(df_py, m)?)?;
33+
Ok(())
34+
}
35+
```

0 commit comments

Comments
 (0)