//! Per-physics implementations of [`crate::containers::model::SubModel`]
//! variants.
//!
//! Each file here owns the **specifics** of one physics: a struct holding
//! its supports (FE spaces, materials, node sets) plus an [`impl SubModelKind`]
//! carrying *all* of its behaviour — variable names, material contract,
//! local assembly, and rendering. The
//! [`crate::containers::model::SubModel`] enum exists **only** for storage
//! and serialization; it dispatches every call through
//! [`SubModel::as_kind`](crate::containers::model::SubModel::as_kind)
//! so no generic code (the assembler, `Dump`, …) ever needs a per-variant
//! `match`.
//!
//! # Adding a new physics
//!
//! 1. add `models/<name>.rs` with a struct + `impl SubModelKind` (and a
//! `new(...)` constructor doing any build-time work);
//! 2. add one variant to [`crate::containers::model::SubModel`];
//! 3. add one arm to
//! [`SubModel::as_kind`](crate::containers::model::SubModel::as_kind);
//! 4. declare the parent-level operator with
//! [`physics_operator!`](crate::physics_operator) **in the same file**: it
//! emits the Rust operator *and* its `#[pyfunction]`, so nothing is written
//! by hand under `py/`;
//! 5. raccord: `pub use` in [`crate::ops::model`], and the registration in the
//! (flat) `#[pymodule]` of `lib.rs`.
//!
//! Everything else is generic. See the book chapter *"Ajouter une physique"*
//! for the full walkthrough.
use crate::aggregate::Aggregate;
use crate::atoms::NodeId;
use crate::containers::element_field::SubElementField;
use crate::containers::field::SubField;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::matrix::{hash_f64, hash_name, hash_nodes, mint_pair, Symmetry, FNV_SEED};
use crate::containers::matrix::{DofOrdering, SubMatrix};
use crate::containers::mesh::{Mesh, SubMesh};
use crate::containers::node_field::NodeField;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::named::Named;
use serde::{Deserialize, Serialize};
pub mod beam;
pub mod bernoulli;
pub mod boundary_transfer;
pub mod contact;
pub mod continuum;
pub mod damage;
pub mod dirichlet;
pub mod elasticity;
pub mod embedded;
pub mod fick;
pub mod flux;
pub mod frame;
pub mod frame3d;
pub mod heat_conduction;
pub mod interface_transfer;
pub mod kernel;
pub mod mpc;
pub mod plasticity;
pub mod radiation;
pub mod shell;
pub mod symmetry;
pub mod tensor;
pub mod timoshenko;
pub mod transfer;
pub mod truss;
pub use kernel::CellGeom;
/// The kind of element matrix a physics contributes — the discriminant that
/// makes the whole assembly pipeline (recipe → scatter → per-kind pattern cache)
/// matrix-agnostic. One `assemble_*` entry point per variant
/// ([`crate::ops::matrix`]) drives the **same** machinery with a different
/// per-element kernel; a physics that has no term for a given kind contributes
/// nothing (its [`matrix_layout`](SubModelKind::matrix_layout) returns `None`).
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // Four matrix kinds and **one single** machinery: the per-element kernel
/// // differs, everything else is shared. A physics with no term for a kind
/// // contributes nothing to it.
/// assert_eq!(MatrixKind::COUNT, 4);
/// assert_eq!(MatrixKind::Stiffness.index(), 0);
/// assert!(volume.as_kind().matrix_layout(MatrixKind::Stiffness).is_some());
/// // A constraint has no matrix layout: it goes through `contributions`, not
/// // through an element kernel.
/// assert!(appui.as_kind().matrix_layout(MatrixKind::Stiffness).is_none());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MatrixKind {
/// Stiffness / conductivity `K` — `∫ Bᵀ D B` (Cast3M `RIGI` / `COND`).
#[default]
Stiffness,
/// Mass / capacity `M` — `∫ ρ Nᵀ N` (Cast3M `MASS` / `CAPA`).
Mass,
/// Geometric (initial-stress) stiffness `K_g` — `∫ Gᵀ σ̂ G` (Cast3M `KSIG`).
Geometric,
/// Consistent tangent `K_t` — `∫ Bᵀ D_alg B` (Cast3M `KTAN`).
Tangent,
}
impl MatrixKind {
/// Number of variants — the width of the per-kind pattern cache.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // Four matrix kinds and **one single** machinery: the per-element kernel
/// // differs, everything else is shared. A physics with no term for a kind
/// // contributes nothing to it.
/// assert_eq!(MatrixKind::COUNT, 4);
/// assert_eq!(MatrixKind::Stiffness.index(), 0);
/// assert!(volume.as_kind().matrix_layout(MatrixKind::Stiffness).is_some());
/// // A constraint has no matrix layout: it goes through `contributions`, not
/// // through an element kernel.
/// assert!(appui.as_kind().matrix_layout(MatrixKind::Stiffness).is_none());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub const COUNT: usize = 4;
/// Dense index in `0..COUNT`, for indexing per-kind caches.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // The index serves as the rank in the pattern cache, one per kind.
/// assert!(MatrixKind::Stiffness.index() < MatrixKind::COUNT);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub const fn index(self) -> usize {
self as usize
}
}
/// How a physics obtains its consistent tangent — a property of the **law**,
/// declared once, not re-derived at every Gauss point.
///
/// Purely **informative**: nothing branches on it. The guard against paying for
/// a tangent is having to call [`crate::ops::matrix::tangent`] at all. What this
/// buys is that a caller can know the price *before* paying it — a Newton loop
/// facing a `Numerical` law may legitimately prefer the elastic stiffness as its
/// iteration operator.
///
/// ```
/// # use pyrucast::models::TangentSource;
/// # use pyrucast::models::plasticity::law::PlasticLaw;
/// // Only two laws have a closed form; the others derive the radial return by
/// // central differences — twelve return maps per Gauss point.
/// assert_eq!(PlasticLaw::Perfect.tangent_source(), TangentSource::Analytic);
/// assert_eq!(PlasticLaw::Gurson.tangent_source(), TangentSource::Numerical);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TangentSource {
/// Closed form: a few dozen operations.
Analytic,
/// Central differences on the return map: **twelve return maps per Gauss
/// point**.
Numerical,
}
/// Structural declaration a volumetric physics gives so the **global**
/// assembler ([`crate::ops::matrix::stiffness`]) can build its stiffness
/// contribution as a *computed* [`SubMatrix`] — a recipe, no eagerly
/// materialised values — and scatter it straight into the global CSR.
///
/// Every field mirrors, one-for-one, what the physics'
/// [`build_stiffness_blocks`](SubModelKind::build_stiffness_blocks) would pass to
/// [`kernel::assemble_block`]. The
/// literal `build_stiffness_blocks` is **kept** alongside it as the bit-for-bit
/// equivalence reference. Volumetric blocks are square on a single support, so
/// one [`SubMesh`] gives both the row and column node sequence.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::containers::matrix::Symmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // The **structural** declaration of a volumetric physics: enough to build
/// // a *computed* block and pour it straight into the global CSR. Each field
/// // mirrors one argument of `assemble_block`.
/// let l = volume.as_kind().matrix_layout(MatrixKind::Stiffness).unwrap();
/// assert_eq!(l.dual_vars, vec!["q".to_string()]);
/// assert_eq!(l.primal_vars, vec!["T".to_string()]);
/// // A standard Galerkin form is symmetric on its own.
/// assert_eq!(l.symmetry, Symmetry::Full);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub struct MatrixLayout {
/// FE subspaces the element kernel integrates over. **Give a `Vec`**: a
/// single subspace for a plain volumetric physics, or several — sharing one
/// submesh, differing only by quadrature — for a multi-quadrature element
/// (a shear-deformable beam, a shell). The primary (index 0) drives the cell
/// loop and the DOF numbering; [`element_matrix`](Domain::element_matrix)
/// receives one [`CellGeom`] per subspace, in this order.
pub fespaces: Vec<Handle<SubFiniteElementSpace>>,
/// POI1 sub-mesh giving the block's row **and** column node sequence.
pub support: Handle<SubMesh>,
/// Row variable names (dual).
pub dual_vars: Vec<String>,
/// Column variable names (primal).
pub primal_vars: Vec<String>,
/// `(node_local, var)` ↔ matrix-index ordering.
pub ordering: DofOrdering,
/// What share of the matrix's symmetry the block carries — **declared** by
/// the physics, believed without verification. A standard Galerkin bilinear
/// form is [`Symmetry::Full`]; see [`Symmetry`] for what the other shares
/// mean and who may claim them.
pub symmetry: Symmetry,
}
/// One stiffness contribution of a sub-model, as handed to the global
/// assembler ([`crate::ops::matrix::stiffness`]).
///
/// A sub-model declares *how* each of its blocks is produced without the
/// assembler needing to know its concrete type: it just iterates
/// [`SubModelKind::contributions`] and folds each variant in. This is the seam that
/// keeps `Dirichlet`, a volumetric physics, and (later) a coupling/contact
/// sub-model on one uniform path — the discriminant is the variant, not a
/// per-type `match` in the assembler.
///
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// # use pyrucast::models::Contribution;
/// // The discriminant that puts a constraint, a volumetric physics and a
/// // coupling on one single path: the variant decides, not a per-type
/// // `match` in the assembler.
/// let c = appui.as_kind().contributions(MatrixKind::Stiffness, None)?;
/// assert!(!c.is_empty());
/// // A support brings **literal** blocks; a volumetric physics, a computed
/// // recipe.
/// assert!(matches!(c[0], Contribution::Literal(_)));
/// assert!(matches!(
/// volume.as_kind().contributions(MatrixKind::Stiffness, None)?[0],
/// Contribution::Computed(_)));
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub enum Contribution {
/// A block integrated on the fly and scattered straight into the global CSR
/// (no values materialised): the fast path of every volumetric physics. The
/// assembler resolves the material and wraps this
/// [`MatrixLayout`] into a computed [`SubMatrix`].
Computed(MatrixLayout),
/// One-or-more blocks whose values the sub-model has already filled in
/// (`Dirichlet`'s C / Cᵀ, MPC, …). Scattered by the literal path.
Literal(Vec<SubMatrix>),
/// An **off-diagonal** block coupling two distinct meshes — integrated on the
/// fly like [`Computed`](Self::Computed), but with its rows on one mesh and
/// its columns on another (an interface exchange law, `h(c₁ − c₂)`).
///
/// Everything below this seam was already row/col-asymmetric —
/// [`SubMatrix::computed`](crate::containers::matrix::SubMatrix::computed)
/// takes both supports, and so do the scatter and the kernel drivers. Only
/// [`MatrixLayout`] collapsed them into one field, which is why this is a
/// separate layout rather than an extra field there: adding one would have
/// touched every existing physics for a need none of them has.
Coupling(CouplingLayout),
}
/// One sub-model's declaration of a term of the residual — the nodal twin of
/// [`Contribution`], and the same idea: a **recipe**, never an assembled
/// container. [`crate::ops::node_field::internal_forces()`] and
/// [`crate::ops::node_field::external_forces()`] consume it exactly as
/// [`crate::ops::matrix::assemble_kind`] consumes a `Contribution` — they
/// resolve what the term reads, run the machinery, and gather the result.
///
/// That split is what keeps the declaration total: a sub-model that resolves
/// nothing cannot fail, and the one `Result` of the whole path sits on the
/// operator, where a caller can act on it.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::SubModel;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{ResidualContribution, SubModelKind};
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let volume = SubModel::heat_conduction(zone, MaterialSymmetry::Isotropic).unwrap();
/// // A physics that integrates a law declares a computed recipe, on its own
/// // layout — never the field, which the operator will produce.
/// let declare = volume.as_kind().internal_force_contribution();
/// assert!(matches!(declare[..], [ResidualContribution::Computed(_)]));
/// ```
pub enum ResidualContribution {
/// A term integrated on the fly and scattered to the nodes: the fast path
/// of every physics whose term is an integral. The layout is the sub-model's
/// own (its stiffness layout for `∫ Bᵀ σ`), and the per-cell kernel is
/// [`SubModelKind::internal_force_element`].
Computed(MatrixLayout),
/// A field the sub-model has already filled in — a hand-made load. The twin
/// of [`Contribution::Literal`].
Literal(NodeField),
/// The terms of a **constraint**: apply its [`Constraint::relations`] to the
/// current solution. On the internal side that is the force `Cᵀ λ`, the
/// opposite of the reaction, spread over the constrained nodes — term `k`
/// carrying `aₖ·λ` into the
/// dual row of its own variable — plus `C·u` on the constraint's own row.
///
/// It is a variant rather than a `Literal` because the declaration is total:
/// a sub-model that has not seen the solution cannot have filled a field
/// with it.
Relations,
}
/// Structural declaration of an **inter-mesh** block: rows integrated on one
/// mesh, columns on another, paired cell by cell.
///
/// The two sides must be **conforming** — same element type, same cell count,
/// cell `i` of one facing cell `i` of the other. That is checked when the block
/// is built, and reported rather than approximated: a non-matching interface is
/// a meshing problem, not something an assembler should paper over.
// ANCHOR: coupling_layout
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::containers::matrix::Symmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// # use pyrucast::containers::matrix::DofOrdering;
/// # use pyrucast::models::CouplingLayout;
/// // What an **interface** law describes: row *and* column subspaces, on
/// // two facing meshes, where a [`MatrixLayout`] holds on a single
/// // support. Conformity is checked when the block is built, and
/// // **reported** rather than approximated: an interface that does not
/// // match is a meshing problem.
/// let l = CouplingLayout {
/// fespaces: vec![zone.clone()],
/// col_fespaces: vec![zone.clone()],
/// row_support: zone.read().submesh().read().to_poi1()?,
/// col_support: zone.read().submesh().read().to_poi1()?,
/// dual_vars: vec!["q".into()],
/// primal_vars: vec!["T".into()],
/// ordering: DofOrdering::NodesThenVars,
/// // An inter-mesh block is never symmetric alone; a real exchange law
/// // declares its two off-diagonal blocks a `Half` pair instead.
/// symmetry: Symmetry::None,
/// };
/// assert_eq!(l.fespaces.len(), l.col_fespaces.len());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub struct CouplingLayout {
/// FE subspaces carrying the **rows** (the primary drives the cell loop).
pub fespaces: Vec<Handle<SubFiniteElementSpace>>,
/// FE subspaces carrying the **columns**, on the facing mesh.
pub col_fespaces: Vec<Handle<SubFiniteElementSpace>>,
/// POI1 sub-mesh giving the block's row node sequence.
pub row_support: Handle<SubMesh>,
/// POI1 sub-mesh giving the block's column node sequence.
pub col_support: Handle<SubMesh>,
/// Row variable names (dual).
pub dual_vars: Vec<String>,
/// Column variable names (primal).
pub primal_vars: Vec<String>,
/// `(node_local, var)` ↔ matrix-index ordering.
pub ordering: DofOrdering,
/// What share of the matrix's symmetry the block carries. An inter-mesh
/// block is never symmetric alone — its rows and columns live on facing
/// meshes — so an exchange law declares its two off-diagonal blocks a
/// [`Symmetry::Half`] pair, exactly as a constraint declares `C` and `Cᵀ`.
pub symmetry: Symmetry,
}
// ANCHOR_END: coupling_layout
/// The **nature** of a physics — its coarse classification, orthogonal to the
/// `Domain` / `Constraint` capability axis. It answers "which field of physics"
/// where the capability seams answer "domain or constraint".
///
/// A physics declares a **set** of natures (usually one): a plain physics is
/// single-natured, a coupled physics (e.g. a future thermo-mechanical element)
/// spans several, and a block that belongs to none is left **untagged** (an empty
/// set — the "nothing" case for hand-built / other matrices). [`Other`](Self::Other)
/// is the explicit odd-one-out nature, for a block one *wants* classified as
/// "other" rather than merely untagged.
///
/// A single nature is fully determined by the
/// [`SubModel`](crate::containers::model::SubModel) variant, so
/// [`SubModelKind::physics`] returns a per-physics **constant** slice (like
/// [`label`](SubModelKind::label)) rather than a stored field. The set travels
/// with each assembled block onto the [`SubMatrix`], and feeds the
/// [`Model::filter`](crate::containers::model::Model::filter) /
/// [`Matrix::filter`](crate::containers::matrix::Matrix::filter) selectors
/// (which match by **containment**).
///
/// ```
/// # use pyrucast::models::Physics;
/// // A sub-model's nature travels with every assembled block: it is what
/// // `Model::filter` and `Matrix::filter` read.
/// assert_eq!(Physics::ALL.len(), 6);
/// // Diffusion and thermal are **distinct** despite their common Laplacian:
/// // a coupled problem must be able to select one without the other.
/// assert_ne!(Physics::Diffusion, Physics::Thermal);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Physics {
/// Solid mechanics — elasticity, plasticity, damage, bars, beams, frames.
Mechanical,
/// Heat transfer — conduction, and radiation alongside
/// [`Radiation`](Self::Radiation).
Thermal,
/// A Lagrange constraint — Dirichlet, MPC, embedded, contact.
Constraint,
/// "Other / nothing" — a nature for a block that fits none of the above but is
/// still explicitly classified (as opposed to simply untagged).
Other,
/// Mass transport — Fickian diffusion and its interface laws. Distinct from
/// [`Thermal`](Self::Thermal) despite sharing the Laplacian: the variables
/// are a concentration and a mass flux, not a temperature and a heat flux,
/// and a coupled problem must be able to select one without the other.
Diffusion,
/// Radiative exchange. Carried **in addition to**
/// [`Thermal`](Self::Thermal) by a radiation sub-model — so it stays part of
/// a thermal assembly, while `filter("radiation")` isolates the non-linear
/// boundary term on its own.
Radiation,
}
impl Physics {
/// The lowercase name of this nature (the inverse of
/// [`from_name`](crate::named::Named::from_name)).
///
/// ```
/// # use pyrucast::models::Physics;
/// # use pyrucast::named::Named;
/// // Exact inverse of `from_name`, for the six natures.
/// assert!(Physics::ALL.iter().all(|p| Physics::from_name(p.name()) == Some(*p)));
/// ```
pub fn name(self) -> &'static str {
match self {
Self::Mechanical => "mechanical",
Self::Thermal => "thermal",
Self::Constraint => "constraint",
Self::Other => "other",
Self::Diffusion => "diffusion",
Self::Radiation => "radiation",
}
}
/// Every nature, in declaration order — the single source for the tag list
/// quoted in the `filter` error messages, so a new nature cannot be added
/// without the messages following.
///
/// ```
/// # use pyrucast::models::Physics;
/// // The single source of the list quoted by the `filter` messages: a
/// // nature cannot be added without the messages following.
/// assert!(Physics::ALL.contains(&Physics::Radiation));
/// ```
pub const ALL: [Physics; 6] = [
Self::Mechanical,
Self::Thermal,
Self::Constraint,
Self::Other,
Self::Diffusion,
Self::Radiation,
];
}
impl crate::named::Named for Physics {
const LABEL: &'static str = "physics";
const VALUES: &'static [Self] = &Self::ALL;
fn name(self) -> &'static str {
Physics::name(self)
}
}
impl std::fmt::Display for Physics {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
/// The behaviour contract of one physics, co-located with its data struct.
///
/// Generic code calls these through
/// [`SubModel::as_kind`](crate::containers::model::SubModel::as_kind);
/// the [`SubModel`](crate::containers::model::SubModel) enum itself carries
/// no logic. Most methods have sensible defaults so a physics overrides
/// only what is specific to it (a plain domain physics typically implements
/// `primal_vars`, `dual_vars`, `as_domain` + the [`Domain`] capability,
/// `element_matrix`, `stiffness_layout`, `label` and `render`).
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // The base contract, with defaults wherever possible: a physics writes
/// // only what is its own. **All** of the model layer goes through it,
/// // `as_kind` being the single `match`.
/// let k = volume.as_kind();
/// assert_eq!(k.primal_vars(), vec!["T".to_string()]);
/// assert!(k.as_domain().is_some()); // a volumetric physics
/// assert!(k.as_constraint().is_none());
/// // And the other way round for a support: it is a **compile-time** fact,
/// // not a run-time error.
/// assert!(appui.as_kind().as_domain().is_none());
/// assert!(appui.as_kind().as_constraint().is_some());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub trait SubModelKind: Sync {
/// Primal variable names introduced by this physics (column labels).
fn primal_vars(&self) -> Vec<String>;
/// Dual variable names introduced by this physics (row labels).
fn dual_vars(&self) -> Vec<String>;
/// This physics' set of [`Physics`] natures — a per-variant **constant**
/// slice, the classification counterpart of [`label`](Self::label). A plain
/// physics returns a single-element slice; a coupled physics returns several.
/// Required so every physics declares its nature(s) explicitly at its
/// definition site. Matched by containment in the `filter` selectors.
fn physics(&self) -> &'static [Physics];
/// Borrow this sub-model as a [`Domain`] capability, or `None` (default) if
/// it is not a domain physics (a constraint such as `Dirichlet`). A domain
/// overrides this to return `Some(self)`. This is the seam the assembler,
/// the material builders and [`crate::ops::element_field::behavior`] use — they never
/// assume every sub-model reads material or integrates a behaviour.
fn as_domain(&self) -> Option<&dyn Domain> {
None
}
/// Borrow this sub-model as a [`Constraint`] capability, or `None`
/// (default) if it imposes no Lagrange constraint (every plain volumetric
/// physics). A constraint (`Dirichlet`, later MPC / strong contact)
/// overrides this to return `Some(self)`. This is the seam the multiplier
/// forwarders on [`SubModel`](crate::containers::model::SubModel) use — they
/// never assume every sub-model carries multipliers.
fn as_constraint(&self) -> Option<&dyn Constraint> {
None
}
/// Borrow this sub-model as a [`Behavior`] capability, or `None` (default)
/// if it integrates no constitutive law. A physics with a law overrides this
/// to return `Some(self)`.
///
/// This is the second half of what [`as_domain`](Self::as_domain) used to
/// lock in one gesture. A physics can now say *I integrate on a subspace,
/// with material* without also claiming *and I have a law* — which is what
/// a boundary transfer needed, and what it had to fake.
fn as_behavior(&self) -> Option<&dyn Behavior> {
None
}
/// Dispatch the per-cell element kernel for `kind` — the single seam the
/// global assembler drives (via a [`ComputedRecipe`](crate::containers::matrix::ComputedRecipe)),
/// routing to [`element_matrix`](Domain::element_matrix) /
/// [`element_mass`](Domain::element_mass) /
/// [`element_geometric`](Domain::element_geometric) /
/// [`element_tangent`](Behavior::element_tangent). `state` is `Some(_)` only for
/// the kinds that consume the current stress/tangent field (geometric,
/// tangent); the others ignore it.
#[allow(clippy::too_many_arguments)]
fn matrix_element(
&self,
kind: MatrixKind,
geoms: &[CellGeom],
material: &SubElementField,
lay: &ElementLayout,
inputs: &KernelState,
ke: &mut [f64],
) -> Result<()> {
// The **one** bridge between the base contract and the element kernels,
// which live on `Domain`: only a physics that produces a matrix has
// them, and only such a physics declares a material FE subspace.
let domain = self.as_domain().ok_or_else(|| {
PyrucastError::Message(format!(
"{}: no element kernel — this sub-model declares no Domain",
self.label()
))
})?;
// The kind and its inputs are **paired by construction**: a mismatch can
// only come from a hand-built recipe, and it is named here rather than
// in every kernel.
match (kind, inputs) {
(MatrixKind::Stiffness, _) => domain.element_matrix(geoms, material, lay, ke),
(MatrixKind::Mass, _) => domain.element_mass(geoms, material, lay, ke),
(MatrixKind::Geometric, KernelState::State(state)) => {
domain.element_geometric(geoms, material, lay, state, ke)
}
(
MatrixKind::Tangent,
KernelState::Behavior {
lay: zone,
deformation,
prev,
dt,
},
) => {
// The consistent tangent is the derivative of the law's step:
// a physics without a law has none, and its tangent *is* its
// stiffness.
let behavior = self.as_behavior().ok_or_else(|| {
PyrucastError::Message(format!(
"{}: no consistent tangent — this sub-model integrates no law",
self.label()
))
})?;
behavior.element_tangent(geoms, zone, deformation, prev, material, *dt, ke)
}
(kind, _) => Err(PyrucastError::Message(format!(
"{}: the {kind:?} matrix was given the wrong inputs",
self.label()
))),
}
}
/// This sub-model's contributions of a given [`MatrixKind`], as the global
/// assembler consumes them. **Default**: derived from
/// [`matrix_layout`](Self::matrix_layout) — `Some(layout)` yields a single
/// [`Contribution::Computed`] (a volumetric physics, integrated straight
/// into the CSR); `None` falls back — **only for `Stiffness`** — to a
/// [`Contribution::Literal`] built from
/// [`build_stiffness_blocks`](Self::build_stiffness_blocks), errors for
/// `Tangent` (a physics with no tangent kernel that has not declared
/// [`tangent_is_stiffness`](Self::tangent_is_stiffness), which the
/// assembler resolves before asking), and yields nothing for the other
/// kinds (a physics with no term for that kind).
///
/// A volumetric physics writes only its per-kind `element_*` + `*_layout`
/// and takes the default. A sub-model whose blocks are *not* a single
/// layout-driven integral (a constraint such as `Dirichlet`, which only
/// contributes to `Stiffness`) overrides **this** method — that override is
/// the extension seam, not a special case buried in the assembler.
///
/// `material` is `Some(_)` iff [`Domain::material_fespace`] is declared
/// (the assembler guarantees it); it is only consulted on the literal path —
/// the computed path resolves material itself from the layout.
fn contributions(
&self,
kind: MatrixKind,
material: Option<&Handle<SubElementField>>,
) -> Result<Vec<Contribution>> {
Ok(match self.matrix_layout(kind) {
Some(layout) => vec![Contribution::Computed(layout)],
// Here the `Option` earns its keep: a **constraint** sub-model has
// no material at all, and that is what distinguishes it from a
// domain. Below this line the question is settled.
None if kind == MatrixKind::Stiffness => {
let material = material.ok_or_else(|| {
PyrucastError::Message(format!(
"{}: a stiffness assembled cell by cell needs material data",
self.label()
))
})?;
vec![Contribution::Literal(
self.build_stiffness_blocks(material)?,
)]
}
None if kind == MatrixKind::Tangent => {
return Err(PyrucastError::Message(format!(
"{}: no consistent tangent — this physics has no tangent kernel \
and does not declare its tangent to be its stiffness",
self.label()
)))
}
None => Vec::new(),
})
}
/// Build and fill the stiffness [`SubMatrix`] block(s) of this physics.
/// `material` is `Some(_)` iff [`Domain::material_fespace`] is declared
/// (the assembler guarantees it).
///
/// **Default**: derived from [`stiffness_layout`](Self::stiffness_layout) —
/// a single block on that layout, filled by
/// [`element_matrix`](Domain::element_matrix) via [`kernel::assemble_block`].
/// A plain volumetric physics therefore writes only `element_matrix` +
/// `stiffness_layout` and gets this for free; this literal path serves as
/// the bit-for-bit reference of the computed (scatter) path. A sub-model
/// with **no** layout does not touch this method — it overrides
/// [`contributions`](Self::contributions) instead (see `Dirichlet`).
fn build_stiffness_blocks(&self, material: &Handle<SubElementField>) -> Result<Vec<SubMatrix>> {
let Some(layout) = self.stiffness_layout() else {
return Err(PyrucastError::Message(format!(
"{}: build_stiffness_blocks has no default without a \
stiffness_layout — override it (e.g. a constraint such as \
Dirichlet, or a multi-block physics)",
self.label()
)));
};
let domain = self.as_domain().ok_or_else(|| {
PyrucastError::Message(format!(
"{}: no element kernel — this sub-model declares no Domain",
self.label()
))
})?;
// Resolved once for the zone, before the parallel region: the closure
// below captures the table, so no cell ever matches a component name.
let lay = domain.element_layout(MatrixKind::Stiffness, &material.read(), None)?;
let block = kernel::assemble_block(
&layout.fespaces,
&layout.support,
&layout.support,
layout.dual_vars,
layout.primal_vars,
layout.ordering,
layout.symmetry,
material,
None,
|geoms, m, _state, ke| domain.element_matrix(geoms, m, &lay, ke),
)?;
Ok(vec![block])
}
/// Structural layout of this physics' stiffness block, or `None` (default)
/// for a physics assembled the literal way (constraints such as `Dirichlet`,
/// or any multi-block physics). When `Some`, it drives **both** paths from a
/// single description: the global assembler
/// ([`crate::ops::matrix::stiffness`]) builds a *computed*
/// [`SubMatrix`] and scatters [`element_matrix`](Domain::element_matrix)
/// straight into the CSR (never materialising values), and the default
/// [`build_stiffness_blocks`](Self::build_stiffness_blocks) produces the
/// *literal* equivalent from the same layout + kernel.
fn stiffness_layout(&self) -> Option<MatrixLayout> {
None
}
/// Structural layout of this physics' **mass / capacity** block, or `None`
/// (default: no mass term). A continuum physics returns the same layout as
/// its stiffness (same fespaces / support / vars) — only the kernel differs.
fn mass_layout(&self) -> Option<MatrixLayout> {
None
}
/// Structural layout of this physics' **geometric-stiffness** block, or
/// `None` (default: none).
fn geometric_layout(&self) -> Option<MatrixLayout> {
None
}
/// Structural layout of this physics' **consistent-tangent** block, or
/// `None` (default: none).
fn tangent_layout(&self) -> Option<MatrixLayout> {
None
}
/// Whether this sub-model's consistent tangent **is** its stiffness: true of
/// a linear physics that has no tangent kernel of its own (conduction,
/// Fick, bars, beams, shells, boundary exchange) and of the constraints,
/// whose relations are linear in the unknowns. A `Tangent` request then
/// assembles this sub-model's [`Stiffness`](MatrixKind::Stiffness) — exact,
/// not an approximation.
///
/// Default `false`. A physics that declares neither this nor a
/// [`tangent_layout`](Self::tangent_layout) makes the tangent an
/// **error**: a silent zero block would make Newton fail far from the cause.
fn tangent_is_stiffness(&self) -> bool {
false
}
/// Dispatch to the per-kind layout ([`stiffness_layout`](Self::stiffness_layout)
/// / [`mass_layout`](Self::mass_layout) /
/// [`geometric_layout`](Self::geometric_layout) /
/// [`tangent_layout`](Self::tangent_layout)). This is the seam
/// [`contributions`](Self::contributions) and the global assembler drive; a
/// physics implements the per-kind primitives, not this dispatcher.
fn matrix_layout(&self, kind: MatrixKind) -> Option<MatrixLayout> {
match kind {
MatrixKind::Stiffness => self.stiffness_layout(),
MatrixKind::Mass => self.mass_layout(),
MatrixKind::Geometric => self.geometric_layout(),
MatrixKind::Tangent => self.tangent_layout(),
}
}
/// Local internal-force vector of one cell — the pure, sequential kernel
/// that applies `Bᵀ` to the stress (Cast3m `BSIG`). It is the **transpose**
/// of this physics' deformation operator `B` (the same `B` behind its
/// [`crate::ops::element_field::deformation`](fn@crate::ops::element_field::deformation) /
/// [`crate::ops::element_field::beam_deformation`](fn@crate::ops::element_field::beam_deformation)),
/// so it mirrors [`Behavior::integrate_point`]'s producer.
///
/// Fills `fe` — the cell's local force vector, node-major / variable-minor
/// (`fe[li * n_dual + di]`, `di` indexing [`dual_vars`](Self::dual_vars)) —
/// from the cell geometry and the `stress` (the [`Behavior::integrate_point`]
/// output) borrowed in place. `geoms` holds one [`CellGeom`] per FE subspace
/// of [`stiffness_layout`](Self::stiffness_layout), in that order.
///
/// **Default**: the continuum-mechanics `f_{i,a} = Σ_g Σ_b (∂N_i/∂x_b) σ_ab`
/// — one [`crate::ops::node_field::divergence`](fn@crate::ops::node_field::divergence)
/// per row of the symmetric stress tensor `σ`, read in Voigt naming
/// (`sigma_xx`, `sigma_xy`, …). A displacement physics (elasticity, Mazars,
/// plasticity) gets it for free; a physics whose dual is not a displacement
/// vector (heat, bar, beam) overrides it.
/// Components this internal-force kernel reads from the state field, in the
/// slot order its indices assume — the counterpart of
/// [`Behavior::deformation_reads`] on the `Bᵀσ` side.
///
/// Default: the continuum stress tensor, plus the hoop `σ_θθ` on a body of
/// revolution, matching the default kernel below. A law reading a
/// large-transformation measure is answered on the reference configuration
/// instead, by the whole first Piola–Kirchhoff `P = F S` (`P_xx, P_xy, …`,
/// hoop `P_zz`) — prepared by
/// [`stress_measure`](fn@crate::ops::element_field::stress_measure), since
/// neither `S` nor `T` is what `Bᵀ` applies to there.
fn internal_force_reads(&self) -> Vec<String> {
let Some(layout) = self.stiffness_layout() else {
return Vec::new();
};
let space_dim = layout.fespaces[0].read().space_dim();
let (mut names, prefix) = if reads_finite_strain(self) {
(
continuum::internal_force::full_matrix_reads("P", space_dim),
"P",
)
} else {
(
continuum::internal_force::voigt_matrix_reads("sigma", space_dim),
"sigma",
)
};
if layout.fespaces[0].read().is_axisymmetric() {
names.push(format!("{prefix}_zz"));
}
names
}
fn internal_force_element(
&self,
geoms: &[CellGeom],
stress: &SubElementField,
lay: &[u32],
_material: &SubElementField,
_mat: &[u32],
fe: &mut [f64],
) -> Result<()> {
if reads_finite_strain(self) {
continuum::internal_force::continuum_internal_force_element_full(geoms, stress, lay, fe)
} else {
continuum::internal_force::continuum_internal_force_element(geoms, stress, lay, fe)
}
}
/// What this term applies its `Bᵀ` to, at the points of `fespace` — read
/// when the sub-model has no constitutive law to produce a state.
///
/// **Default**: the primal itself, interpolated there. That is what a
/// boundary transfer reads — its `∫ h·a·N` needs `a`, not a stress. An
/// interface reads a **jump** across two conforming sides, which is neither
/// a state nor a single interpolation, and overrides this.
///
/// The seam exists because the operator cannot guess: it knows how to
/// resolve a state from a behaviour, and how to interpolate a primal, but
/// what a term reads is the term's own business.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::field::SubField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::SubModel;
/// # use pyrucast::containers::node_field::NodeField;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Physics, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm))?;
/// # let zone = fes.get(0)?;
/// # let support = mesh::poi1_from_nodes(&n)?;
/// # let mut u = NodeField::from_submesh(&support.get(0)?, vec!["T".into()])?;
/// # u.get(0)?.write().set_uniform("T", 3.0)?;
/// # let conduction = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
/// # let bord = SubModel::boundary_transfer(
/// # zone.clone(), &conduction, vec!["T".into()])?;
/// // A boundary transfer reads the primal at the points, not a state: its
/// // value there is the field's, interpolated.
/// let lu = bord.as_kind().residual_input(&zone, &u)?;
/// assert_eq!(lu.read().components(), &["T".to_string()]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
fn residual_input(
&self,
fespace: &Handle<SubFiniteElementSpace>,
solution: &NodeField,
) -> Result<Handle<SubElementField>> {
let mut one = crate::containers::finite_element_space::FiniteElementSpace::empty();
one.add_sub(fespace.clone())?;
crate::ops::element_field::interp_to_gauss(solution, &one)?.get(0)
}
/// This sub-model's contributions to the **internal** side of the balance
/// `Σ f_int = Σ f_ext` — empty when it has no term there.
///
/// The nodal twin of [`contributions`](Self::contributions), and it works
/// the same way: a sub-model declares a **recipe**, never an assembled
/// container. [`crate::ops::node_field::internal_forces()`] resolves the
/// state zone, drives the kernel and gathers the field, exactly as
/// [`crate::ops::matrix::assemble_kind`] resolves the material, drives the
/// block and gathers the matrix. Nothing here can fail, because nothing
/// here is resolved.
///
/// With [`external_force_contribution`](Self::external_force_contribution)
/// the pair yields `r` itself, where `contributions` yields the blocks of
/// `∂r/∂u`. The residual is the gap between the two sums, so **no physics
/// ever writes a sign**: an author places their term on one side of the
/// equals sign or the other, which is a question of physics, and the single
/// subtraction lives in the caller.
///
/// **Default**: one [`ResidualContribution::Computed`] on the stiffness
/// layout for a sub-model that integrates a law — the `∫ Bᵀ σ` whose kernel
/// is [`internal_force_element`](Self::internal_force_element). A
/// constraint, having no such layout, declares nothing.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::SubModel;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{RelationSense, ResidualContribution, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// # let volume = SubModel::heat_conduction(zone, MaterialSymmetry::Isotropic).unwrap();
/// // A volumetric physics declares its integral; a support declares its
/// // relations, from which the operator draws the reaction.
/// assert!(matches!(volume.as_kind().internal_force_contribution()[..],
/// [ResidualContribution::Computed(_)]));
/// assert!(matches!(appui.as_kind().internal_force_contribution()[..],
/// [ResidualContribution::Relations]));
/// ```
fn internal_force_contribution(&self) -> Vec<ResidualContribution> {
match (self.as_domain(), self.stiffness_layout()) {
(Some(_), Some(layout)) => vec![ResidualContribution::Computed(layout)],
_ => Vec::new(),
}
}
/// Local **external** force vector of one cell — the per-cell kernel of an
/// integrated given term, `∫ N φ dΩ`. The counterpart of
/// [`internal_force_element`](Self::internal_force_element) on the other
/// side of the equals sign, and it reads the **material**, where the given
/// density lives, rather than a state.
///
/// Fills `fe` node-major / variable-minor, like its twin. Default errors:
/// only a physics that declares a
/// [`ResidualContribution::Computed`] on the external side ever reaches it.
fn external_force_element(
&self,
_geoms: &[CellGeom],
_material: &SubElementField,
_lay: &ElementLayout,
_fe: &mut [f64],
) -> Result<()> {
Err(PyrucastError::Message(format!(
"{}: no external kernel — external_force_element is undefined for this physics",
self.label()
)))
}
/// This sub-model's contributions to the **external** side of
/// `Σ f_int = Σ f_ext` — the given data of its terms, on the right of the
/// equals sign — empty when it has none.
///
/// **Default**: nothing. A physics whose term is entirely a response to `u`
/// (elasticity, conduction, a bar) declares none; the ambient of a boundary
/// transfer and a distributed flux load will declare one.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::SubModel;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::SubModelKind;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let volume = SubModel::heat_conduction(zone, MaterialSymmetry::Isotropic).unwrap();
/// // Conduction only responds to `u`: nothing on the right of the equals sign.
/// assert!(volume.as_kind().external_force_contribution().is_empty());
/// ```
fn external_force_contribution(&self) -> Vec<ResidualContribution> {
Vec::new()
}
/// Short type label, e.g. `"HeatConduction"` (used by `Debug` and the
/// default `display`).
fn label(&self) -> &'static str;
/// One-line summary for `Display`. Default: `SubModel<{label}>`.
fn display(&self) -> String {
format!("SubModel<{}>", self.label())
}
/// Full multi-line rendering for [`crate::dump::Dump`].
fn render(&self, opts: &DumpOptions) -> String;
}
/// A sub-model that imposes a **Lagrange constraint** — an optional capability,
/// not part of the base [`SubModelKind`] contract. A constraint implements it
/// *and* returns `Some(self)` from [`SubModelKind::as_constraint`]; a plain
/// volumetric physics implements neither, so it simply has no multipliers.
///
/// This is the seam of the constraint family — `Dirichlet` today, MPC and strong
/// contact later — and the natural home for the multiplier-driven logic they
/// share (e.g. the future condensation of the multiplier DOFs).
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // The **constraint** capability: relations, each with its multiplier node
/// // and the component its right-hand side is written into.
/// let c = appui.as_kind().as_constraint().unwrap();
/// let r = c.relations()?;
/// assert_eq!(r.len(), 1);
/// assert_eq!(r[0].terms.len(), 1);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub trait Constraint {
/// POI1 mesh carrying this constraint's multiplier nodes — one node per
/// relation, minted by the constraint itself. Borrowed from the sub-model;
/// generic code clones it when an owned [`Mesh`] is needed.
fn multiplier_mesh(&self) -> &Mesh;
/// The linear relations this constraint imposes, in a **method-neutral**
/// form: one [`Relation`] per multiplier node, each carrying its terms
/// `(node, variable, target_dual, coefficient)`. It is the single source of
/// truth the imposition methods consume — the Lagrange path
/// ([`SubModelKind::contributions`]) builds its `C` / `Cᵀ` blocks from the
/// same relations a future master/slave *elimination* will read, so neither
/// re-parses the user's mesh-per-term input.
fn relations(&self) -> Result<Vec<Relation>>;
}
/// One term of a linear constraint relation, carried **method-neutrally**:
/// `coefficient · u(node, variable)`. Its force `coefficient · λ`, the
/// opposite of its reaction, lands in `target_dual`, the dual (residual) row
/// of `variable` in its physics.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // One relation term: a node, its variable, and the dual of the targeted
/// // physics — the latter is what hooks the constraint onto the physics it
/// // constrains.
/// let r = appui.as_kind().as_constraint().unwrap().relations()?;
/// assert_eq!(r[0].terms[0].node, n[0].id());
/// assert_eq!(r[0].terms[0].variable, "T");
/// assert_eq!(r[0].terms[0].target_dual, "q");
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Debug)]
pub struct ConstraintTerm {
/// Constrained node (a column of the target physics' stiffness).
pub node: NodeId,
/// Constrained primal variable (e.g. `"u_x"`).
pub variable: String,
/// Dual row of `variable` where the reaction is injected (e.g. `"f_x"`).
pub target_dual: String,
/// Scalar coefficient `aₖ`.
pub coefficient: f64,
}
/// The sense of a constraint relation: an **equality** (the default, always
/// enforced) or a **unilateral inequality** solved by the active-set operator
/// [`solver::solve`](crate::ops::solver::solve).
///
/// The KKT conditions follow the sign convention of the existing Lagrange
/// blocks (`Cᵀ·λ` is *added* to the target's dual row):
///
/// - [`GreaterEqual`](Self::GreaterEqual): `C·u ≥ g`, `λ ≥ 0`, `λ·(C·u − g) = 0`;
/// - [`LessEqual`](Self::LessEqual): `C·u ≤ g`, `λ ≤ 0`, `λ·(C·u − g) = 0`.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // Equality, or inequality — what moves the constraint from the direct
/// // solver to the active set. The Python face takes the sense by its name,
/// // `"="` (the default), `">="` or `"<="`, and reads `≥` and `≤` as well.
/// # use pyrucast::named::Named;
/// assert_eq!(RelationSense::default(), RelationSense::Equality);
/// assert_eq!(RelationSense::parse(">=")?, RelationSense::GreaterEqual);
/// assert_eq!(RelationSense::parse("≤")?, RelationSense::LessEqual);
/// assert!(RelationSense::parse("≠").is_err());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum RelationSense {
/// `Σₖ aₖ·uₖ = g` — always enforced (both solve paths).
#[default]
Equality,
/// `Σₖ aₖ·uₖ ≥ g` — enforced only while active (multiplier `λ ≤ 0`, so
/// that the reaction `−λ` pushes).
GreaterEqual,
/// `Σₖ aₖ·uₖ ≤ g` — enforced only while active (multiplier `λ ≥ 0`, so
/// that the reaction `−λ` pushes).
LessEqual,
}
impl Named for RelationSense {
const LABEL: &'static str = "relation sense";
const VALUES: &'static [Self] = &[
RelationSense::Equality,
RelationSense::GreaterEqual,
RelationSense::LessEqual,
];
fn name(self) -> &'static str {
match self {
RelationSense::Equality => "=",
RelationSense::GreaterEqual => ">=",
RelationSense::LessEqual => "<=",
}
}
// The doubled equality of programming languages, and the mathematical
// symbols.
fn aliases() -> &'static [(&'static str, Self)] {
&[
("==", RelationSense::Equality),
("≥", RelationSense::GreaterEqual),
("≤", RelationSense::LessEqual),
]
}
}
impl std::fmt::Display for RelationSense {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
/// The primal every constraint relation owns: its Lagrange multiplier, on a
/// node of its own, whose solved value is the reaction.
///
/// One name for every constraint: once in the matrix, a relation is a
/// relation, whatever built it. Two relations never meet on one degree of
/// freedom since each has its own multiplier node.
///
/// ```
/// assert_eq!(pyrucast::models::MULTIPLIER, "lambda");
/// ```
pub const MULTIPLIER: &str = "lambda";
/// The dual every constraint relation owns: its equation row, and the slot,
/// on the relation's multiplier node, where the user writes its right-hand
/// side `g` in the load field — see
/// [`SubModel::constraint_rhs`](crate::containers::model::SubModel::constraint_rhs).
///
/// ```
/// assert_eq!(pyrucast::models::IMPOSED, "imposed");
/// ```
pub const IMPOSED: &str = "imposed";
/// One linear constraint relation `Σₖ coeffₖ · u(nodeₖ, varₖ) ⋈ g` (`⋈` is the
/// [`sense`](Self::sense) — `=` by default), enforced by a fresh
/// `multiplier_node` whose solved value is the multiplier `λ` — the
/// relation's reaction is `−λ` times its coefficients. The right-hand
/// side `g` is supplied by the user in the load field at the multiplier node's
/// [`IMPOSED`] component, so it is **not** carried here.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // One relation: its multiplier node, minted by the constraint, and its
/// // terms. It is the seam shared by every constraint.
/// let r = appui.as_kind().as_constraint().unwrap().relations()?;
/// assert_eq!(r[0].multiplier_node, appui.multiplier_mesh()?.node(0, 0, 0)?.id());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Debug)]
pub struct Relation {
/// The Lagrange-multiplier node that enforces this relation, its own.
pub multiplier_node: NodeId,
/// The terms summed on the left-hand side.
pub terms: Vec<ConstraintTerm>,
/// Equality (default) or unilateral inequality — read by the solvers only,
/// the Lagrange blocks are assembled identically either way.
pub sense: RelationSense,
}
/// Build the Lagrange `C` / `Cᵀ` block pair for **one** constraint term over one
/// paired submesh (multiplier ↔ constrained, one cell per relation, paired
/// element-for-element), every entry equal to `coefficient`:
///
/// - **`C`** — rows `(multiplier, IMPOSED)`, cols `(constrained, variable)`:
/// the constraint-equation row, which carries the relations' `sense`
/// ([`SubMatrix::row_sense`]) for the solver to read;
/// - **`Cᵀ`** — rows `(constrained, target_dual)`, cols `(multiplier, MULTIPLIER)`:
/// the reaction in the target's dual row.
///
/// Shared by [`dirichlet::Dirichlet`] (one term, `coefficient = 1`) and
/// [`mpc::Mpc`] (one call per term): the single place the saddle-point bordering
/// blocks are filled.
pub(crate) fn constraint_block_pair(
multiplier_sm: &Handle<SubMesh>,
constrained_sm: &Handle<SubMesh>,
variable: &str,
target_dual: &str,
coefficient: f64,
sense: RelationSense,
) -> Result<(SubMatrix, SubMatrix)> {
// Neither block is symmetric — both are rectangular — but together they are,
// and this is the one place that knows it: the same coefficient is written
// into both, a few lines below. The identity folds in everything that tells
// this pair from another; two constraints that hashed alike would be
// *rejected* by `Matrix::symmetric`, never wrongly accepted.
let (id_c, id_ct) = {
let (mult_g, cons_g) = (multiplier_sm.read(), constrained_sm.read());
let mut h = FNV_SEED;
h = hash_nodes(h, mult_g.connectivity());
h = hash_nodes(h, cons_g.connectivity());
for name in [variable, target_dual] {
h = hash_name(h, name);
}
mint_pair(hash_f64(h, coefficient))
};
// C block: rows = multiplier × IMPOSED, cols = constrained × variable.
let mut c = SubMatrix::new(
multiplier_sm.clone(),
constrained_sm.clone(),
vec![IMPOSED.to_string()],
vec![variable.to_string()],
DofOrdering::NodesThenVars,
Symmetry::Half(id_c),
)?;
c.set_row_sense(sense);
// Cᵀ block: rows = constrained × target_dual, cols = multiplier × MULTIPLIER.
let mut ct = SubMatrix::new(
constrained_sm.clone(),
multiplier_sm.clone(),
vec![target_dual.to_string()],
vec![MULTIPLIER.to_string()],
DofOrdering::NodesThenVars,
Symmetry::Half(id_ct),
)?;
// Both blocks are built — hence both `seal`s, the only writers here — so the
// node lists can now be read in place instead of copied: `add_entry` only
// ever takes a read guard on the supports.
let (mult_g, cons_g) = (multiplier_sm.read(), constrained_sm.read());
for (cons, mult) in cons_g
.connectivity()
.iter()
.zip(mult_g.connectivity().iter())
{
c.add_entry_with(
&mult_g,
&cons_g,
*mult,
IMPOSED,
*cons,
variable,
coefficient,
)?;
ct.add_entry_with(
&cons_g,
&mult_g,
*cons,
target_dual,
*mult,
MULTIPLIER,
coefficient,
)?;
}
Ok((c, ct))
}
/// A static component list in the owned form [`Domain::material_components`]
/// returns — the one line every physics whose contract is fixed needs.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// # use pyrucast::models::owned_components;
/// // The shortcut every physics uses to hand back its material contract
/// // without retyping it.
/// assert_eq!(owned_components(&["E", "nu"]),
/// vec!["E".to_string(), "nu".to_string()]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn owned_components(names: &[&str]) -> Vec<String> {
names.iter().map(|s| s.to_string()).collect()
}
/// Where a physics' components sit in the rows its kernel is handed.
///
/// A constitutive kernel runs once per Gauss point — some tens of millions of
/// times in a non-linear solve — so it reads by **index**, never by name: a name
/// lookup is a string comparison that re-proves at every point what is a
/// property of the zone. This table is that proof, done once, before the
/// parallel region: it translates the canonical order a physics declares
/// ([`Behavior::deformation_reads`], [`Behavior::state_reads`],
/// [`Domain::material_components`]) into positions in the actual fields.
///
/// Resolving rather than assuming also makes the convention **checked**: a field
/// built by hand, in another order or missing a component, is refused by
/// [`Behavior::zone_layout`] with a message naming the field and the gap — instead
/// of silently feeding a permuted tensor to the law.
/// ```
/// # use pyrucast::models::ZoneLayout;
/// // A table says where to read, not what to read: the physics declares its
/// // canonical order, the zone translates it into positions.
/// let lay = ZoneLayout {
/// deformation: vec![2, 0, 1],
/// state: Vec::new(),
/// material: vec![0, 1],
/// optional_material: Vec::new(),
/// };
/// let ligne = [10.0, 20.0, 30.0];
/// // The convention's first component sits in third position.
/// assert_eq!(ligne[lay.deformation[0] as usize], 30.0);
/// ```
pub struct ZoneLayout {
/// Position of each [`Behavior::deformation_reads`] component.
pub deformation: Vec<u32>,
/// Position of each [`Behavior::state_reads`] component in the `prev` row.
pub state: Vec<u32>,
/// Position of each **required** material component, in
/// [`Domain::material_components`] order.
pub material: Vec<u32>,
/// Position of each **optional** material component, in
/// [`Domain::optional_material_components`] order;
/// [`ABSENT_COMPONENT`](crate::containers::field::ABSENT_COMPONENT) where
/// the caller supplied none.
pub optional_material: Vec<u32>,
}
/// What a **matrix** kernel reads, resolved once per zone — the counterpart of
/// [`ZoneLayout`] on the element side.
///
/// The two paths of a physics now hold the same shape: the point kernel gets a
/// [`ZoneLayout`] from [`Behavior::zone_layout`], the element kernel gets an
/// `ElementLayout` from [`Domain::element_layout`], and neither looks a
/// component up by name. A name search is a string comparison; done inside a
/// per-cell loop it re-proves at every cell what is a property of the *zone*.
///
/// ```
/// # use pyrucast::models::ElementLayout;
/// // A table says where to read. The physics declares its canonical order
/// // (`material_components`, `element_state_reads`), the zone translates it.
/// let lay = ElementLayout {
/// material: vec![1, 0],
/// optional_material: Vec::new(),
/// state: Vec::new(),
/// };
/// let ligne = [0.3, 210_000.0];
/// // `E` is declared first, but stored second in that particular field.
/// assert_eq!(ligne[lay.material[0] as usize], 210_000.0);
/// ```
pub struct ElementLayout {
/// Position of each **required** material component, in
/// [`Domain::material_components`] order.
pub material: Vec<u32>,
/// Position of each **optional** material component, in
/// [`Domain::optional_material_components`] order;
/// [`ABSENT_COMPONENT`](crate::containers::field::ABSENT_COMPONENT) where
/// the caller supplied none.
pub optional_material: Vec<u32>,
/// Position of each [`Domain::element_state_reads`] component in the state
/// row — empty for the kinds that read no state (stiffness, mass).
pub state: Vec<u32>,
}
/// The borrowed twin of [`KernelInputs`](crate::containers::matrix::KernelInputs):
/// what a matrix kernel reads besides its material, already borrowed and, for the
/// tangent, already resolved.
///
/// The `ZoneLayout` travels **inside** the tangent variant because it belongs to
/// it: no other kind resolves one, and hanging an `Option<&ZoneLayout>` on the
/// signature would be a slot for three kinds to leave empty.
///
/// ```
/// # use pyrucast::models::KernelState;
/// // What a stiffness receives: nothing more than its material.
/// let inputs = KernelState::MaterialOnly;
/// assert!(matches!(inputs, KernelState::MaterialOnly));
/// ```
pub enum KernelState<'a> {
/// Stiffness, mass.
MaterialOnly,
/// Geometric stiffness: the current stress.
State(&'a SubElementField),
/// Consistent tangent, evaluated at the point.
Behavior {
lay: &'a ZoneLayout,
deformation: &'a SubElementField,
prev: &'a SubElementField,
dt: f64,
},
}
/// A **domain** sub-model — an optional capability, not part of the base
/// [`SubModelKind`] contract. A domain is a physics defined *over a region*: it
/// reads material data **and** integrates a constitutive law over its cells. A
/// domain implements this trait *and* returns `Some(self)` from
/// [`SubModelKind::as_domain`]; a constraint such as `Dirichlet` implements
/// neither, so its absence of material and behaviour is a compile-time fact, not
/// a runtime error.
///
/// Material and behaviour used to be **one** capability here, and that was the
/// mistake: this trait asked for six methods, of which four served only those
/// that really have a law. A boundary transfer needs the integration and the
/// material — its `h` lives on a subspace, its `∫ h NᵀN` is integrated cell by
/// cell — and has no law at all; the price of admission was a kernel that
/// recomputed, point by point, what the matrix already knew.
///
/// So the law now lives next door, in [`Behavior`], which has `Domain` for
/// supertrait: every behaviour integrates, not every integration has a law.
/// What remains here is one fact — *I integrate on an FE subspace, with
/// material*.
///
/// An implementer writes the material declaration
/// ([`material_fespace`](Self::material_fespace)) and whichever matrix kernels
/// it has ([`element_matrix`](Self::element_matrix) & consorts); every one of
/// those is provided and errors by default, because a physics may integrate
/// without producing a matrix of a given kind — or any matrix at all, as a
/// distributed load does.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::{Model, SubModel};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{Constraint, Domain, MatrixKind, RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let volume = SubModel::heat_conduction(zone.clone(), MaterialSymmetry::Isotropic).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// // Matter and behaviour are **one single** capability: the material
/// // parameterises the constitutive law, it has no meaning without it.
/// let d = volume.as_kind().as_domain().unwrap();
/// assert_eq!(d.material_components(), vec!["k".to_string()]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub trait Domain: Sync {
/// FE subspace on which this domain expects its material data.
fn material_fespace(&self) -> Handle<SubFiniteElementSpace>;
/// Material component names this domain requires, or `None` if it declares a
/// material FE subspace but constrains no particular component. Default:
/// `None`.
///
/// **Owned**, not `&'static`: a physics whose variables are given by the
/// caller derives its coefficient names from them — a transfer law wants one
/// `h_<variable>` per transferred quantity, which no static table can hold.
/// The DOF names ([`SubModelKind::primal_vars`]) had always been owned for
/// the same reason; this closes the asymmetry. It is read once per sub-model
/// when the material field is built, so the allocation is not on any hot
/// path. Most implementers hand a static list to
/// [`owned_components`](fn@owned_components) and are done.
fn material_components(&self) -> Vec<String> {
Vec::new()
}
/// Material component names this domain **accepts but does not require**:
/// passed through the material channel if supplied (kept by
/// [`material_field`](fn@crate::ops::element_field::material_field)), never demanded
/// at assembly (only the *required* components discriminate the material
/// zone). Read by an ancillary operator — e.g. `alpha` (thermal expansion)
/// consumed by
/// [`crate::ops::element_field::thermal_strain`](fn@crate::ops::element_field::thermal_strain).
/// Default: `&[]`.
fn optional_material_components(&self) -> &'static [&'static str] {
&[]
}
/// Components the **matrix** kernel of `kind` reads from the state field, in
/// the slot order its indices assume — the counterpart of
/// [`state_reads`](Behavior::state_reads) on the element side.
///
/// Default: none. A stiffness or a mass reads only the material, so only the
/// two state-consuming kinds — `Geometric` (the current stress) and
/// `Tangent` (the algorithmic moduli) — declare anything here. The material
/// side needs no declaration at all: [`material_components`](Self::material_components)
/// already is it.
fn element_state_reads(&self, _kind: MatrixKind) -> Vec<String> {
Vec::new()
}
/// Resolve this physics' matrix conventions against the fields it will be
/// handed — **the upstream half of index-based reading**, and the only place
/// a matrix kernel's component names are matched at all.
///
/// **Provided**, and rarely worth redefining; the mirror of
/// [`zone_layout`](Behavior::zone_layout). The driver calls it once per zone,
/// before the parallel region, and hands the result to every cell.
fn element_layout(
&self,
kind: MatrixKind,
material: &SubElementField,
state: Option<&SubElementField>,
) -> Result<ElementLayout> {
let mat_names = self.material_components();
let mat_refs: Vec<&str> = mat_names.iter().map(String::as_str).collect();
let state_names = self.element_state_reads(kind);
let state_refs: Vec<&str> = state_names.iter().map(String::as_str).collect();
let state_lay = match (state, state_refs.is_empty()) {
(_, true) => Vec::new(),
(Some(s), false) => s.resolve_components(&state_refs, "state")?,
// The assembler supplies a state for exactly the kinds that read
// one; a kernel declaring reads without one is a wiring mistake,
// caught here rather than at a Gauss point.
(None, false) => {
return Err(PyrucastError::Message(format!(
"{kind:?}: this kernel reads {state_refs:?} from the state field, \
and none was supplied"
)))
}
};
Ok(ElementLayout {
material: material.resolve_components(&mat_refs, "material")?,
optional_material: material
.resolve_optional_components(self.optional_material_components()),
state: state_lay,
})
}
/// Local element stiffness matrix of one cell — the pure, sequential kernel
/// a physics author writes (the stiffness counterpart of
/// [`integrate_point`](Behavior::integrate_point)). Fills `ke` (row-major,
/// node-major / variable-minor: `ke[(li*n_dual+di) * n_cols_loc + (lj*n_primal+pj)]`)
/// from the cell geometry and material.
///
/// `geoms` holds one [`CellGeom`] per FE subspace declared in
/// [`SubModelKind::stiffness_layout`], in that order: a plain volumetric
/// physics reads `geoms[0]`, a multi-quadrature element (a shear-deformable
/// beam, a shell) reads each — e.g. `geoms[0]` full Gauss for bending,
/// `geoms[1]` reduced for shear.
///
/// `lay` is [`element_layout`](Self::element_layout)'s answer, resolved once
/// for the zone: read the material by `lay.material[k]`, **never by name** —
/// a name search inside a per-cell loop re-proves at every cell what is a
/// property of the zone.
///
/// It **never sees rayon or a lock**: the assembler drives it in
/// parallel over all cells. Default errors, like its four siblings: a
/// physics may integrate on a subspace without producing a stiffness — a
/// distributed load has a support and a density, and a null derivative.
/// What decides is [`stiffness_layout`](SubModelKind::stiffness_layout),
/// which such a physics leaves at `None`; the kernel is then never reached.
fn element_matrix(
&self,
_geoms: &[CellGeom],
_material: &SubElementField,
_lay: &ElementLayout,
_ke: &mut [f64],
) -> Result<()> {
Err(PyrucastError::Message(
"no stiffness kernel — element_matrix is undefined for this physics".into(),
))
}
/// Local element **mass** matrix of one cell (`∫ ρ Nᵀ N` for mechanics,
/// `∫ ρ c Nᵀ N` for the thermal capacity) — the mass counterpart of
/// [`element_matrix`](Self::element_matrix). Default errors: a physics may
/// legitimately have no mass term.
fn element_mass(
&self,
_geoms: &[CellGeom],
_material: &SubElementField,
_lay: &ElementLayout,
_ke: &mut [f64],
) -> Result<()> {
Err(PyrucastError::Message(
"no mass kernel — element_mass is undefined for this physics".into(),
))
}
/// Local element **geometric (initial-stress) stiffness** of one cell
/// (`∫ Gᵀ σ̂ G`). `state` carries this physics' current stress field (the
/// [`integrate_behavior`](Behavior::integrate_behavior) output), read by
/// `lay.state[k]`. Default errors: not every physics buckles.
fn element_geometric(
&self,
_geoms: &[CellGeom],
_material: &SubElementField,
_lay: &ElementLayout,
_state: &SubElementField,
_ke: &mut [f64],
) -> Result<()> {
Err(PyrucastError::Message(
"no geometric-stiffness kernel — element_geometric is undefined for this physics"
.into(),
))
}
/// Local element **coupling** matrix of one facing cell pair — the kernel
/// behind [`Contribution::Coupling`]. `row_geoms` describes the cell on the
/// row mesh, `col_geoms` the facing cell on the column mesh; `ke` is
/// `(row nodes × dual) × (col nodes × primal)`, same node-major layout as
/// [`element_matrix`](Self::element_matrix).
///
/// It is the physics' job to carry the **sign**: an exchange law contributes
/// `+h∫NᵢNⱼ` on its two diagonal blocks and `−h∫NᵢNⱼ` off-diagonal, and since
/// the two go through different kernels there is no factor to thread through
/// the assembler. Default errors: only an interface couples two meshes.
fn coupling_element(
&self,
_kind: MatrixKind,
_row_geoms: &[CellGeom],
_col_geoms: &[CellGeom],
_material: &SubElementField,
_lay: &ElementLayout,
_ke: &mut [f64],
) -> Result<()> {
Err(PyrucastError::Message(
"no coupling kernel — coupling_element is undefined for this physics".into(),
))
}
}
/// How a law's input is produced from the nodal solution — the `B` of
/// `ε = B·u`, **named** by the law ([`Behavior::strain_operator`]) and **run**
/// by [`crate::ops::element_field::strain`](fn@crate::ops::element_field::strain).
///
/// The law declares, the operator runs: it holds the solution once for every
/// sub-model, and no law handles a nodal field. Each variant is one of the
/// geometric producers of [`crate::ops::element_field`], applied to the law's own
/// primal unknowns on its [`behavior_fespace`](Behavior::behavior_fespace):
///
/// | variant | producer | what the law reads |
/// |---|---|---|
/// | `Deformation(m)` | `deformation` | a strain measure of the displacement (`eps_xx`, …) |
/// | `Gradient` | `gradient` | the gradient of each unknown (`grad_T_x`, …) |
/// | `Value` | `interp_to_gauss` | the unknown itself at the point (`T`) |
/// | `Beam` | `beam_deformation` | section strains (`eps`, `kappa`, `gamma`, …) |
/// | `Shell(f)` | `shell_deformation` | membrane, curvatures, drilling, shear |
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::SubModel;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::tensor::Kinematics;
/// # use pyrucast::models::{StrainOperator, SubModelKind};
/// # use pyrucast::ops::element_field::StrainMeasure;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// let solide = SubModel::elasticity(zone.clone(), Kinematics::PlaneStrain, MaterialSymmetry::Isotropic, StrainMeasure::Linear)?;
/// let thermique = SubModel::heat_conduction(zone, MaterialSymmetry::Isotropic)?;
/// let entree = |m: &SubModel| m.as_kind().as_behavior().unwrap().strain_operator();
/// // A solid reads the small-strain tensor of its displacement, conduction the
/// // gradient of its temperature: the same `B·u`, two operators.
/// assert_eq!(entree(&solide), StrainOperator::Deformation(StrainMeasure::Linear));
/// assert_eq!(entree(&thermique), StrainOperator::Gradient);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StrainOperator {
/// A strain measure of the displacement, one component per axis.
Deformation(crate::ops::element_field::StrainMeasure),
/// The gradient of each primal unknown.
Gradient,
/// The primal unknowns themselves, interpolated at the points.
Value,
/// A beam's section strains; they read `Φ` from the material.
Beam,
/// A shell's generalized strains, in the given formulation.
Shell(shell::ShellFormulation),
}
/// Whether `kind` carries a law reading a large-transformation measure
/// (Green–Lagrange or Hencky): its residual is then written on the reference
/// configuration with the first Piola–Kirchhoff stress.
fn reads_finite_strain<K: SubModelKind + ?Sized>(kind: &K) -> bool {
matches!(
kind.as_behavior().map(|law| law.strain_operator()),
Some(StrainOperator::Deformation(measure))
if measure != crate::ops::element_field::StrainMeasure::Linear
)
}
/// The **law** capability: a pointwise constitutive evaluation producing a
/// state, on top of a [`Domain`]'s integration.
///
/// This is the second of the two facts `Domain` used to lock together. A domain
/// says *I integrate on an FE subspace, with material*; a behaviour says *and I
/// have a law evaluated at each point*. The two are not orthogonal — a law is
/// evaluated on a subspace and reads material — hence the supertrait: every
/// behaviour is a domain, not every domain is a behaviour.
///
/// The distinction is not academic. A boundary transfer integrates `∫ h NᵀN`
/// and needs the first; its `h·a` is not a law but the coefficient of that same
/// operator applied at a point, and the residual `A·u` follows from the
/// operator itself. Requiring it to declare a law was the price of admission,
/// and it paid it with a kernel that recomputed what the matrix already knew.
///
/// A physics with a law implements both traits and returns `Some(self)` from
/// [`SubModelKind::as_behavior`]; one without implements `Domain` alone.
///
/// ## The convention every law follows
///
/// A law steps from A to B — the state at A, the strain at B — and computes the
/// stress at B as **the material at B applied to the elastic strain at B**:
/// `σ(B) = C(B) : ε_e(B)`. Elasticity and damage do it directly (their elastic
/// strain is the strain), plasticity through `ε_e = ε − ε_p`. A stress written
/// that way stays secant when the material depends on the state — a modulus
/// that drops with temperature lowers the stress at the same elastic strain —
/// so a step-by-step solver needs no correction when the materials move. An
/// incremental `σ(A) + C(B):Δε` would carry the stress of the old modulus
/// along instead. MFront writes its behaviours the same way.
///
/// ```
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::containers::model::SubModel;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::{RelationSense, SubModelKind};
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let fes = FiniteElementSpace::lagrange1(&Mesh::from_submesh(sm)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let impose = mesh::poi1_from_nodes(&n[..1]).unwrap();
/// # let cible = pyrucast::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
/// # let appui = SubModel::dirichlet(&impose, &cible, "T", RelationSense::Equality).unwrap();
/// # let volume = SubModel::heat_conduction(zone, MaterialSymmetry::Isotropic).unwrap();
/// // Conduction integrates **and** has a law; a support does neither. It is
/// // a compile-time fact, not a run-time error.
/// assert!(volume.as_kind().as_domain().is_some());
/// assert!(volume.as_kind().as_behavior().is_some());
/// assert!(appui.as_kind().as_domain().is_none());
/// assert!(appui.as_kind().as_behavior().is_none());
/// ```
pub trait Behavior: Domain {
/// FE subspace this domain integrates its constitutive behaviour on. Its
/// deformation input is produced geometrically by
/// [`crate::ops::element_field::gradient`](fn@crate::ops::element_field::gradient) /
/// [`crate::ops::element_field::deformation`](fn@crate::ops::element_field::deformation),
/// and [`crate::ops::element_field::behavior`] uses this handle to pair the per-zone
/// deformation field with its sub-model. Usually the same FE subspace as
/// [`material_fespace`](Domain::material_fespace).
fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace>;
/// Output component names of the material-state field produced by
/// [`integrate_point`](Self::integrate_point) — the dual flux/stress
/// followed by the updated internal state (`VAR1`), in order.
fn behavior_output_components(&self) -> Vec<String>;
/// Components this kernel reads from the **deformation** row, in the slot
/// order its indices assume — the physics' own convention (`eps_xx`,
/// `eps_yy`, `eps_xy` for a plane continuum; `grad_T_x`, … for conduction).
///
/// Read once per zone by [`zone_layout`](Self::zone_layout), never at a
/// Gauss point. Declaring it is physics — naming what the law consumes —
/// and it is what lets the kernel index instead of search.
fn deformation_reads(&self) -> Vec<String>;
/// How the input [`deformation_reads`](Self::deformation_reads) names is
/// produced from the nodal solution — this law's `B`, run by
/// [`crate::ops::element_field::strain`](fn@crate::ops::element_field::strain).
///
/// **Required**, deliberately: a law that forgot it would have no input, and
/// a default would hand it someone else's.
fn strain_operator(&self) -> StrainOperator;
/// Components this kernel reads from the **previous state** row, in slot
/// order. Default: none — most laws have no history.
///
/// Every declared component must exist in the state: what a law reads back
/// is what it wrote, so a mismatch is a real inconsistency, caught once per
/// zone rather than turned into a silent zero at each point.
fn state_reads(&self) -> Vec<String> {
Vec::new()
}
/// Resolve this physics' conventions against the fields it will actually be
/// handed — **the upstream half of index-based reading**, and the only place
/// component names are matched at all.
///
/// **Provided**, and rarely worth redefining. Required components must be
/// present (a missing one names itself in the error); optional material
/// components may be absent, marked
/// [`ABSENT_COMPONENT`](crate::containers::field::ABSENT_COMPONENT).
fn zone_layout(
&self,
deformation: &SubElementField,
prev: &SubElementField,
material: &SubElementField,
) -> Result<ZoneLayout> {
let def_names = self.deformation_reads();
let state_names = self.state_reads();
let mat_names = self.material_components();
let def_refs: Vec<&str> = def_names.iter().map(String::as_str).collect();
let state_refs: Vec<&str> = state_names.iter().map(String::as_str).collect();
let mat_refs: Vec<&str> = mat_names.iter().map(String::as_str).collect();
Ok(ZoneLayout {
deformation: deformation.resolve_components(&def_refs, "deformation")?,
state: prev.resolve_components(&state_refs, "previous state")?,
material: material.resolve_components(&mat_refs, "material")?,
optional_material: material
.resolve_optional_components(self.optional_material_components()),
})
}
/// Local element **consistent tangent** of one cell (`∫ Bᵀ D_alg B`).
/// `state` carries the algorithmic tangent moduli produced by
/// [`integrate_point`](Self::integrate_point), read by `lay.state[k]`.
/// Default errors: a linear law has no tangent of its own.
#[allow(clippy::too_many_arguments)]
fn element_tangent(
&self,
_geoms: &[CellGeom],
_lay: &ZoneLayout,
_deformation: &SubElementField,
_prev: &SubElementField,
_material: &SubElementField,
_dt: f64,
_ke: &mut [f64],
) -> Result<()> {
Err(PyrucastError::Message(
"no tangent kernel — element_tangent is undefined for this physics".into(),
))
}
/// The material state **at rest**, before any step — the `prev` of the first
/// step. **Provided**: zero on every output component, which is the rest
/// state of nearly every law (σ = 0, ε = 0, ε_p = 0, p = 0).
///
/// It exists so that `prev` is **always** a real field. The alternative —
/// an `Option` threaded down to the Gauss point — made every physics ask
/// "is there a state yet?" some tens of millions of times per solve, to
/// answer the same thing every time; and it is a question about the *step*,
/// not about the point. The field has to be allocated for the step's output
/// anyway, so materializing it costs one buffer that was already coming.
///
/// Redefine it where the rest state is **not** the zero state: a law whose
/// internal variable starts from a material constant (Gurson's initial
/// porosity `f_0`) seeds it here, once, instead of testing for emptiness at
/// every Gauss point.
fn initial_state(&self, _material: &SubElementField) -> Result<SubElementField> {
SubElementField::new(self.behavior_fespace(), self.behavior_output_components())
}
/// Whether this domain's law needs the **time increment** — a creep or
/// viscoplastic law, whose answer depends on how long the step lasted.
/// Default: `false`.
///
/// Read once, by [`crate::ops::element_field::behavior::integrate`], which
/// refuses the whole integration when such a law is handed no `dt`. The
/// kernel then receives a plain `f64` and never asks: the question belongs
/// to the step, and answering it per Gauss point answered it some tens of
/// millions of times to say the same thing.
fn requires_dt(&self) -> bool {
false
}
/// The **elastic operator** of this law, when it has one: the continuum it
/// stands on and the symmetry of its elastic constants, which head its
/// material contract (`E`, `nu` for an isotropic law).
///
/// It is what a plasticity law predicts with and a damage law degrades —
/// the `D` of `σ = D:ε`, not the law's own response. Read by
/// [`elastic_stress`](fn@crate::ops::element_field::elastic_stress) and
/// [`elastic_strain`](fn@crate::ops::element_field::elastic_strain).
/// Default: none — a conduction, a bar or a beam has no continuum `D`.
fn elastic_operator(&self) -> Option<(&continuum::Continuum, symmetry::MaterialSymmetry)> {
None
}
/// Where this physics' consistent tangent comes from — see
/// [`TangentSource`]. Default: `Analytic`, which is the truth for every
/// physics whose tangent is a closed form. A physics that differentiates its
/// own law numerically says so, and a caller can then decide whether it
/// wants to pay.
fn tangent_source(&self) -> TangentSource {
TangentSource::Analytic
}
/// The consistent tangent `D_alg` at **one Gauss point** — the mirror of
/// [`integrate_point`](Self::integrate_point), and its exact inputs.
///
/// It takes the same row slices for the same reason: the algorithmic tangent
/// is the derivative of the *step* `ε(B) ↦ σ(B)` at frozen state A, not a
/// tangent to a surface at a point. Both ends of the step are part of its
/// definition — and a law differentiated by finite differences literally
/// re-runs its return map from `prev`.
///
/// Writes the full-3-D `6×6` modulus into `d`, a **caller-owned** buffer
/// living outside the Gauss loop: this kernel allocates nothing, exactly
/// like [`integrate_point`](Self::integrate_point). The reduction to the
/// kinematics' Voigt size is the caller's business.
///
/// Default: errors — not every physics has a tangent of its own.
#[allow(clippy::too_many_arguments)]
fn tangent_point(
&self,
_geom: &CellGeom,
_g: usize,
_lay: &ZoneLayout,
_deformation: &[f64],
_prev: &[f64],
_material: &[f64],
_dt: f64,
_d: &mut [[f64; 6]; 6],
) -> Result<()> {
Err(PyrucastError::Message(
"no tangent kernel — tangent_point is undefined for this physics".into(),
))
}
/// Constitutive law at **one Gauss point** — the pure, sequential kernel a
/// physics author writes. Integrates the step **A → B** for cell `geom.cell`
/// at Gauss point `g`:
///
/// Every input is the **row of this Gauss point** — a borrowed slice of the
/// field's own buffer, never a copy — read through `lay`:
///
/// - `deformation` is the **end-of-step** kinematics ε(B) (the strain, the
/// temperature gradient `∇T`, …) produced by a *geometric* operator, in
/// [`deformation_reads`](Self::deformation_reads) order;
/// - `prev` is the **converged state at the start of the step A** — the
/// dual flux/stress σ(A), the internal variables `VAR(A)`, and (for laws
/// that form an increment) the start-of-step kinematics ε(A). It is
/// **always** a real row: on the first step it is
/// [`initial_state`](Self::initial_state), the rest state;
/// - `material` is this cell's material data, empty for a physics that
/// declares none;
/// - `dt` is the time increment, `0.0` for a rate-independent law — a law
/// that needs one is guaranteed to get it, because
/// [`crate::ops::element_field::behavior::integrate`] refuses the whole
/// integration otherwise.
///
/// Write the [`behavior_output_components`](Self::behavior_output_components)
/// values — the material state at B (σ(B), `VAR(B)`, and any echoed ε(B)) —
/// into `out`. It **never sees rayon or a lock**:
/// [`integrate_behavior`](Self::integrate_behavior) drives it in parallel
/// over all cells.
///
/// Two invariants hold here, and they are what makes this kernel fast: **no
/// test that upstream already settled** (a component's presence, a field's
/// shape, an absent increment) and **no dynamic allocation** — no `Vec`, no
/// `String`, no `format!`, no intermediate struct. What is left is the
/// physics, including its own branches.
// A constitutive kernel legitimately needs its geometry, the Gauss index,
// its layout, the A→B kinematics, material, time step and output slot.
#[allow(clippy::too_many_arguments)]
fn integrate_point(
&self,
geom: &CellGeom,
g: usize,
lay: &ZoneLayout,
deformation: &[f64],
prev: &[f64],
material: &[f64],
dt: f64,
out: &mut [f64],
) -> Result<()>;
/// Integrate the constitutive law (Cast3m `COMP`). **Provided**: drives the
/// point kernel [`integrate_point`](Self::integrate_point) in parallel over
/// the behaviour FE subspace via [`kernel::element_pointwise`].
///
/// This is the **incremental montage** A → B: `deformation` carries the
/// end-of-step kinematics ε(B) alone, and `prev` — the *converged output of
/// the previous step*, or [`initial_state`](Self::initial_state) on the
/// first one — carries the whole state at A (σ(A), `VAR(A)`, ε(A)).
/// Returns the **material-state** field
/// at B: the dual flux/stress followed by the updated internal-state
/// variables (`VAR1`), which becomes the next step's `prev`. Where
/// [`SubModelKind::build_stiffness_blocks`] is the *linearization* of the
/// law, this is its *exact* response: for a linear law the two agree
/// (`∫ Bᵀ·flux = K·u`); a non-linear law departs from that tangent.
///
/// The **layout is resolved here**, once, and `dt` captured by the point
/// closure: below this line the kernel indexes and computes, and does
/// nothing else.
fn integrate_behavior(
&self,
deformation: &Handle<SubElementField>,
prev: &Handle<SubElementField>,
material: &Handle<SubElementField>,
dt: f64,
) -> Result<SubElementField> {
let fespace = self.behavior_fespace();
let out_components = self.behavior_output_components();
// One resolution per zone, against the fields actually handed over —
// which is also where a hand-built field is refused.
let lay = self.zone_layout(&deformation.read(), &prev.read(), &material.read())?;
kernel::element_pointwise(
&fespace,
deformation,
prev,
material,
out_components,
|geom, g, def, prev, mat, out| {
self.integrate_point(geom, g, &lay, def, prev, mat, dt, out)
},
)
}
}
/// Declare a physics' **parent-level operator** and its Python twin, from a
/// single place in the physics' own file.
///
/// The author of a physics writes physics and documentation; the plumbing —
/// the sweep, the `#[pyfunction]`, the stub attribute, the unwrapping of the
/// Python wrappers — is emitted here. They never open `src/py/`.
///
/// Two doc blocks, because the two audiences differ: the Rust one carries the
/// `///` comment and its doctest, the Python one a string literal, which is
/// what lands in the `.pyi`. Sharing a single block would put a Rust doctest
/// into a Python docstring. Same shape as `define_polymorphic_pyfunction!` in
/// `src/py/ops/field.rs`, the house precedent.
///
/// What it emits for `truss` — declared `truss(fespace, strain_measure:
/// StrainMeasure = StrainMeasure::Linear) via SubModel::truss` — is an ordinary
/// function: it sweeps the FE space, one sub-model per subspace, and Rust passes
/// the argument the Python face defaults. That default is written into the Rust
/// documentation, so that a Rust reader knows what the Python one gets by
/// saying nothing.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::element_field::StrainMeasure;
/// # use pyrucast::ops::model;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]]
/// # .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut left = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # left.add_cell(&[n[0].id(), n[1].id()])?;
/// # let mut right = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # right.add_cell(&[n[1].id(), n[2].id()])?;
/// # let bars = Mesh::from_submesh(left).union(&Mesh::from_submesh(right))?;
/// let fes = FiniteElementSpace::lagrange1(&bars)?;
/// assert_eq!(fes.len(), 2);
/// let cables = model::truss(&fes, StrainMeasure::GreenLagrange)?;
/// assert_eq!(cables.len(), fes.len());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[macro_export]
macro_rules! physics_operator {
// ── Alias: a named facade over a generic operator ───────────────────────
//
// Flow and damage laws are **attributes** of one single physics (cf.
// `models::plasticity::law`), not extra physics. They nonetheless read better
// named at the call site — `drucker_prager(fespace, k, strain_measure)` rather
// than `plasticity(fespace, k, PlasticLaw::DruckerPrager, strain_measure)`. The facade
// duplicates nothing: it forwards to the generic operator.
//
// Every such facade is a continuum law, and every continuum law reads a
// strain measure, so the arm adds it after the declared arguments: Rust
// passes it explicitly, the Python face takes it as `strain_measure`,
// `"linear"` unless said otherwise — one name, each language its idiom.
//
// Every facade also takes the same `kinematics`, so the Python docstring
// ends with sections the arm writes once for all — the parameters
// `fespace`, `kinematics` and `strain_measure`, the return, the errors —:
// `python:` gives only the first line and the law's own description.
(
$(#[$rust_doc:meta])*
pub fn $name:ident(fespace $(, $arg:ident : $ty:ty)* $(,)?) = $target:path, $fixed:expr;
python: $py_doc:literal
) => {
$(#[$rust_doc])*
///
/// The Python face defaults `strain_measure` to `StrainMeasure::Linear`.
pub fn $name(
fespace: &$crate::containers::finite_element_space::FiniteElementSpace,
$($arg: $ty,)*
strain_measure: $crate::ops::element_field::StrainMeasure,
) -> $crate::error::Result<$crate::containers::model::Model> {
$target(fespace, $($arg,)* $fixed, strain_measure)
}
#[cfg(feature = "python-api")]
::paste::paste! {
/// The Python face of this physics — generated, never hand-written.
pub mod [<$name _py>] {
#[allow(unused_imports)]
use super::*;
#[doc = $py_doc]
#[doc = "\n\n# Parameters\n\n- `fespace`: the FE space; one sub-model per subspace.\n- `kinematics`: `\"plane_stress\"`, `\"plane_strain\"` or `\"axisymmetric\"` on a\n 2-D space, `\"full_3d\"` (also `\"solid\"`) on a 3-D one. `\"axisymmetric\"`\n requires a geometry built with `Coords.axisymmetric()`.\n- `strain_measure`: the strain the law reads: `\"linear\"` (small strains, the\n default), `\"green_lagrange\"` (large rotations) or `\"hencky\"` (large plastic\n strains); the stress it writes is the dual, named after it (`sigma_*`,\n `S_*`, `T_*`).\n\n# Returns\n\nA `Model` with one sub-model per subspace of `fespace`; the material is\nsupplied at assembly and integration time.\n\n# Raises\n\n- `ValueError` for an unknown `kinematics` or `strain_measure`.\n- `RuntimeError` if `kinematics` does not match the dimension of the space,\n if `\"axisymmetric\"` meets a geometry that is not, or for a measure that is\n not a strain a law reads (`\"gradient\"`, `\"jacobian\"`, …)."]
#[cfg_attr(feature = "stub-gen", ::pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[::pyo3::pyfunction]
#[pyo3(signature = (
fespace, $($arg,)*
strain_measure = $crate::ops::element_field::StrainMeasure::Linear
))]
pub fn $name(
fespace: ::pyo3::PyRef<$crate::py::finite_element_space::PyFiniteElementSpace>,
$($arg: $ty,)*
strain_measure: $crate::ops::element_field::StrainMeasure,
) -> ::pyo3::PyResult<$crate::py::model::PyModel> {
Ok($crate::py::model::PyModel {
inner: $target(&fespace.inner, $($arg,)* $fixed, strain_measure)?,
})
}
} }
};
// ── Physics bearing on a target model ───────────────────────────────────
//
// A load introduces no unknown: it writes into the dual row of **another**
// physics. It therefore needs the model it loads — to check there that the
// row exists and to inherit its nature, which the row name alone is not
// enough to settle. The fespace stays first: it is what one sweeps, and
// the target is only one more argument.
(
$(#[$rust_doc:meta])*
pub fn $name:ident(fespace, target $(, $arg:ident : $ty:ty)* $(,)?) via $sub:path;
python: $py_doc:literal
) => {
$(#[$rust_doc])*
pub fn $name(
fespace: &$crate::containers::finite_element_space::FiniteElementSpace,
target: &$crate::containers::model::Model,
$($arg: $ty,)*
) -> $crate::error::Result<$crate::containers::model::Model> {
#[allow(clippy::clone_on_copy)]
$crate::ops::model::spanning(fespace, |zone| $sub(zone, target $(, $arg.clone())*))
}
#[cfg(feature = "python-api")]
::paste::paste! {
/// The Python face of this physics — generated, never hand-written.
pub mod [<$name _py>] {
#[allow(unused_imports)]
use super::*;
#[doc = $py_doc]
#[cfg_attr(feature = "stub-gen", ::pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[::pyo3::pyfunction]
pub fn $name(
fespace: ::pyo3::PyRef<$crate::py::finite_element_space::PyFiniteElementSpace>,
target: ::pyo3::PyRef<$crate::py::model::PyModel>,
$($arg: $ty,)*
) -> ::pyo3::PyResult<$crate::py::model::PyModel> {
Ok($crate::py::model::PyModel {
inner: super::$name(&fespace.inner, &target.inner $(, $arg)*)?,
})
}
} }
};
// ── Physics on its FE space alone ───────────────────────────────────────
//
// An argument may carry a **Python** default (`arg: T = default`): Rust has
// no default arguments, so its caller passes it explicitly, while the
// Python face takes it as a keyword — one name, each language its idiom.
(
$(#[$rust_doc:meta])*
pub fn $name:ident(fespace $(, $arg:ident : $ty:ty $(= $default:expr)?)* $(,)?) via $sub:path;
python: $py_doc:literal
) => {
$(#[$rust_doc])*
$($(
#[doc = ""]
#[doc = concat!(
"The Python face defaults `", stringify!($arg), "` to `", stringify!($default), "`."
)]
)?)*
pub fn $name(
fespace: &$crate::containers::finite_element_space::FiniteElementSpace,
$($arg: $ty,)*
) -> $crate::error::Result<$crate::containers::model::Model> {
// A non-`Copy` argument (`Vec<(String, String)>`) would be moved at
// the first zone: the closure is `FnMut`, it sees several. So we
// clone, which costs nothing on the enums.
#[allow(clippy::clone_on_copy)]
$crate::ops::model::spanning(fespace, |zone| $sub(zone $(, $arg.clone())*))
}
#[cfg(feature = "python-api")]
::paste::paste! {
/// The Python face of this physics — generated, never hand-written.
pub mod [<$name _py>] {
// The argument types are written in the scope of the physics' own
// file; a physics without arguments imports none.
#[allow(unused_imports)]
use super::*;
#[doc = $py_doc]
#[cfg_attr(feature = "stub-gen", ::pyo3_stub_gen::derive::gen_stub_pyfunction)]
#[::pyo3::pyfunction]
#[pyo3(signature = (fespace $(, $arg $(= $default)?)*))]
pub fn $name(
fespace: ::pyo3::PyRef<$crate::py::finite_element_space::PyFiniteElementSpace>,
$($arg: $ty,)*
) -> ::pyo3::PyResult<$crate::py::model::PyModel> {
Ok($crate::py::model::PyModel {
inner: super::$name(&fespace.inner $(, $arg)*)?,
})
}
} }
};
}