use crate::aggregate::Aggregate;
use crate::containers::matrix::{DofOrdering, Matrix, SubMatrix, Symmetry};
use crate::handle::Handle;
use crate::models::Physics;
use crate::py::mesh::submesh_handle;
use crate::py::node::PyNode;
use crate::py::node_field::PyNodeField;
use pyo3::prelude::*;
type PyMatrixEntries = Vec<(u32, String, u32, String, f64)>;
fn check_divisor(rhs: f64, what: &str) -> PyResult<()> {
if rhs == 0.0 {
return Err(pyo3::exceptions::PyZeroDivisionError::new_err(format!(
"{what} division by zero"
)));
}
if !rhs.is_finite() {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"{what} division by {rhs}: every value of the result would be non-finite"
)));
}
Ok(())
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "SubMatrix")]
pub struct PySubMatrix {
pub(crate) handle: Handle<SubMatrix>,
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PySubMatrix {
fn add_entry(
&self,
row_node: PyRef<'_, PyNode>,
row_field: &str,
col_node: PyRef<'_, PyNode>,
col_field: &str,
value: f64,
) -> PyResult<()> {
let (rn, cn) = (row_node.as_node().id(), col_node.as_node().id());
self.handle
.write()
.add_entry(rn, row_field, cn, col_field, value)?;
Ok(())
}
fn get(
&self,
row_node: PyRef<'_, PyNode>,
row_field: &str,
col_node: PyRef<'_, PyNode>,
col_field: &str,
) -> f64 {
let (rn, cn) = (row_node.as_node().id(), col_node.as_node().id());
self.handle.read().get(rn, row_field, cn, col_field)
}
fn n_rows(&self) -> usize {
self.handle.read().n_rows()
}
fn n_cols(&self) -> usize {
self.handle.read().n_cols()
}
fn entry_count(&self) -> usize {
self.handle.read().entry_count()
}
#[getter]
fn is_symmetric(&self) -> bool {
self.handle.read().is_symmetric()
}
#[getter]
fn factor(&self) -> f64 {
self.handle.read().factor()
}
fn __mul__(&self, rhs: f64) -> PySubMatrix {
PySubMatrix {
handle: Handle::new(&*self.handle.read() * rhs),
}
}
fn __rmul__(&self, lhs: f64) -> PySubMatrix {
self.__mul__(lhs)
}
fn __truediv__(&self, rhs: f64) -> PyResult<PySubMatrix> {
check_divisor(rhs, "sub_matrix")?;
Ok(PySubMatrix {
handle: Handle::new(&*self.handle.read() / rhs),
})
}
fn physics(&self) -> Vec<String> {
self.handle
.read()
.physics()
.iter()
.map(|p| p.name().to_string())
.collect()
}
fn field_names(&self) -> Vec<String> {
self.handle.read().field_names()
}
fn row_dofs(&self) -> Vec<(u32, String)> {
self.handle
.read()
.row_dofs()
.into_iter()
.map(|(nid, name)| (nid.0, name))
.collect()
}
fn col_dofs(&self) -> Vec<(u32, String)> {
self.handle
.read()
.col_dofs()
.into_iter()
.map(|(nid, name)| (nid.0, name))
.collect()
}
fn dense(&self) -> Vec<f64> {
self.handle.read().dense()
}
fn mul_dense(&self, x: Vec<f64>) -> PyResult<Vec<f64>> {
Ok(self.handle.read().mul_dense(&x)?)
}
fn entries(&self) -> PyMatrixEntries {
self.handle
.read()
.iter_entries()
.into_iter()
.map(|(rn, rf, cn, cf, v)| (rn.0, rf, cn.0, cf, v))
.collect()
}
fn __len__(&self) -> usize {
self.handle.read().entry_count()
}
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "Matrix")]
pub struct PyMatrix {
pub(crate) inner: Matrix,
}
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PyMatrix {
#[new]
fn py_new() -> Self {
Self {
inner: Matrix::empty(),
}
}
#[classmethod]
#[pyo3(signature = (row_support, col_support, dual_vars, primal_vars, ordering="nodes_then_vars", symmetry=Symmetry::None))]
fn block(
_cls: &pyo3::Bound<'_, pyo3::types::PyType>,
row_support: &Bound<'_, PyAny>,
col_support: &Bound<'_, PyAny>,
dual_vars: Vec<String>,
primal_vars: Vec<String>,
ordering: &str,
symmetry: Symmetry,
) -> PyResult<Self> {
let ord = match ordering {
"nodes_then_vars" => DofOrdering::NodesThenVars,
"vars_then_nodes" => DofOrdering::VarsThenNodes,
other => {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"unknown ordering '{other}'; expected 'nodes_then_vars' or 'vars_then_nodes'"
)))
}
};
let row = submesh_handle(row_support)?;
let col = submesh_handle(col_support)?;
let sub = SubMatrix::new(row, col, dual_vars, primal_vars, ord, symmetry);
let mut m = Matrix::empty();
m.add_sub(Handle::new(sub))?;
Ok(Self { inner: m })
}
fn assemble(&mut self) -> PyResult<()> {
self.inner.assemble()?;
Ok(())
}
fn finalize(&mut self) -> PyResult<()> {
self.inner.finalize()?;
Ok(())
}
fn filter(&self, physics: Physics) -> PyResult<Self> {
Ok(Self {
inner: self.inner.filter(physics),
})
}
fn physics(&self) -> Vec<String> {
self.inner
.physics()
.iter()
.map(|p| p.name().to_string())
.collect()
}
fn n_rows(&self) -> PyResult<usize> {
Ok(self.inner.n_rows()?)
}
fn n_cols(&self) -> PyResult<usize> {
Ok(self.inner.n_cols()?)
}
fn entry_count(&self) -> usize {
self.inner.entry_count()
}
#[getter]
fn symmetric(&self) -> bool {
self.inner.symmetric()
}
fn field_names(&self) -> Vec<String> {
self.inner.field_names()
}
fn row_dofs(&self) -> PyResult<Vec<(u32, String)>> {
Ok(self
.inner
.row_dofs()?
.into_iter()
.map(|(n, name)| (n.0, name))
.collect())
}
fn col_dofs(&self) -> PyResult<Vec<(u32, String)>> {
Ok(self
.inner
.col_dofs()?
.into_iter()
.map(|(n, name)| (n.0, name))
.collect())
}
fn get(
&self,
row_node: PyRef<'_, PyNode>,
row_field: &str,
col_node: PyRef<'_, PyNode>,
col_field: &str,
) -> f64 {
let (rn, cn) = (row_node.as_node().id(), col_node.as_node().id());
self.inner.get(rn, row_field, cn, col_field)
}
fn dense(&self) -> PyResult<Vec<f64>> {
Ok(self.inner.dense()?)
}
fn mul_dense(&self, x: Vec<f64>) -> PyResult<Vec<f64>> {
Ok(self.inner.mul_dense(&x)?)
}
fn __truediv__(&self, rhs: f64) -> PyResult<PyMatrix> {
check_divisor(rhs, "matrix")?;
Ok(PyMatrix {
inner: &self.inner / rhs,
})
}
fn __rmul__(&self, lhs: f64) -> PyMatrix {
PyMatrix {
inner: &self.inner * lhs,
}
}
fn __neg__(&self) -> PyMatrix {
PyMatrix {
inner: -&self.inner,
}
}
fn entries(&self) -> PyMatrixEntries {
self.inner
.iter_entries()
.into_iter()
.map(|(rn, rf, cn, cf, v)| (rn.0, rf, cn.0, cf, v))
.collect()
}
}
#[pymethods]
impl PyMatrix {
fn __mul__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<Py<PyAny>> {
let py = rhs.py();
if let Ok(field) = rhs.extract::<PyRef<'_, PyNodeField>>() {
let inner = self.inner.mul_field(&field.inner)?;
return Ok(Py::new(py, PyNodeField { inner })?.into_any());
}
let s: f64 = rhs.extract()?;
let inner = &self.inner * s;
Ok(Py::new(py, PyMatrix { inner })?.into_any())
}
}
enum SumOperand<'py> {
Aggregate(PyRef<'py, PyMatrix>),
Block(PyRef<'py, PySubMatrix>),
}
impl<'py> SumOperand<'py> {
fn extract(rhs: &Bound<'py, PyAny>, op: &str) -> PyResult<Self> {
if let Ok(m) = rhs.extract::<PyRef<'py, PyMatrix>>() {
return Ok(Self::Aggregate(m));
}
if let Ok(b) = rhs.extract::<PyRef<'py, PySubMatrix>>() {
return Ok(Self::Block(b));
}
Err(pyo3::exceptions::PyTypeError::new_err(format!(
"{op}: the right-hand side must be a Matrix or a SubMatrix"
)))
}
}
#[pymethods]
impl PyMatrix {
fn __add__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyMatrix> {
let inner = match SumOperand::extract(rhs, "matrix + x")? {
SumOperand::Aggregate(m) => &self.inner + &m.inner,
SumOperand::Block(b) => &self.inner + &*b.handle.read(),
};
Ok(PyMatrix { inner })
}
fn __sub__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyMatrix> {
let inner = match SumOperand::extract(rhs, "matrix - x")? {
SumOperand::Aggregate(m) => &self.inner - &m.inner,
SumOperand::Block(b) => &self.inner - &*b.handle.read(),
};
Ok(PyMatrix { inner })
}
}
#[pymethods]
impl PySubMatrix {
fn __add__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyMatrix> {
let inner = match SumOperand::extract(rhs, "sub_matrix + x")? {
SumOperand::Aggregate(m) => &*self.handle.read() + &m.inner,
SumOperand::Block(b) => {
let other = (*b.handle.read()).clone();
&*self.handle.read() + &other
}
};
Ok(PyMatrix { inner })
}
fn __sub__(&self, rhs: &Bound<'_, PyAny>) -> PyResult<PyMatrix> {
let inner = match SumOperand::extract(rhs, "sub_matrix - x")? {
SumOperand::Aggregate(m) => &*self.handle.read() - &m.inner,
SumOperand::Block(b) => {
let other = (*b.handle.read()).clone();
&*self.handle.read() - &other
}
};
Ok(PyMatrix { inner })
}
fn __neg__(&self) -> PySubMatrix {
PySubMatrix {
handle: Handle::new(-&*self.handle.read()),
}
}
}
#[cfg(feature = "stub-gen")]
pyo3_stub_gen::inventory::submit! {
pyo3_stub_gen::derive::gen_methods_from_python! { r#"
class PyMatrix:
@overload
def __mul__(self, rhs: pyo3_stub_gen.RustType["PyNodeField"]) -> pyo3_stub_gen.RustType["PyNodeField"]:
"""`matrix * x` → the matrix-vector product: `x` is read at the column
DOFs, the result is a fresh `NodeField` over the row DOFs."""
@overload
def __mul__(self, rhs: float) -> pyo3_stub_gen.RustType["PyMatrix"]:
"""`matrix * scalar` → a fresh `Matrix` whose blocks carry the scaled
`factor` (lazy — no value is rewritten). **Not** finalized: call
`finalize()` (or `assemble` for computed blocks) before solving."""
"# }
}
#[cfg(feature = "stub-gen")]
pyo3_stub_gen::inventory::submit! {
pyo3_stub_gen::derive::gen_methods_from_python! { r#"
class PyMatrix:
def __add__(self, rhs: pyo3_stub_gen.RustType["PyMatrix"] | pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
"""`matrix + other` → a fresh `Matrix` holding the blocks of both,
shared and **not** deduplicated: `k + k` is `2k` where `k | k` is `k`.
Reach for `|` to compose one operator out of distinct parts, for `+` to
add two operators. **Not** finalized: call `assemble()` before solving."""
def __sub__(self, rhs: pyo3_stub_gen.RustType["PyMatrix"] | pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
"""`matrix - other` → as `+`, with the right-hand side's blocks
negated (which copies them, the factor living in the block)."""
"# }
}
#[cfg(feature = "stub-gen")]
pyo3_stub_gen::inventory::submit! {
pyo3_stub_gen::derive::gen_methods_from_python! { r#"
class PySubMatrix:
def __add__(self, rhs: pyo3_stub_gen.RustType["PyMatrix"] | pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
"""`sub_matrix + other` → a fresh `Matrix` holding this block and the
other operand's, as `Matrix.__add__` does."""
def __sub__(self, rhs: pyo3_stub_gen.RustType["PyMatrix"] | pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
"""`sub_matrix - other` → as `+`, with the right-hand side negated."""
def __neg__(self) -> pyo3_stub_gen.RustType["PySubMatrix"]:
"""`-sub_matrix` → a fresh block carrying the negated `factor`
(lazy — no value is rewritten)."""
"# }
}
crate::impl_aggregate_pymethods!(
PyMatrix,
PySubMatrix,
"Matrix",
sub_matrix,
Matrix,
r#"
class PyMatrix:
@overload
def __getitem__(self, key: int) -> pyo3_stub_gen.RustType["PySubMatrix"]:
"""`matrix[i]` → the `SubMatrix` view of block i (one rectangular COO
block, with its row and column supports)."""
@overload
def __getitem__(self, key: slice) -> pyo3_stub_gen.RustType["PyMatrix"]:
"""`matrix[i:j:k]` → a fresh `Matrix` holding the sliced blocks, shared
with this one (no deep copy)."""
def __or__(self, other: pyo3_stub_gen.RustType["PyMatrix"] | pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
"""`matrix | other` → a fresh `Matrix` holding the blocks of both, in
first-seen order and deduplicated by object identity. Assemble the global
operator this way, then call `finalize()` before solving."""
def __ror__(self, other: pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
"""`sub_matrix | matrix` — the mirror of `matrix | sub_matrix`,
differing only in that the lone block comes first."""
"#,
r#"
class PySubMatrix:
def __or__(self, other: pyo3_stub_gen.RustType["PySubMatrix"]) -> pyo3_stub_gen.RustType["PyMatrix"]:
"""`sub_matrix | sub_matrix` → a fresh `Matrix` holding both blocks."""
"#
);
crate::impl_dump_pymethod!(handle PySubMatrix, handle);