//! Fickian diffusion — assembly of the cell-wise stiffness
//! `K_ij = ∫ ∇N_i · D · ∇N_j dx`.
//!
//! The mass-transport twin of [`heat_conduction`](crate::models::heat_conduction):
//! same Laplacian, different variables. Fick's first law is `j = −D·∇c`; as in
//! conduction, what is stored is the **weak-form** flux `D·∇c`, so that
//! `∫ Bᵀ·flux = K·c` and the behaviour matches the stiffness in the linear case.
//!
//! ## Every name carries its species
//!
//! A diffusion problem rarely has one diffusing species, and two of them share
//! neither their concentration, their flux, nor their diffusivity. The species
//! is therefore **named at construction** and carried by every quantity that
//! belongs to it:
//!
//! ```text
//! species "H2" primal c_H2 dual j_H2
//! material D_H2 (D_H2_1, D_H2_11, … when oriented)
//! behaviour grad_c_H2_x → j_H2_x
//! ```
//!
//! Two `Fick` sub-models with different species then live on the **same mesh**
//! without colliding — their DOFs are distinct names, so the assembler puts them
//! side by side with no special case. It also removes the older ambiguity with
//! heat conduction, whose `T`/`q` no longer risk meeting a bare `c`/`j`.
//!
//! What is **not** suffixed is what belongs to the medium rather than to the
//! species: the storage coefficient `poro` and the material axes `V1X`, `V1Y`, …
//! A porous solid has one porosity and one weaving frame, whatever diffuses
//! through it.
//!
//! Its nature is [`Physics::Diffusion`], not `Thermal`: sharing an operator is
//! not sharing a physics, and a coupled thermo-diffusive model must be able to
//! select one without dragging in the other.
//!
//! The diffusivity obeys any [`MaterialSymmetry`]:
//!
//! | symmetry | material components |
//! |---|---|
//! | isotropic | `D_<species>` |
//! | orthotropic | `D_<species>_1`, `D_<species>_2`, `D_<species>_3` + the material axes |
//! | anisotropic | `D_<species>_11 … D_<species>_33` (symmetric) + the material axes |
//!
//! The transient (storage) term `∂c/∂t` is the mass matrix, `∫ poro N_i N_j` —
//! `poro` being the storage coefficient, the porosity for a species diffusing
//! through a porous solid. It is optional: a steady assembly never asks for it.
use crate::containers::element_field::SubElementField;
use crate::containers::field::ABSENT_COMPONENT;
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::SubModel;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::models::kernel::MAX_CELL_DOFS;
use crate::models::symmetry::{self, MaterialSymmetry};
use crate::models::ElementLayout;
use crate::models::ZoneLayout;
use crate::models::{
Behavior, CellGeom, Domain, MatrixLayout, Physics, StrainOperator, SubModelKind,
};
use serde::{Deserialize, Serialize};
/// Column DOF name of a species — `c_H2`.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::matrix::{DofOrdering};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::kernel::assemble_block;
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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 support = zone.read().submesh().read().to_poi1().unwrap();
/// # let mat = Handle::new(SubElementField::from_uniform_per_component(
/// # zone.clone(), vec!["D_H2".into()], &[2.0]).unwrap());
/// # use pyrucast::models::fick;
/// // The species names the concentration: that is what lets several
/// // diffusions coexist in one model.
/// assert_eq!(fick::primal_var("H2"), "c_H2");
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn primal_var(species: &str) -> String {
format!("c_{species}")
}
/// Row DOF name of a species — `j_H2`.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::matrix::{DofOrdering};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::kernel::assemble_block;
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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 support = zone.read().submesh().read().to_poi1().unwrap();
/// # let mat = Handle::new(SubElementField::from_uniform_per_component(
/// # zone.clone(), vec!["D_H2".into()], &[2.0]).unwrap());
/// # use pyrucast::models::fick;
/// assert_eq!(fick::dual_var("H2"), "j_H2");
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn dual_var(species: &str) -> String {
format!("j_{species}")
}
/// Storage (capacity) coefficient, consumed **only** by the mass matrix.
const STORAGE_COMPONENTS: &[&str] = &["poro"];
/// Isotropic contract.
const MATERIAL_COMPONENTS: &[&str] = &["D"];
/// Orthotropic diffusivities plus the in-plane material axis (2-D).
const ORTHOTROPIC_2D: &[&str] = &["D_1", "D_2", "D_3", "V1X", "V1Y"];
/// Orthotropic diffusivities plus the two material axes (3-D).
const ORTHOTROPIC_3D: &[&str] = &[
"D_1", "D_2", "D_3", "V1X", "V1Y", "V1Z", "V2X", "V2Y", "V2Z",
];
/// The symmetric diffusivity tensor plus the in-plane material axis (2-D).
const ANISOTROPIC_2D: &[&str] = &["D_11", "D_12", "D_13", "D_22", "D_23", "D_33", "V1X", "V1Y"];
/// The symmetric diffusivity tensor plus the two material axes (3-D).
const ANISOTROPIC_3D: &[&str] = &[
"D_11", "D_12", "D_13", "D_22", "D_23", "D_33", "V1X", "V1Y", "V1Z", "V2X", "V2Y", "V2Z",
];
/// The material contract of a symmetry, **with the species** carried by every
/// diffusivity and by nothing else.
///
/// The species follows `D` and the direction index goes last (`D_H2_1`,
/// `D_H2_11`), as in `grad_c_H2_x` and `j_H2_x`. The axes `V1X…V2Z` keep their
/// bare names: they are the medium's frame, shared by everything that diffuses
/// through it.
fn material_contract(symmetry: MaterialSymmetry, space_dim: usize, species: &str) -> Vec<String> {
static_contract(symmetry, space_dim)
.iter()
.map(|name| {
if let Some(index) = name.strip_prefix('D') {
format!("D_{species}{index}")
} else {
(*name).to_string()
}
})
.collect()
}
/// The species-free contract, one table per symmetry.
fn static_contract(symmetry: MaterialSymmetry, space_dim: usize) -> &'static [&'static str] {
match (symmetry, space_dim) {
(MaterialSymmetry::Isotropic, _) => MATERIAL_COMPONENTS,
(MaterialSymmetry::Orthotropic, 2) => ORTHOTROPIC_2D,
(MaterialSymmetry::Orthotropic, _) => ORTHOTROPIC_3D,
(MaterialSymmetry::Anisotropic, 2) => ANISOTROPIC_2D,
(MaterialSymmetry::Anisotropic, _) => ANISOTROPIC_3D,
}
}
/// Axis suffixes for the vector components, indexed by spatial direction.
const AXES: [&str; 3] = ["x", "y", "z"];
/// Behaviour-**input** components (`grad_c_x`, …) — what
/// [`crate::ops::element_field::gradient`](fn@crate::ops::element_field::gradient)
/// names the gradient of a field whose component is [`primal_var`].
fn gradient_components(space_dim: usize, species: &str) -> Vec<String> {
let primal = primal_var(species);
(0..space_dim)
.map(|a| format!("grad_{primal}_{}", AXES[a]))
.collect()
}
/// Behaviour-**output** components (`j_x`, …) — the weak-form flux `D·∇c`. Named
/// after the dual variable rather than `flux_*`, so a model carrying both
/// conduction and diffusion keeps two unambiguous flux fields.
fn flux_components(space_dim: usize, species: &str) -> Vec<String> {
let dual = dual_var(species);
(0..space_dim)
.map(|a| format!("{dual}_{}", AXES[a]))
.collect()
}
/// Fickian diffusion of **one named species** on an FE subspace.
///
/// - primal variable: `c_<species>` (concentration, columns).
/// - dual variable: `j_<species>` (mass flux, row labels).
/// - Material data is supplied at assembly time, not stored here.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Interpolation, 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::{Domain, 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.iter().map(|x| x.id()).collect::<Vec<_>>()).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// # let fes = FiniteElementSpace::lagrange1(&maillage).unwrap();
/// # let zone = fes.get(0).unwrap();
/// # use pyrucast::models::fick::{self, Fick};
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// // The species names everything: the concentration, the flux, the diffusivity.
/// let f = Fick::new(zone.clone(), "H2", MaterialSymmetry::Isotropic)?;
/// assert_eq!(f.primal_vars(), vec![fick::primal_var("H2")]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone, Serialize, Deserialize)]
pub struct Fick {
pub(crate) fespace: Handle<SubFiniteElementSpace>,
/// POI1 support over the subspace's unique nodes (row/col support).
pub(crate) support: Handle<SubMesh>,
pub(crate) space_dim: usize,
pub(crate) symmetry: MaterialSymmetry,
/// The diffusing species, carried by every name this physics declares.
pub(crate) species: String,
}
impl Fick {
/// Fickian diffusion of `species` on an FE subspace, with the given
/// material symmetry.
///
/// The species names the concentration, the flux and the diffusivity; an
/// empty one is refused, since it would give back the bare `c`/`j` the
/// suffix exists to avoid.
///
/// ```
/// # 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::symmetry::MaterialSymmetry;
/// # 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();
/// # use pyrucast::models::fick::Fick;
/// # use pyrucast::models::SubModelKind;
/// let f = Fick::new(zone.clone(), "H2", MaterialSymmetry::Isotropic)?;
/// assert_eq!(f.primal_vars(), vec!["c_H2".to_string()]);
/// assert_eq!(f.dual_vars(), vec!["j_H2".to_string()]);
/// // An empty species is refused: it would give back the bare `c`/`j` the
/// // suffix exists precisely to avoid.
/// assert!(Fick::new(zone.clone(), "", MaterialSymmetry::Isotropic).is_err());
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn new(
fespace: Handle<SubFiniteElementSpace>,
species: &str,
symmetry: MaterialSymmetry,
) -> Result<Self> {
if species.is_empty() {
return Err(PyrucastError::Message(
"Fick: a diffusing species must be named — its concentration, flux and \
diffusivity all carry the name (`c_H2`, `j_H2`, `D_H2`), which is what lets \
two species share a mesh"
.into(),
));
}
let (submesh, space_dim) = {
let s = fespace.read();
(s.submesh(), s.space_dim())
};
let support = submesh.read().to_poi1()?;
Ok(Self {
fespace,
support,
space_dim,
symmetry,
species: species.to_string(),
})
}
}
impl SubModelKind for Fick {
fn primal_vars(&self) -> Vec<String> {
vec![primal_var(&self.species)]
}
fn dual_vars(&self) -> Vec<String> {
vec![dual_var(&self.species)]
}
fn as_domain(&self) -> Option<&dyn Domain> {
Some(self)
}
fn as_behavior(&self) -> Option<&dyn Behavior> {
Some(self)
}
fn stiffness_layout(&self) -> Option<MatrixLayout> {
Some(MatrixLayout {
fespaces: vec![self.fespace.clone()],
support: self.support.clone(),
dual_vars: self.dual_vars(),
primal_vars: self.primal_vars(),
ordering: DofOrdering::NodesThenVars,
symmetry: Symmetry::Full,
})
}
/// The storage (mass) matrix shares the diffusion layout — only the kernel
/// differs.
fn mass_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
/// Internal nodal fluxes `j_i = ∫ ∇N_i · flux dx` — `Bᵀ` applied to the
/// weak-form flux, as in conduction. Single dual variable, so `fe[i]` per node.
fn internal_force_reads(&self) -> Vec<String> {
flux_components(self.space_dim, &self.species)
}
fn internal_force_element(
&self,
geoms: &[CellGeom],
stress: &SubElementField,
lay: &[u32],
_material: &SubElementField,
_mat: &[u32],
fe: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let d = geom.space_dim;
let mut dn_buf = [0.0_f64; MAX_CELL_DOFS];
for g in 0..geom.n_gauss {
let dn = &mut dn_buf[..geom.n_nodes * d];
geom.dn_dx(g, dn)?;
let w = geom.det_j_w(g);
// The flux row, sliced once: its bounds were settled with the zone,
// so a node no longer re-proves them component by component.
let row = stress.row(geom.cell, g);
for i in 0..geom.n_nodes {
let mut s = 0.0;
for a in 0..d {
s += dn[i * d + a] * row[lay[a] as usize];
}
fe[i] += s * w;
}
}
Ok(())
}
/// Linear diffusion: the consistent tangent **is** the diffusivity matrix.
fn tangent_is_stiffness(&self) -> bool {
true
}
fn physics(&self) -> &'static [Physics] {
&[Physics::Diffusion]
}
fn label(&self) -> &'static str {
"Fick"
}
fn render(&self, _opts: &DumpOptions) -> String {
let primal = self.primal_vars().join(", ");
let dual = self.dual_vars().join(", ");
let n = self.support.read().cell_count();
format!(
"SubModel<Fick({})>\n primal var(s): {primal}\n \
dual var(s): {dual}\n support: {n} node(s)",
self.symmetry
)
}
}
impl Domain for Fick {
fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
/// Every diffusivity carries the species, before the direction index
/// (`D_H2`, `D_H2_1`, `D_H2_11`); the material axes `V1X…V2Z` keep their
/// bare names, being the medium's frame rather than the species' business.
fn material_components(&self) -> Vec<String> {
material_contract(self.symmetry, self.space_dim, &self.species)
}
/// `poro` — required only by the storage (mass) matrix, never by the
/// diffusion assembly.
fn optional_material_components(&self) -> &'static [&'static str] {
STORAGE_COMPONENTS
}
fn element_matrix(
&self,
geoms: &[CellGeom],
material: &SubElementField,
lay: &ElementLayout,
ke: &mut [f64],
) -> Result<()> {
element_stiffness(&geoms[0], material, lay, self.symmetry, ke)
}
fn element_mass(
&self,
geoms: &[CellGeom],
material: &SubElementField,
lay: &ElementLayout,
ke: &mut [f64],
) -> Result<()> {
element_storage(&geoms[0], material, lay, ke)
}
}
impl Behavior for Fick {
fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn behavior_output_components(&self) -> Vec<String> {
flux_components(self.space_dim, &self.species)
}
/// Fick's law: weak-form flux `D·∇c` at one Gauss point.
fn deformation_reads(&self) -> Vec<String> {
gradient_components(self.space_dim, &self.species)
}
fn strain_operator(&self) -> StrainOperator {
StrainOperator::Gradient
}
fn integrate_point(
&self,
geom: &CellGeom,
_g: usize,
lay: &ZoneLayout,
deformation: &[f64],
_prev: &[f64],
material: &[f64],
_dt: f64,
out: &mut [f64],
) -> Result<()> {
let space_dim = geom.space_dim;
let d3 = symmetry::transport_tensor_from(
|k| material[lay.material[k] as usize],
self.symmetry,
space_dim,
)?;
for a in 0..space_dim {
let mut acc = 0.0;
for b in 0..space_dim {
acc += d3[(a, b)] * deformation[lay.deformation[b] as usize];
}
out[a] = acc;
}
Ok(())
}
}
/// Element kernel: local diffusion matrix of one cell,
/// `K[i, j] = Σ_g ∇N_iᵀ · D · ∇N_j · |J|_g · w_g`, written into `ke` (flat
/// row-major, side `n_nodes`). Pure and sequential — driven in parallel by
/// [`crate::models::kernel::assemble_block`].
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::matrix::{DofOrdering, Symmetry};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::kernel::assemble_block;
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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 support = zone.read().submesh().read().to_poi1().unwrap();
/// # let mat = Handle::new(SubElementField::from_uniform_per_component(
/// # zone.clone(), vec!["D_H2".into()], &[2.0]).unwrap());
/// # use pyrucast::models::fick;
/// # use pyrucast::models::ElementLayout;
/// // The field is laid out in the contract's order: the table is the identity.
/// let lay = ElementLayout { material: vec![0], optional_material: vec![], state: vec![] };
/// // The same Laplacian as the conduction, with the species' diffusivity.
/// let bloc = assemble_block(
/// std::slice::from_ref(&zone), &support, &support,
/// vec!["j_H2".into()], vec!["c_H2".into()], DofOrdering::NodesThenVars, Symmetry::Full,
/// &mat, None,
/// |geoms, m, _s, ke| fick::element_stiffness(
/// &geoms[0], m, &lay, MaterialSymmetry::Isotropic, ke),
/// )?;
/// let total: f64 = bloc.iter_entries()?.into_iter().map(|(_, _, _, _, v)| v).sum();
/// assert!(total.abs() < 1e-9); // une concentration uniforme ne diffuse pas
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn element_stiffness(
geom: &CellGeom,
material: &SubElementField,
lay: &ElementLayout,
symmetry: MaterialSymmetry,
ke: &mut [f64],
) -> Result<()> {
let n_nodes = geom.n_nodes;
let space_dim = geom.space_dim;
// Everything is read at the Gauss point, the axes of an oriented
// diffusivity included: a material field may vary inside a cell. The
// species no longer travels down here: naming `D_<species>` is the zone's
// business, and it did it once — this reads `lay.material` and never a name.
let oriented = symmetry.has_frame();
let mut dn_buf = [0.0_f64; MAX_CELL_DOFS];
for g in 0..geom.n_gauss {
let dn = &mut dn_buf[..n_nodes * geom.space_dim];
geom.dn_dx(g, dn)?;
let det_j_w = geom.det_j_w(g);
let row = material.row(geom.cell, g);
let tensor = if oriented {
Some(symmetry::transport_tensor_from(
|k| row[lay.material[k] as usize],
symmetry,
space_dim,
)?)
} else {
None
};
match &tensor {
None => {
let d = row[lay.material[0] as usize];
for i in 0..n_nodes {
for j in 0..n_nodes {
let mut grad_dot = 0.0;
for a in 0..space_dim {
grad_dot += dn[i * space_dim + a] * dn[j * space_dim + a];
}
ke[i * n_nodes + j] += d * grad_dot * det_j_w;
}
}
}
Some(d3) => {
for i in 0..n_nodes {
for j in 0..n_nodes {
let mut acc = 0.0;
for a in 0..space_dim {
for b in 0..space_dim {
acc += dn[i * space_dim + a] * d3[(a, b)] * dn[j * space_dim + b];
}
}
ke[i * n_nodes + j] += acc * det_j_w;
}
}
}
}
}
Ok(())
}
/// Element kernel: local **storage** (mass) matrix of one cell,
/// `C[i, j] = Σ_g poro · N_i N_j · |J|_g · w_g`. Same `ke` layout as
/// [`element_stiffness`].
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::element_field::SubElementField;
/// # use pyrucast::containers::finite_element_space::FiniteElementSpace;
/// # use pyrucast::containers::matrix::{DofOrdering, Symmetry};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::models::kernel::assemble_block;
/// # use pyrucast::models::symmetry::MaterialSymmetry;
/// # 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 support = zone.read().submesh().read().to_poi1().unwrap();
/// # let mat = Handle::new(SubElementField::from_uniform_per_component(
/// # zone.clone(), vec!["poro".into()], &[3.0]).unwrap());
/// # use pyrucast::models::fick;
/// # use pyrucast::models::ElementLayout;
/// // `poro` is the Fick contract's only **optional** component.
/// let lay = ElementLayout {
/// material: vec![], optional_material: vec![0], state: vec![],
/// };
/// // Le pendant de la capacité thermique, côté transport de masse.
/// let bloc = assemble_block(
/// std::slice::from_ref(&zone), &support, &support,
/// vec!["j_H2".into()], vec!["c_H2".into()], DofOrdering::NodesThenVars, Symmetry::Full,
/// &mat, None,
/// |geoms, m, _s, ke| fick::element_storage(&geoms[0], m, &lay, ke),
/// )?;
/// let total: f64 = bloc.iter_entries()?.into_iter().map(|(_, _, _, _, v)| v).sum();
/// assert!((total - 3.0 * 0.5).abs() < 1e-9);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn element_storage(
geom: &CellGeom,
material: &SubElementField,
lay: &ElementLayout,
ke: &mut [f64],
) -> Result<()> {
let n_nodes = geom.n_nodes;
// `poro` is optional: the diffusion assembly never asks for it, the storage
// matrix cannot do without.
let poro =
match lay.optional_material[0] {
ABSENT_COMPONENT => return Err(PyrucastError::Message(
"Fick storage matrix: material component `poro` (storage coefficient) is required"
.into(),
)),
i => i as usize,
};
for g in 0..geom.n_gauss {
let n = geom.n_at_g(g);
// Read at the point: a storage coefficient may vary inside a cell.
let det_j_w = geom.det_j_w(g) * material.row(geom.cell, g)[poro];
for i in 0..n_nodes {
for j in 0..n_nodes {
ke[i * n_nodes + j] += n[i] * n[j] * det_j_w;
}
}
}
Ok(())
}
crate::physics_operator! {
/// Fickian-diffusion `Model` of one named `species`, spanning **every**
/// subspace of `fespace` — one [`SubModel::Fick`] per [`SubFiniteElementSpace`].
/// Parent-level operator.
///
/// Every name carries the species: DOFs `c_<species>` / `j_<species>`, the
/// diffusivity `D_<species>`. `symmetry` selects the diffusivity the
/// material field must carry: `D_<species>`, the principal `D_<species>_1…`
/// (orthotropic) or the symmetric tensor `D_<species>_11…` (anisotropic),
/// the two oriented ones with the material axes. It is supplied at assembly
/// time.
///
/// ```
/// # 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::symmetry::MaterialSymmetry;
/// # use pyrucast::ops::model;
/// # 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 m = model::fick(&fes, "H2", MaterialSymmetry::Isotropic)?;
/// assert_eq!(m.primal_vars(), vec!["c_H2".to_string()]);
/// let ortho = model::fick(&fes, "H2", MaterialSymmetry::Orthotropic)?;
/// assert_eq!(ortho.dual_vars(), vec!["j_H2".to_string()]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn fick(fespace, species: &str, symmetry: MaterialSymmetry = MaterialSymmetry::Isotropic) via SubModel::fick;
python: "Fickian diffusion of one named species, spanning every subspace of `fespace`.\n\nEvery name carries the species: the unknown is `c_<species>`, the dual row\n`j_<species>`, the diffusivity `D_<species>`, the reported flux\n`j_<species>_x…`. Two species therefore share a mesh without colliding. Its\nphysics nature is `\"diffusion\"`, so `model.filter(\"diffusion\")` isolates it\nfrom a thermal or mechanical model it is composed with.\n\n# Parameters\n\n- `fespace`: the FE space; one sub-model per subspace.\n- `species`: the name of the species, `\"H2\"` for `c_H2`.\n- `symmetry`: the diffusivity the material field must carry: `\"isotropic\"`\n (`D_<species>`), `\"orthotropic\"` (`D_<species>_1 …`) or `\"anisotropic\"`\n (the symmetric `D_<species>_11 …`), the oriented ones plus the material\n axes `V1X, V1Y, …`. Those axes and the optional storage `poro` keep\n **bare** names: they belong to the medium, not to what diffuses through it.\n\n# Returns\n\nA `Model` with one sub-model per subspace of `fespace`.\n\n# Raises\n\n`ValueError` for an unknown `symmetry`."
}