pyrucast 0.15.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
Documentation
//! Python wrappers for [`crate::containers::model::SubModel`] and [`crate::containers::model::Model`].

use crate::atoms::NodeId;
use crate::containers::model::{Model, SubModel};
use crate::handle::Handle;
use crate::models::Physics;
use crate::py::finite_element_space::{PyFiniteElementSpace, PySubFiniteElementSpace};
use crate::py::mesh::PyMesh;
use crate::py::node::PyNode;
use crate::py::node_field::PyNodeField;
use pyo3::prelude::*;

/// A **view** into one sub-model of a `Model`, obtained by indexing
/// (`model[i]`) — never constructed directly. Build physics at the parent
/// level instead: `model.heat_conduction(fes)` or `model.dirichlet(...)`,
/// composed with `|`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "SubModel")]
pub struct PySubModel {
    pub(crate) handle: Handle<SubModel>,
}

#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PySubModel {
    /// Names of the primal (primary) variables of this sub-model.
    fn primal_vars(&self) -> Vec<String> {
        self.handle.read().primal_vars()
    }

    /// Names of the dual variables of this sub-model.
    fn dual_vars(&self) -> Vec<String> {
        self.handle.read().dual_vars()
    }

    /// `sub.fespace()` — the `SubFiniteElementSpace` this sub-model integrates
    /// on, its law included when it has one; side A for an interface
    /// transfer. `None` for a constraint sub-model (Dirichlet, MPC…, which
    /// integrate nothing).
    fn fespace(&self) -> Option<PySubFiniteElementSpace> {
        self.handle
            .read()
            .material_fespace()
            .map(|handle| PySubFiniteElementSpace { handle })
    }

    /// The physics nature(s) of this sub-model as a list of tags among
    /// `"mechanical"`, `"thermal"`, `"diffusion"`, `"radiation"`,
    /// `"constraint"` and `"contact"`. A flux or an exchange takes the nature
    /// of the model it targets; a constraint carries `"constraint"` plus that
    /// nature, or alone when its relation spans two physics; radiation carries
    /// `"thermal"` and `"radiation"`; a contact carries `"constraint"`,
    /// `"mechanical"` and `"contact"`.
    fn physics(&self) -> Vec<String> {
        self.handle
            .read()
            .physics()
            .iter()
            .map(|p| p.name().to_string())
            .collect()
    }

    /// The kind of this sub-model, named — `"Dirichlet"`, `"Contact"`,
    /// `"Elasticity"`… The question its natures cannot answer: a contact and a
    /// Dirichlet on displacements are both constraint and mechanical.
    fn label(&self) -> &'static str {
        self.handle.read().label()
    }

    /// POI1 `Mesh` of the multiplier nodes (Lagrange physics only — empty
    /// otherwise). Build a load `SubNodeField` on `mesh[0]` to impose the
    /// constrained values, or read the nodes via `mesh.node(0, i, 0)`.
    fn multiplier_mesh(&self) -> PyResult<PyMesh> {
        let mesh = self.handle.read().multiplier_mesh()?;
        Ok(PyMesh { inner: mesh })
    }

    /// Names of the material components this sub-model expects, or
    /// `None` for physics that don't need material data (Dirichlet, …).
    fn material_components(&self) -> Option<Vec<String>> {
        self.handle
            .read()
            .material_components()
            .map(|c| c.iter().map(|s| s.to_string()).collect())
    }

    /// Whether this sub-model carries a constitutive behaviour that can be
    /// integrated with `strain` / `integrate_behavior`: `True` for the
    /// physics with a law, `False` for constraints like Dirichlet and for the
    /// exchanges and the flux, which integrate on a subspace without a law.
    #[getter]
    fn has_behavior(&self) -> bool {
        self.handle.read().has_behavior()
    }
}

/// A physics problem: a collection of sub-models (heat conduction,
/// Dirichlet BCs, ...) over finite-element spaces.
///
/// Build sub-models with the operators of `pyrucast.model`
/// (`model.heat_conduction(fes)`, `model.dirichlet(...)`) and compose them
/// with `|`; assemble with `stiffness` / `mass`.
#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pyclass)]
#[pyclass(name = "Model")]
pub struct PyModel {
    pub(crate) inner: Model,
}

#[cfg_attr(feature = "stub-gen", pyo3_stub_gen::derive::gen_stub_pymethods)]
#[pymethods]
impl PyModel {
    /// Names of the primal (primary) variables across the whole model.
    fn primal_vars(&self) -> Vec<String> {
        self.inner.primal_vars()
    }

    /// Names of the dual variables across the whole model.
    fn dual_vars(&self) -> Vec<String> {
        self.inner.dual_vars()
    }

    /// `Model.dual_of(variable)` — the dual (residual) variable conjugate to a
    /// primal `variable` (e.g. `"u_x" -> "f_x"`, `"T" -> "q"`), searched across
    /// all sub-models, or `None`. A helper to fill an MPC term's `target_dual`.
    fn dual_of(&self, variable: &str) -> Option<String> {
        self.inner.dual_of(variable)
    }

    /// `Model.fespace()` — the `FiniteElementSpace` this model integrates on:
    /// the behaviour subspace of each domain sub-model (constraints skipped), in
    /// order, one per sub-model — two physics on one subspace list it twice.
    /// The subspaces are shared, not copied. Raises if the model has no domain
    /// sub-model. Combined with `FiniteElementSpace.mesh()`, lets a caller
    /// recover the FE space and mesh from the model alone.
    fn fespace(&self) -> PyResult<PyFiniteElementSpace> {
        Ok(PyFiniteElementSpace {
            inner: self.inner.fespace()?,
        })
    }

    /// `Model.filter(physics)` — a new `Model` holding only the sub-models **whose
    /// nature set contains** the given physics. `physics` is a tag: `"mechanical"`,
    /// `"thermal"`, `"constraint"`, `"other"`, `"diffusion"`, `"radiation"` or
    /// `"contact"`. Sub-model order is preserved; the result may be empty.
    ///
    /// A coupled physics declares several natures and is therefore returned by
    /// each of its filters — a radiation boundary is both `"thermal"` and
    /// `"radiation"`, a contact both `"constraint"` and `"contact"`.
    fn filter(&self, physics: Physics) -> Self {
        Self {
            inner: self.inner.filter(physics),
        }
    }

    /// `Model.exclude(physics)` — the complement of `filter`: a new `Model`
    /// holding only the sub-models **whose nature set does not contain** the
    /// given physics. The two compose, one condition each: a constraint also
    /// carries the nature of the physics it pins, so
    /// `model.filter("mechanical")` is the mechanics **with** its supports and
    /// `model.filter("mechanical").exclude("constraint")` the mechanics alone.
    fn exclude(&self, physics: Physics) -> Self {
        Self {
            inner: self.inner.exclude(physics),
        }
    }

    /// `Model.multiplier_mesh()` — POI1 `Mesh` of the constraint multiplier
    /// nodes across the model (empty for a model with no constraint). Each
    /// constraint mints its own, one per relation: read them via
    /// `mesh.node(0, i, 0)` or build a load `SubNodeField` on `mesh[0]`.
    fn multiplier_mesh(&self) -> PyResult<PyMesh> {
        Ok(PyMesh {
            inner: self.inner.multiplier_mesh()?,
        })
    }

    /// `Model.constraint_rhs(imposed)` — build the constraint load (right-hand
    /// side) of this model's constraint from `(node, g)` pairs.
    ///
    /// `imposed` is a list of `(Node, value)`: each node **keys the relation it
    /// belongs to** (for `dirichlet` the constrained node itself, for `mpc` any
    /// of the relation's term nodes), and `value` is the right-hand side `g`.
    /// Returns a fresh `NodeField` over the multiplier nodes, carrying the
    /// `imposed` component, with `g` at each cited relation and `0` elsewhere. Union it
    /// into the global load with `|`, e.g. `load | model.constraint_rhs([...])`.
    ///
    /// The model must hold exactly one constraint sub-model (the `dirichlet` /
    /// `mpc` object). Raises if a node constrains none of its relations, or keys
    /// several of them (ambiguous — drop it).
    fn constraint_rhs(
        &self,
        py: Python<'_>,
        imposed: Vec<(Py<PyNode>, f64)>,
    ) -> PyResult<PyNodeField> {
        // The relations' nodes live in the multipliers' `Coords`; a model with
        // no constraint has none, and `constraint_rhs` says so itself.
        let coords = self.inner.multiplier_mesh()?.coords().ok();
        let pairs = imposed
            .iter()
            .map(|(node, g)| Ok((node.borrow(py).id_in(coords.as_ref())?, *g)))
            .collect::<PyResult<Vec<(NodeId, f64)>>>()?;
        let inner = self.inner.constraint_rhs(&pairs)?;
        Ok(PyNodeField { inner })
    }

    /// `Model.constraint_rhs_by_index(imposed)` — like `constraint_rhs` but each
    /// relation is keyed by its **index** (0-based, in `relations()` order)
    /// instead of a node.
    ///
    /// `imposed` is a list of `(relation_index, g)`. Use this when a node
    /// participates in several relations, where node keying would be ambiguous.
    /// Returns the same kind of `NodeField` over the multiplier nodes; union it
    /// with `|`. Raises if an index is out of range.
    fn constraint_rhs_by_index(&self, imposed: Vec<(usize, f64)>) -> PyResult<PyNodeField> {
        let inner = self.inner.constraint_rhs_by_index(&imposed)?;
        Ok(PyNodeField { inner })
    }
}

crate::impl_aggregate_pymethods!(
    PyModel,
    PySubModel,
    "Model",
    sub_model,
    Model,
    r#"
class PyModel:
    @overload
    def __getitem__(self, key: int) -> pyo3_stub_gen.RustType["PySubModel"]:
        """`model[i]` → the `SubModel` view of term i (a physics term, a
        Dirichlet condition, an MPC, ...)."""
    @overload
    def __getitem__(self, key: slice) -> pyo3_stub_gen.RustType["PyModel"]:
        """`model[i:j:k]` → a fresh `Model` holding the sliced terms, shared
        with this one (no deep copy)."""
    def __or__(self, other: pyo3_stub_gen.RustType["PyModel"] | pyo3_stub_gen.RustType["PySubModel"]) -> pyo3_stub_gen.RustType["PyModel"]:
        """`model | other` → a fresh `Model` holding the terms of both, in
        first-seen order and deduplicated by object identity. This is how a problem
        is composed: physics | boundary conditions | constraints."""
    def __ror__(self, other: pyo3_stub_gen.RustType["PySubModel"]) -> pyo3_stub_gen.RustType["PyModel"]:
        """`sub_model | model` — the mirror of `model | sub_model`, differing
        only in that the lone term comes first."""
    "#,
    r#"
class PySubModel:
    def __or__(self, other: pyo3_stub_gen.RustType["PySubModel"]) -> pyo3_stub_gen.RustType["PyModel"]:
        """`sub_model | sub_model` → a fresh `Model` holding both terms."""
    "#
);
crate::impl_dump_pymethod!(handle PySubModel, handle);