Skip to main content

_core/
lib.rs

1use ndarray::Array2;
2use numpy::{IntoPyArray, PyArray2, PyReadonlyArray2};
3use pyo3::prelude::*;
4use pyo3::types::PyDict;
5
6use ftp_core::{ComputeMethod, FtpError, FtpResult};
7
8/// Convert an FtpError into a Python ValueError.
9fn ftp_err(e: FtpError) -> PyErr {
10    pyo3::exceptions::PyValueError::new_err(e.to_string())
11}
12
13/// Helper: get a computed output or raise ValueError.
14fn require_output<'a>(opt: Option<&'a Array2<f64>>, name: &str) -> PyResult<&'a Array2<f64>> {
15    opt.ok_or_else(|| {
16        pyo3::exceptions::PyValueError::new_err(format!(
17            "'{name}' not available — call compute() first"
18        ))
19    })
20}
21
22/// FTP Calculator — wraps the Rust ftp_core engine.
23///
24/// Usage:
25///     calc = FtpCalculator(outstanding, profiles, rates)
26///     calc.compute("stock")
27///     result = calc.stock_amort  # numpy 2D array
28#[pyclass]
29struct FtpCalculator {
30    inner: FtpResult,
31}
32
33#[pymethods]
34impl FtpCalculator {
35    #[new]
36    fn new(
37        outstanding: PyReadonlyArray2<'_, f64>,
38        profiles: PyReadonlyArray2<'_, f64>,
39        rates: PyReadonlyArray2<'_, f64>,
40    ) -> Self {
41        Self {
42            inner: FtpResult::new(
43                outstanding.as_array().to_owned(),
44                profiles.as_array().to_owned(),
45                rates.as_array().to_owned(),
46            ),
47        }
48    }
49
50    /// Run the FTP computation. method must be "stock" or "flux".
51    fn compute(&mut self, method: &str) -> PyResult<()> {
52        let m = match method {
53            "stock" => ComputeMethod::Stock,
54            "flux" => ComputeMethod::Flux,
55            other => {
56                return Err(pyo3::exceptions::PyValueError::new_err(format!(
57                    "unknown method '{other}' — use 'stock' or 'flux'"
58                )));
59            }
60        };
61        self.inner.compute(m).map_err(ftp_err)
62    }
63
64    /// (rows, cols) of the profile matrix.
65    #[getter]
66    fn dims(&self) -> (usize, usize) {
67        self.inner.input_profiles().dim()
68    }
69
70    // --- output getters (return numpy arrays) ---
71
72    #[getter]
73    fn stock_amort<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyArray2<f64>>> {
74        let arr = require_output(self.inner.stock_amort(), "stock_amort")?;
75        Ok(arr.to_owned().into_pyarray(py))
76    }
77
78    #[getter]
79    fn stock_instal<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyArray2<f64>>> {
80        let arr = require_output(self.inner.stock_instal(), "stock_instal")?;
81        Ok(arr.to_owned().into_pyarray(py))
82    }
83
84    #[getter]
85    fn varstock_amort<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyArray2<f64>>> {
86        let arr = require_output(self.inner.varstock_amort(), "varstock_amort")?;
87        Ok(arr.to_owned().into_pyarray(py))
88    }
89
90    #[getter]
91    fn varstock_instal<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyArray2<f64>>> {
92        let arr = require_output(self.inner.varstock_instal(), "varstock_instal")?;
93        Ok(arr.to_owned().into_pyarray(py))
94    }
95
96    #[getter]
97    fn ftp_rate<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyArray2<f64>>> {
98        let arr = require_output(self.inner.ftp_rate(), "ftp_rate")?;
99        Ok(arr.to_owned().into_pyarray(py))
100    }
101
102    #[getter]
103    fn ftp_int<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyArray2<f64>>> {
104        let arr = require_output(self.inner.ftp_int(), "ftp_int")?;
105        Ok(arr.to_owned().into_pyarray(py))
106    }
107
108    #[getter]
109    fn market_rate<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyArray2<f64>>> {
110        let arr = require_output(self.inner.market_rate(), "market_rate")?;
111        Ok(arr.to_owned().into_pyarray(py))
112    }
113
114    fn __repr__(&self) -> String {
115        let (r, c) = self.inner.input_profiles().dim();
116        let computed = self.inner.stock_amort().is_some();
117        format!("FtpCalculator(rows={r}, cols={c}, computed={computed})")
118    }
119}
120
121// --- One-shot convenience functions ---
122
123fn run_compute<'py>(
124    py: Python<'py>,
125    outstanding: PyReadonlyArray2<'py, f64>,
126    profiles: PyReadonlyArray2<'py, f64>,
127    rates: PyReadonlyArray2<'py, f64>,
128    method: ComputeMethod,
129) -> PyResult<Bound<'py, PyDict>> {
130    let mut r = FtpResult::new(
131        outstanding.as_array().to_owned(),
132        profiles.as_array().to_owned(),
133        rates.as_array().to_owned(),
134    );
135    r.compute(method).map_err(ftp_err)?;
136
137    let dict = PyDict::new(py);
138    dict.set_item(
139        "stock_amort",
140        r.stock_amort().unwrap().to_owned().into_pyarray(py),
141    )?;
142    dict.set_item(
143        "stock_instal",
144        r.stock_instal().unwrap().to_owned().into_pyarray(py),
145    )?;
146    dict.set_item(
147        "varstock_amort",
148        r.varstock_amort().unwrap().to_owned().into_pyarray(py),
149    )?;
150    dict.set_item(
151        "varstock_instal",
152        r.varstock_instal().unwrap().to_owned().into_pyarray(py),
153    )?;
154    dict.set_item(
155        "ftp_rate",
156        r.ftp_rate().unwrap().to_owned().into_pyarray(py),
157    )?;
158    dict.set_item("ftp_int", r.ftp_int().unwrap().to_owned().into_pyarray(py))?;
159    dict.set_item(
160        "market_rate",
161        r.market_rate().unwrap().to_owned().into_pyarray(py),
162    )?;
163    Ok(dict)
164}
165
166/// Compute FTP using the stock method. Returns a dict of numpy arrays.
167#[pyfunction]
168fn compute_stock<'py>(
169    py: Python<'py>,
170    outstanding: PyReadonlyArray2<'py, f64>,
171    profiles: PyReadonlyArray2<'py, f64>,
172    rates: PyReadonlyArray2<'py, f64>,
173) -> PyResult<Bound<'py, PyDict>> {
174    run_compute(py, outstanding, profiles, rates, ComputeMethod::Stock)
175}
176
177/// Compute FTP using the flux method. Returns a dict of numpy arrays.
178#[pyfunction]
179fn compute_flux<'py>(
180    py: Python<'py>,
181    outstanding: PyReadonlyArray2<'py, f64>,
182    profiles: PyReadonlyArray2<'py, f64>,
183    rates: PyReadonlyArray2<'py, f64>,
184) -> PyResult<Bound<'py, PyDict>> {
185    run_compute(py, outstanding, profiles, rates, ComputeMethod::Flux)
186}
187
188#[pymodule]
189fn _core(m: &Bound<'_, PyModule>) -> PyResult<()> {
190    m.add_class::<FtpCalculator>()?;
191    m.add_function(wrap_pyfunction!(compute_stock, m)?)?;
192    m.add_function(wrap_pyfunction!(compute_flux, m)?)?;
193    Ok(())
194}