//! Distributed load — the consistent nodal forces of a given density,
//! `f_i = ∫_Γ φ N_i dΓ` (Cast3M `FLUX` / `SOUR` / `PRES` on a fixed geometry).
//!
//! The first sub-model whose whole term sits on the **right** of
//! `Σ f_int = Σ f_ext`: its derivative with respect to `u` is zero, so it
//! contributes to no matrix at all. It is a [`Domain`] — it integrates on an FE
//! subspace and reads its density there — without being a
//! [`Behavior`](crate::models::Behavior): there is no law to evaluate, only a
//! given value to weight by the shape functions.
//!
//! That shape is exactly what the old free operator could not express. As
//! `ops::node_field::flux` it produced the same numbers, but from outside the
//! model: nothing recorded that the term existed, nothing archived it with the
//! problem, and forgetting to union it into the load was silent. As a
//! sub-model it enters `r = Σ rᵢ` like every other term.
//!
//! The density lives in the material, named after the row it feeds — `phi_q`
//! for a heat source, `phi_f_x` for a traction. Uniform or varying per Gauss
//! point is the material field's business, not this physics'.
//!
//! **The normal mode** — the row named [`NORMAL`], `"n"` — is a pressure: the
//! density `phi_n` acts along the normal of the cell, `f_ia = ∫ φ n_a N_i dΓ`,
//! and feeds every displacement row of the target at once (`f_x`, `f_y`,
//! `f_z`). The normal is that of the **active** configuration: evaluated on a
//! configuration laid at `X + u`, the load follows the wall (Cast3M `PRES` on
//! the current geometry), with no stiffness of its own, as in Cast3M.
use crate::containers::element_field::SubElementField;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::matrix::DofOrdering;
use crate::containers::matrix::Symmetry;
use crate::containers::mesh::SubMesh;
use crate::containers::model::{Model, SubModel};
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::models::kernel::MAX_CELL_DOFS;
use crate::models::tensor::dual_name;
use crate::models::transfer::{owner_physics, physics_slice};
use crate::models::{
CellGeom, Contribution, Domain, ElementLayout, MatrixKind, MatrixLayout, Physics,
ResidualContribution, SubModelKind,
};
use serde::{Deserialize, Serialize};
/// The material component carrying the density of a distributed load, named
/// after the dual row it feeds.
///
/// ```
/// # use pyrucast::models::flux;
/// assert_eq!(flux::density_name("q"), "phi_q");
/// assert_eq!(flux::density_name("f_x"), "phi_f_x");
/// ```
pub fn density_name(dual: &str) -> String {
format!("phi_{dual}")
}
/// The row name of the **normal** mode: a density along the normal of the cell,
/// feeding every displacement row of the target — a pressure.
///
/// ```
/// # use pyrucast::models::flux;
/// assert_eq!(flux::NORMAL, "n");
/// assert_eq!(flux::density_name(flux::NORMAL), "phi_n");
/// ```
pub const NORMAL: &str = "n";
/// A distributed load on one FE subspace: `∫ φ N dΓ`, into one dual row.
///
/// ```
/// # 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::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::flux::Flux;
/// # use pyrucast::models::{Domain, MatrixKind, Physics, SubModelKind};
/// # use pyrucast::ops::model;
/// # 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)).unwrap();
/// # let zone = fes.get(0).unwrap();
/// // The target: the model being loaded. It is the one that owns the "q" row.
/// let cible = model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
/// let charge = Flux::new(zone, &cible, "q")?;
/// // A load has no primal: it writes into the dual row of another
/// // autre physique, et n'introduit aucune inconnue.
/// assert!(charge.primal_vars().is_empty());
/// assert_eq!(charge.dual_vars(), vec!["q".to_string()]);
/// // Its derivative is zero: no matrix, of any kind.
/// assert!(charge.matrix_layout(MatrixKind::Stiffness).is_none());
/// assert_eq!(charge.material_components(), vec!["phi_q".to_string()]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Serialize, Deserialize)]
pub struct Flux {
fespace: Handle<SubFiniteElementSpace>,
support: Handle<SubMesh>,
dual: String,
physics: Physics,
/// The rows a normal-mode load feeds — every displacement row of its space
/// — or empty for a load feeding its one row `dual`.
normal_rows: Vec<String>,
}
impl Flux {
/// Build a distributed load on `fespace`, feeding the `dual` row.
///
/// `target` is the model this load feeds. The nature of the load cannot be
/// deduced from the row name — the caller chooses it freely — but the model
/// being loaded knows it: the sub-model that declares `dual` gives both the
/// physics and the proof that the row is assembled by someone.
///
/// ```
/// # 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::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::flux::Flux;
/// # use pyrucast::models::{Physics, SubModelKind};
/// # use pyrucast::ops::model;
/// # 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 maillage = Mesh::from_submesh(sm);
/// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # let cible = model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
/// assert!(Flux::new(zone.clone(), &cible, "q").is_ok());
/// // An empty dual row designates nothing: refused at construction.
/// assert!(Flux::new(zone.clone(), &cible, "").is_err());
/// // A row the target does not assemble either: that is the whole point
/// // de recevoir le modèle chargé.
/// assert!(Flux::new(zone.clone(), &cible, "f_x").is_err());
/// // A formulation owning its own interpolation (a beam) cannot receive a
/// // consistent load from here: it alone knows its shape functions. Settled
/// // at construction, not at the Gauss point.
/// # use pyrucast::atoms::Interpolation;
/// let poutre = FiniteElementSpace::new(&maillage, Interpolation::ModelEmbedded).unwrap();
/// assert!(Flux::new(poutre.get(0).unwrap(), &cible, "q").is_err());
/// // The normal mode feeds displacement rows, which a thermal target lacks.
/// assert!(Flux::new(zone, &cible, "n").is_err());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn new(fespace: Handle<SubFiniteElementSpace>, target: &Model, dual: &str) -> Result<Self> {
if dual.is_empty() {
return Err(PyrucastError::Message(
"Flux: name the dual row this load feeds, e.g. \"q\" for a heat source or \
\"f_x\" for a traction"
.into(),
));
}
// The normal mode feeds every displacement row of the space, along the
// normal of a cell one dimension below it — both settled here.
let normal_rows: Vec<String> = if dual == NORMAL {
let (space_dim, ref_dim) = {
let s = fespace.read();
(s.space_dim(), s.ref_dim())
};
if ref_dim + 1 != space_dim {
return Err(PyrucastError::Message(format!(
"Flux: the normal mode needs a boundary — cells of dimension {} in a \
{space_dim}-D space — and these are of dimension {ref_dim}",
space_dim.saturating_sub(1)
)));
}
(0..space_dim).map(dual_name).collect()
} else {
Vec::new()
};
// The load's kind is that of the term it loads. The row's name does not give
// it — the user picks it freely — but the loaded model does: we look for the
// sub-model that owns that dual.
// A row nobody assembles used to build a mute load; it is now a construction
// error.
let feeds: Vec<String> = if normal_rows.is_empty() {
vec![dual.to_string()]
} else {
normal_rows.clone()
};
let physics = owner_physics(target, |sub| {
let duals = sub.as_kind().dual_vars();
feeds.iter().all(|row| duals.contains(row))
})
.ok_or_else(|| {
PyrucastError::Message(format!(
"Flux: {feeds:?} — not dual rows of the model it loads, which declares {:?}",
target.dual_vars()
))
})?;
// A distributed load weights by the **field's** shape functions: it needs
// one, and that is a fact of the zone, settled here once and for all rather
// than at every Gauss point. A formulation owning its own interpolation (a
// `ModelEmbedded` beam) must supply its consistent load itself.
crate::models::kernel::require_field_basis(&fespace, "shape values")?;
let submesh = fespace.read().submesh();
let support = SubMesh::to_poi1(&submesh);
Ok(Self {
fespace,
support,
dual: dual.to_string(),
physics,
normal_rows,
})
}
/// The rows this load feeds: `dual`, or every displacement row in the
/// normal mode.
fn rows(&self) -> Vec<String> {
if self.normal_rows.is_empty() {
vec![self.dual.clone()]
} else {
self.normal_rows.clone()
}
}
/// Layout of the term: the subspace it integrates on, the node support it
/// scatters to, and the single row it feeds.
fn layout(&self) -> MatrixLayout {
MatrixLayout {
fespaces: vec![self.fespace.clone()],
support: self.support.clone(),
dual_vars: self.rows(),
primal_vars: Vec::new(),
ordering: DofOrdering::NodesThenVars,
symmetry: Symmetry::None,
}
}
}
impl SubModelKind for Flux {
/// None: a load introduces no unknown. It writes into a row it does not
/// own — the dual of the physics it loads — which is what makes it a term
/// with a target rather than one of its own.
fn primal_vars(&self) -> Vec<String> {
Vec::new()
}
fn dual_vars(&self) -> Vec<String> {
self.rows()
}
fn physics(&self) -> &'static [Physics] {
physics_slice(self.physics)
}
fn as_domain(&self) -> Option<&dyn Domain> {
Some(self)
}
/// Nothing, for any kind. `∂r/∂u = 0` is the whole point: a given density
/// does not move when the solution does. The default would fall back to
/// literal stiffness blocks, which is the constraint path, not this one.
fn contributions(
&self,
_kind: MatrixKind,
_material: Option<&Handle<SubElementField>>,
) -> Result<Vec<Contribution>> {
Ok(Vec::new())
}
fn external_force_contribution(&self) -> Vec<ResidualContribution> {
vec![ResidualContribution::Computed(self.layout())]
}
/// `f_i = Σ_g φ(g) N_i(g) |J|_g w_g` — the consistent nodal load, weighted
/// by the shape functions rather than split evenly.
fn external_force_element(
&self,
geoms: &[CellGeom],
material: &SubElementField,
lay: &ElementLayout,
fe: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let phi = lay.material[0] as usize;
if !self.normal_rows.is_empty() {
return normal_load(geom, material, phi, fe);
}
// On a C¹ basis (a Bernoulli beam) the field's basis is not the geometric
// one: it is the basis that carries the nodal moments of a distributed load.
// The buffer is on the stack, outside the loop.
let mut n_buf = [0.0_f64; MAX_CELL_DOFS];
for g in 0..geom.n_gauss {
let shape = geom.field_n_at_g(g, &mut n_buf);
let w = geom.det_j_w(g) * material.row(geom.cell, g)[phi];
if w == 0.0 {
continue;
}
for i in 0..geom.n_nodes {
fe[i] += shape[i] * w;
}
}
Ok(())
}
fn label(&self) -> &'static str {
"Flux"
}
fn render(&self, _opts: &DumpOptions) -> String {
format!(
"Flux<{}> on {} cell(s) → {}",
self.physics.name(),
self.fespace.read().cell_count(),
self.dual
)
}
}
/// The nodal forces of a density along the normal of the cell, `f_ia = ∫ φ n_a
/// N_i dΓ`, node-major (`fe[i * space_dim + a]`). The normal is the unit one of
/// the active configuration — `(t_y, −t_x)` for a segment of tangent `t`, the
/// cross product of the two tangents on a face — so the load follows whatever
/// geometry is active.
fn normal_load(
geom: &CellGeom,
material: &SubElementField,
phi: usize,
fe: &mut [f64],
) -> Result<()> {
let d = geom.space_dim;
let mut shape_buf = [0.0_f64; MAX_CELL_DOFS];
let mut normal = [0.0_f64; 3];
for g in 0..geom.n_gauss {
let w = geom.det_j_w(g) * material.row(geom.cell, g)[phi];
if w == 0.0 {
continue;
}
geom.normal(g, &mut normal[..d])?;
let shape = geom.field_n_at_g(g, &mut shape_buf);
for i in 0..geom.n_nodes {
for a in 0..d {
fe[i * d + a] += shape[i] * normal[a] * w;
}
}
}
Ok(())
}
impl Domain for Flux {
fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
/// The density, named after the row it feeds — `phi_q`, `phi_f_x`. Required:
/// a load whose density nobody supplied is not a load of zero, it is a
/// mistake, and it says so at assembly.
fn material_components(&self) -> Vec<String> {
vec![density_name(&self.dual)]
}
}
crate::physics_operator! {
/// Distributed-load `Model` spanning **every** subspace of `fespace`, feeding
/// the `dual` row of `target`; the density is supplied at assembly time, in
/// the material, as `phi_<dual>`.
///
/// The subspace comes first — it is what the operator sweeps — and the
/// loaded model follows: a load owns no unknown of its own, so it is the
/// target that says which physics the row belongs to, and that the row is
/// assembled by someone at all.
///
/// ```
/// # 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;
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::model;
/// # 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)).unwrap();
/// // A load distributed over the thermal model it feeds: that model owns the
/// // "q" row, and gives its kind.
/// let conduction = model::heat_conduction(&fes, MaterialSymmetry::Isotropic)?;
/// let charge = model::flux(&fes, &conduction, "q")?;
/// assert_eq!(charge.dual_vars(), vec!["q".to_string()]);
/// assert!(charge.primal_vars().is_empty());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn flux(fespace, target, dual: &str) via SubModel::flux;
python: "A distributed load: the consistent nodal forces `∫ φ N dΓ` of a density.\n\nIt brings no unknown and writes into the dual row of another physics, which\ngives it its kind and attests that the row is assembled by someone. Material:\n`phi_<dual>` — the density, uniform or varying per Gauss point. Its derivative\nwith respect to the solution is taken as **zero**: it feeds no matrix, only\nthe right-hand side, read by `pyrucast.node_field.external_forces`.\n\n# Parameters\n\n- `fespace`: the FE space the density lives on.\n- `target`: the model it loads.\n- `dual`: the dual row of `target` to load (`\"q\"` for a heat source, `\"f_x\"`\n for a traction). The row `\"n\"` is the **normal** mode, a pressure: `phi_n`\n acts along the normal of the cell, `∫ φ n N dΓ`, into every displacement\n row of `target`. The normal is that of the active configuration — on a\n configuration laid at `X + u` (`pyrucast.coords.displace_from`), the load\n follows the wall. For a contour travelled counter-clockwise the normal of a\n segment points out of the material: a pressure `p` pushing on the wall is\n then `phi_n = -p`.\n\n# Returns\n\nA `Model` with one sub-model per subspace of `fespace`.\n\n# Raises\n\n`RuntimeError` if `dual` is not a dual row of `target`."
}