use crate::aggregate::Aggregate;
use crate::atoms::NodeId;
use crate::containers::element_field::SubElementField;
use crate::containers::finite_element_space::{FiniteElementSpace, SubFiniteElementSpace};
use crate::containers::matrix::AssemblyPattern;
use crate::containers::mesh::Mesh;
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::models::symmetry::MaterialSymmetry;
use crate::models::tensor::Kinematics;
use crate::models::{
bernoulli, boundary_transfer, contact, damage, dirichlet, elasticity, embedded, fick,
heat_conduction, interface_transfer, mpc, plasticity, radiation, shell, timoshenko, truss,
Constraint, MatrixKind, Physics, RelationSense, SubModelKind,
};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::sync::{Arc, OnceLock};
fn insert_relation_value(
values: &mut std::collections::HashMap<(NodeId, String), f64>,
multiplier_node: NodeId,
slot: &str,
g: f64,
caller: &str,
) -> Result<()> {
if let Some(prev) = values.insert((multiplier_node, slot.to_string()), g)
&& prev != g
{
return Err(PyrucastError::Message(format!(
"{caller}: conflicting values ({prev} and {g}) for the same relation \
(multiplier node {multiplier_node}, slot {slot})"
)));
}
Ok(())
}
#[derive(Serialize, Deserialize)]
pub enum SubModel {
HeatConduction(heat_conduction::HeatConduction),
BoundaryTransfer(boundary_transfer::BoundaryTransfer),
Dirichlet(dirichlet::Dirichlet),
Mpc(mpc::Mpc),
Embedded(embedded::Embedded),
Contact(contact::Contact),
Truss(truss::Truss),
Elasticity(elasticity::Elasticity),
Plasticity(plasticity::Plasticity),
Mazars(damage::Damage),
Timoshenko(timoshenko::Timoshenko),
Fick(fick::Fick),
InterfaceTransfer(interface_transfer::InterfaceTransfer),
Radiation(radiation::Radiation),
Bernoulli(bernoulli::Bernoulli),
Shell(shell::Shell),
}
impl SubModel {
pub fn as_kind(&self) -> &dyn SubModelKind {
match self {
SubModel::HeatConduction(p) => p,
SubModel::BoundaryTransfer(p) => p,
SubModel::Dirichlet(p) => p,
SubModel::Mpc(p) => p,
SubModel::Embedded(p) => p,
SubModel::Contact(p) => p,
SubModel::Truss(p) => p,
SubModel::Elasticity(p) => p,
SubModel::Plasticity(p) => p,
SubModel::Mazars(p) => p,
SubModel::Timoshenko(p) => p,
SubModel::Fick(p) => p,
SubModel::InterfaceTransfer(p) => p,
SubModel::Radiation(p) => p,
SubModel::Bernoulli(p) => p,
SubModel::Shell(p) => p,
}
}
pub fn heat_conduction(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
Self::heat_conduction_with_symmetry(fespace, MaterialSymmetry::Isotropic)
}
pub fn heat_conduction_with_symmetry(
fespace: Handle<SubFiniteElementSpace>,
symmetry: MaterialSymmetry,
) -> Result<Self> {
Ok(SubModel::HeatConduction(
heat_conduction::HeatConduction::with_symmetry(fespace, symmetry)?,
))
}
pub fn boundary_transfer(
fespace: Handle<SubFiniteElementSpace>,
components: Vec<(String, String)>,
physics: Physics,
) -> Result<Self> {
Ok(SubModel::BoundaryTransfer(
boundary_transfer::BoundaryTransfer::new(fespace, components, physics)?,
))
}
pub fn truss(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
Ok(SubModel::Truss(truss::Truss::new(fespace)?))
}
pub fn elasticity(
fespace: Handle<SubFiniteElementSpace>,
kinematics: Kinematics,
) -> Result<Self> {
Self::elasticity_with_symmetry(fespace, kinematics, MaterialSymmetry::Isotropic)
}
pub fn elasticity_with_symmetry(
fespace: Handle<SubFiniteElementSpace>,
kinematics: Kinematics,
symmetry: MaterialSymmetry,
) -> Result<Self> {
Ok(SubModel::Elasticity(elasticity::Elasticity::with_symmetry(
fespace, kinematics, symmetry,
)?))
}
pub fn fick(fespace: Handle<SubFiniteElementSpace>, species: &str) -> Result<Self> {
Self::fick_with_symmetry(fespace, MaterialSymmetry::Isotropic, species)
}
pub fn fick_with_symmetry(
fespace: Handle<SubFiniteElementSpace>,
symmetry: MaterialSymmetry,
species: &str,
) -> Result<Self> {
Ok(SubModel::Fick(fick::Fick::with_symmetry(
fespace, symmetry, species,
)?))
}
pub fn radiation(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
Ok(SubModel::Radiation(radiation::Radiation::new(fespace)?))
}
pub fn bernoulli(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
Ok(SubModel::Bernoulli(bernoulli::Bernoulli::new(fespace)?))
}
pub fn shell(fespace: Handle<SubFiniteElementSpace>, model: shell::ShellModel) -> Result<Self> {
Ok(SubModel::Shell(shell::Shell::new(fespace, model)?))
}
pub fn interface_transfer(
side_a: Handle<SubFiniteElementSpace>,
side_b: Handle<SubFiniteElementSpace>,
components: Vec<(String, String)>,
physics: Physics,
tol: f64,
) -> Result<Self> {
Ok(SubModel::InterfaceTransfer(
interface_transfer::InterfaceTransfer::new(side_a, side_b, components, physics, tol)?,
))
}
pub fn plasticity_perfect(
fespace: Handle<SubFiniteElementSpace>,
kinematics: Kinematics,
) -> Result<Self> {
Self::plasticity_with_law(fespace, kinematics, plasticity::law::PlasticLaw::Perfect)
}
pub fn plasticity_with_law(
fespace: Handle<SubFiniteElementSpace>,
kinematics: Kinematics,
law: plasticity::law::PlasticLaw,
) -> Result<Self> {
Ok(SubModel::Plasticity(plasticity::Plasticity::with_law(
fespace, kinematics, law,
)?))
}
pub fn mazars(fespace: Handle<SubFiniteElementSpace>, kinematics: Kinematics) -> Result<Self> {
Self::damage_with_law(fespace, kinematics, damage::law::DamageLaw::Mazars)
}
pub fn damage_with_law(
fespace: Handle<SubFiniteElementSpace>,
kinematics: Kinematics,
law: damage::law::DamageLaw,
) -> Result<Self> {
Ok(SubModel::Mazars(damage::Damage::with_law(
fespace, kinematics, law,
)?))
}
pub fn timoshenko(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
Ok(SubModel::Timoshenko(timoshenko::Timoshenko::new(fespace)?))
}
#[allow(clippy::too_many_arguments)]
pub fn dirichlet(
imposed_variable: String,
target_dual: String,
imposed_mesh: &Mesh,
multiplier_mesh: &Mesh,
multiplier: Option<String>,
imposed_value: Option<String>,
sense: RelationSense,
) -> Result<Self> {
Ok(SubModel::Dirichlet(dirichlet::Dirichlet::new(
imposed_variable,
target_dual,
imposed_mesh,
multiplier_mesh,
multiplier,
imposed_value,
sense,
)?))
}
pub fn mpc(
terms: Vec<mpc::MpcTerm>,
multiplier_mesh: &Mesh,
multiplier: Option<String>,
imposed_value: Option<String>,
sense: RelationSense,
) -> Result<Self> {
Ok(SubModel::Mpc(mpc::Mpc::new(
terms,
multiplier_mesh,
multiplier,
imposed_value,
sense,
)?))
}
#[allow(clippy::too_many_arguments)]
pub fn embedded(
immersed: &Mesh,
host: &Mesh,
components: Vec<(String, String)>,
multipliers: Option<Vec<String>>,
imposed_values: Option<Vec<String>>,
tol: Option<f64>,
) -> Result<Self> {
Ok(SubModel::Embedded(embedded::Embedded::new(
immersed,
host,
components,
multipliers,
imposed_values,
tol,
)?))
}
pub fn contact(
slave: &Mesh,
master: &Mesh,
components: Vec<(String, String)>,
multiplier: Option<String>,
imposed_value: Option<String>,
) -> Result<Self> {
Ok(SubModel::Contact(contact::Contact::new(
slave,
master,
components,
multiplier,
imposed_value,
)?))
}
pub fn dual_of(&self, variable: &str) -> Option<String> {
let kind = self.as_kind();
let position = kind.primal_vars().iter().position(|p| p == variable)?;
kind.dual_vars().get(position).cloned()
}
pub fn multiplier_nodes(&self) -> Result<Vec<NodeId>> {
let mut out = Vec::new();
if let Some(constraint) = self.as_kind().as_constraint() {
for sm in constraint.multiplier_mesh() {
out.extend(sm.read().connectivity().iter().copied());
}
}
Ok(out)
}
pub fn multiplier_mesh(&self) -> Result<Mesh> {
let mut mesh = Mesh::empty();
if let Some(constraint) = self.as_kind().as_constraint() {
for sm in constraint.multiplier_mesh() {
mesh.add_sub(sm.clone())?;
}
}
Ok(mesh)
}
pub fn constraint_rhs(&self, imposed: &[(NodeId, f64)]) -> Result<NodeField> {
let (constraint, components) = self.constraint_components()?;
let relations = constraint.relations()?;
let mut node_to_rel: std::collections::HashMap<NodeId, Option<usize>> =
std::collections::HashMap::new();
for (i, rel) in relations.iter().enumerate() {
for term in &rel.terms {
node_to_rel
.entry(term.node)
.and_modify(|slot| {
if *slot != Some(i) {
*slot = None;
}
})
.or_insert(Some(i));
}
}
let mut values: std::collections::HashMap<(NodeId, String), f64> =
std::collections::HashMap::new();
for &(node, g) in imposed {
let idx = match node_to_rel.get(&node) {
None => {
return Err(PyrucastError::Message(format!(
"constraint_rhs: node {node} is not constrained by this {}",
self.as_kind().label()
)))
}
Some(None) => {
return Err(PyrucastError::Message(format!(
"constraint_rhs: node {node} keys several relations of this {} — \
node keying is ambiguous, use constraint_rhs_by_index",
self.as_kind().label()
)))
}
Some(Some(i)) => *i,
};
let rel = &relations[idx];
insert_relation_value(
&mut values,
rel.multiplier_node,
&rel.imposed_value,
g,
"constraint_rhs",
)?;
}
self.multiplier_load(&components, &values)
}
pub fn constraint_rhs_by_index(&self, imposed: &[(usize, f64)]) -> Result<NodeField> {
let (constraint, components) = self.constraint_components()?;
let relations = constraint.relations()?;
let mut values: std::collections::HashMap<(NodeId, String), f64> =
std::collections::HashMap::new();
for &(idx, g) in imposed {
let rel = relations.get(idx).ok_or_else(|| {
PyrucastError::Message(format!(
"constraint_rhs_by_index: relation index {idx} out of range (this \
constraint has {} relation(s))",
relations.len()
))
})?;
insert_relation_value(
&mut values,
rel.multiplier_node,
&rel.imposed_value,
g,
"constraint_rhs_by_index",
)?;
}
self.multiplier_load(&components, &values)
}
fn constraint_components(&self) -> Result<(&dyn Constraint, Vec<String>)> {
let kind = self.as_kind();
let constraint = kind.as_constraint().ok_or_else(|| {
PyrucastError::Message(format!(
"constraint_rhs: sub-model {} is not a constraint (it has no multipliers)",
kind.label()
))
})?;
let components = kind.dual_vars();
if components.is_empty() {
return Err(PyrucastError::Message(
"constraint_rhs: the constraint owns no dual (imposed-value) variable".into(),
));
}
Ok((constraint, components))
}
fn multiplier_load(
&self,
components: &[String],
values: &std::collections::HashMap<(NodeId, String), f64>,
) -> Result<NodeField> {
let mut field = NodeField::default();
for sm in &self.multiplier_mesh()? {
let mut sub = SubNodeField::from_poi1(sm, components.to_vec())?;
let nids: Vec<NodeId> = sm.read().connectivity().to_vec();
for nid in nids {
for comp in components {
if let Some(&g) = values.get(&(nid, comp.clone())) {
sub.set_value(nid, comp, g)?;
}
}
}
field.add_sub(Handle::new(sub))?;
}
Ok(field)
}
pub fn material_fespace(&self) -> Option<Handle<SubFiniteElementSpace>> {
self.as_kind().as_domain().map(|d| d.material_fespace())
}
pub fn material_components(&self) -> Option<Vec<String>> {
self.as_kind().as_domain().map(|d| d.material_components())
}
pub fn optional_material_components(&self) -> &'static [&'static str] {
self.as_kind()
.as_domain()
.map(|d| d.optional_material_components())
.unwrap_or(&[])
}
pub fn primal_vars(&self) -> Vec<String> {
self.as_kind().primal_vars()
}
pub fn dual_vars(&self) -> Vec<String> {
self.as_kind().dual_vars()
}
pub fn physics(&self) -> &'static [Physics] {
self.as_kind().physics()
}
pub fn has_behavior(&self) -> bool {
self.as_kind().as_domain().is_some()
}
pub fn behavior_fespace(&self) -> Option<Handle<SubFiniteElementSpace>> {
self.as_kind().as_domain().map(|d| d.behavior_fespace())
}
pub(crate) fn integrate_behavior(
&self,
deformation: &Handle<SubElementField>,
prev: &Handle<SubElementField>,
material: &Handle<SubElementField>,
dt: f64,
) -> Result<SubElementField> {
self.as_kind()
.as_domain()
.ok_or_else(|| {
crate::error::PyrucastError::Message(format!(
"{}: no behaviour — integrate_behavior is undefined",
self.as_kind().label()
))
})?
.integrate_behavior(deformation, prev, material, dt)
}
pub(crate) fn requires_dt(&self) -> bool {
self.as_kind().as_domain().is_some_and(|d| d.requires_dt())
}
pub(crate) fn initial_state(
&self,
material: &Handle<SubElementField>,
) -> Result<SubElementField> {
self.as_kind()
.as_domain()
.ok_or_else(|| {
crate::error::PyrucastError::Message(format!(
"{}: no behaviour — initial_state is undefined",
self.as_kind().label()
))
})?
.initial_state(&material.read())
}
pub(crate) fn build_internal_forces(
&self,
stress: &Handle<SubElementField>,
) -> Result<crate::containers::node_field::SubNodeField> {
self.as_kind().build_internal_forces(stress)
}
}
impl fmt::Debug for SubModel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SubModel")
.field("kind", &self.as_kind().label())
.field("physics", &self.as_kind().physics())
.finish()
}
}
impl fmt::Display for SubModel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_kind().display())
}
}
impl crate::dump::Dump for SubModel {
fn render(&self, opts: &crate::dump::DumpOptions) -> String {
self.as_kind().render(opts)
}
}
#[derive(Serialize, Deserialize, Default)]
pub struct Model {
subs: Vec<Handle<SubModel>>,
#[serde(skip)]
matrix_patterns: [OnceLock<Arc<AssemblyPattern>>; MatrixKind::COUNT],
}
crate::impl_aggregate!(Model, SubModel, sub_model, "sub-model(s)", {
fn post_push(&mut self) {
self.matrix_patterns = Default::default();
}
});
crate::impl_aggregate_dump!(Model);
impl Model {
pub(crate) fn matrix_pattern(
&self,
kind: MatrixKind,
build: impl FnOnce() -> Result<AssemblyPattern>,
) -> Result<Arc<AssemblyPattern>> {
let cell = &self.matrix_patterns[kind.index()];
if let Some(p) = cell.get() {
return Ok(p.clone());
}
let p = Arc::new(build()?);
let _ = cell.set(p.clone());
Ok(p)
}
}
impl Model {
pub fn contact_gaps(&self) -> Result<NodeField> {
let mut found: Option<Handle<SubModel>> = None;
for h in self {
if matches!(&*h.read(), SubModel::Contact(_)) {
if found.is_some() {
return Err(PyrucastError::Message(
"contact_gaps: model holds several contact sub-models; call it on \
a single-contact model (the `contact` object)"
.into(),
));
}
found = Some(h.clone());
}
}
let handle = found.ok_or_else(|| {
PyrucastError::Message("contact_gaps: model holds no contact sub-model".into())
})?;
let sub = handle.read();
let SubModel::Contact(c) = &*sub else {
unreachable!("filtered on Contact above");
};
let pairs: Vec<(usize, f64)> = c
.gaps()
.iter()
.enumerate()
.map(|(i, &g0)| (i, -g0))
.collect();
sub.constraint_rhs_by_index(&pairs)
}
pub fn multiplier_mesh(&self) -> Result<Mesh> {
let mut mesh = Mesh::empty();
for h in self {
if let Some(constraint) = h.read().as_kind().as_constraint() {
for sm in constraint.multiplier_mesh() {
mesh.add_sub(sm.clone())?;
}
}
}
Ok(mesh)
}
pub fn dual_of(&self, variable: &str) -> Result<Option<String>> {
for h in self {
if let Some(dual) = h.read().dual_of(variable) {
return Ok(Some(dual));
}
}
Ok(None)
}
pub fn constraint_rhs(&self, imposed: &[(NodeId, f64)]) -> Result<NodeField> {
self.sole_constraint()?.read().constraint_rhs(imposed)
}
pub fn constraint_rhs_by_index(&self, imposed: &[(usize, f64)]) -> Result<NodeField> {
self.sole_constraint()?
.read()
.constraint_rhs_by_index(imposed)
}
fn sole_constraint(&self) -> Result<Handle<SubModel>> {
let mut found: Option<Handle<SubModel>> = None;
for h in self {
if h.read().as_kind().as_constraint().is_some() {
if found.is_some() {
return Err(PyrucastError::Message(
"constraint_rhs: model holds several constraint sub-models; call it \
on a single-constraint model (e.g. the `dirichlet` / `mpc` object)"
.into(),
));
}
found = Some(h.clone());
}
}
found.ok_or_else(|| {
PyrucastError::Message("constraint_rhs: model holds no constraint sub-model".into())
})
}
pub fn primal_vars(&self) -> Result<Vec<String>> {
let mut all: Vec<String> = Vec::new();
for h in self {
all.extend(h.read().primal_vars());
}
Ok(union_names(all))
}
pub fn dual_vars(&self) -> Result<Vec<String>> {
let mut all: Vec<String> = Vec::new();
for h in self {
all.extend(h.read().dual_vars());
}
Ok(union_names(all))
}
pub fn fespace(&self) -> Result<FiniteElementSpace> {
let mut fes = FiniteElementSpace::empty();
for h in self {
if let Some(sub) = h.read().behavior_fespace() {
fes.add_sub(sub)?;
}
}
if fes.is_empty() {
return Err(PyrucastError::Message(
"Model::fespace: model has no domain sub-model to integrate on".into(),
));
}
Ok(fes)
}
pub fn filter(&self, physics: Physics) -> Result<Model> {
let mut indices: Vec<usize> = Vec::new();
for (i, h) in self.iter().enumerate() {
if h.read().physics().contains(&physics) {
indices.push(i);
}
}
self.subset(indices)
}
}
fn union_names<I: IntoIterator<Item = String>>(iter: I) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for name in iter {
if !out.contains(&name) {
out.push(name);
}
}
out
}
impl crate::archive::Archivable for SubModel {
const TAG: &'static str = "SubModel";
}
impl crate::archive::Archivable for Model {
const TAG: &'static str = "Model";
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aggregate::Aggregate;
use crate::atoms::ElementType;
use crate::atoms::Node;
use crate::containers::element_field::ElementField;
use crate::containers::field::SubField;
use crate::containers::finite_element_space::FiniteElementSpace;
use crate::containers::mesh::Mesh;
use crate::containers::mesh::SubMesh;
use crate::coords::Coords;
use crate::handle::Handle;
use crate::models::owned_components;
use crate::ops::model;
fn build_seg2_heat_model(
length: f64,
k: f64,
dirichlet_at_left: bool,
) -> (Handle<Coords>, NodeId, NodeId, Model, ElementField) {
let coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[length]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
let sub = fes.get(0).unwrap();
let mut mat = SubElementField::new(sub.clone(), vec!["k".into()]).unwrap();
mat.set_uniform("k", k).unwrap();
let mut materials = ElementField::empty();
materials.add_sub(Handle::new(mat)).unwrap();
let mut model = Model::empty();
model
.add_sub(Handle::new(SubModel::heat_conduction(sub).unwrap()))
.unwrap();
if dirichlet_at_left {
let imposed =
Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
model
.add_sub(Handle::new(
SubModel::dirichlet(
"T".into(),
"q".into(),
&imposed,
&multiplier,
None,
None,
Default::default(),
)
.unwrap(),
))
.unwrap();
}
(coords, a.id(), b.id(), model, materials)
}
#[test]
fn primal_dual_vars_for_heat_conduction_alone() {
let (_cfg, _, _, model, _mat) = build_seg2_heat_model(1.0, 1.0, false);
assert_eq!(model.primal_vars().unwrap(), vec!["T".to_string()]);
assert_eq!(model.dual_vars().unwrap(), vec!["q".to_string()]);
}
#[test]
fn primal_dual_vars_include_lagrange_after_dirichlet() {
let (_cfg, _, _, model, _mat) = build_seg2_heat_model(1.0, 1.0, true);
assert_eq!(
model.primal_vars().unwrap(),
vec!["T".to_string(), "lambda_T".to_string()]
);
assert_eq!(
model.dual_vars().unwrap(),
vec!["q".to_string(), "imposed_T".to_string()]
);
}
#[test]
fn physics_nature_per_submodel() {
let (_cfg, _, _, model, _mat) = build_seg2_heat_model(1.0, 1.0, true);
let natures: Vec<Vec<Physics>> =
model.iter().map(|h| h.read().physics().to_vec()).collect();
assert_eq!(
natures,
vec![vec![Physics::Thermal], vec![Physics::Constraint]]
);
}
#[test]
fn filter_selects_submodels_by_physics() {
let (_cfg, _, _, model, _mat) = build_seg2_heat_model(1.0, 1.0, true);
assert_eq!(model.len(), 2);
let thermal = model.filter(Physics::Thermal).unwrap();
assert_eq!(thermal.len(), 1);
assert_eq!(
thermal.get(0).unwrap().read().physics(),
&[Physics::Thermal]
);
let constraint = model.filter(Physics::Constraint).unwrap();
assert_eq!(constraint.len(), 1);
assert_eq!(
constraint.get(0).unwrap().read().physics(),
&[Physics::Constraint]
);
let mechanical = model.filter(Physics::Mechanical).unwrap();
assert_eq!(mechanical.len(), 0);
}
#[test]
fn assembled_blocks_carry_physics_and_matrix_filters() {
let (_cfg, _, _, model, materials) = build_seg2_heat_model(1.0, 1.0, true);
let k = crate::ops::matrix::stiffness(&model, &materials).unwrap();
for h in &k {
assert!(!h.read().physics().is_empty(), "assembled block is tagged");
}
let present = k.physics().unwrap();
assert!(present.contains(&Physics::Thermal));
assert!(present.contains(&Physics::Constraint));
let constraint = k.filter(Physics::Constraint).unwrap();
assert_eq!(constraint.len(), 2);
for h in &constraint {
assert_eq!(h.read().physics(), &[Physics::Constraint]);
}
let thermal = k.filter(Physics::Thermal).unwrap();
assert_eq!(thermal.len(), 1);
}
#[test]
fn heat_conduction_assembles_analytical_seg2_stiffness() {
let length = 2.0;
let k_val = 1.5;
let (_cfg, a_id, b_id, model, materials) = build_seg2_heat_model(length, k_val, false);
let k = crate::ops::matrix::stiffness(&model, &materials).unwrap();
assert_eq!(k.n_rows().unwrap(), 2);
assert_eq!(k.n_cols().unwrap(), 2);
let expected = k_val / length;
let tol = 1e-12;
assert!((k.get(a_id, "q", a_id, "T").unwrap() - expected).abs() < tol);
assert!((k.get(a_id, "q", b_id, "T").unwrap() + expected).abs() < tol);
assert!((k.get(b_id, "q", a_id, "T").unwrap() + expected).abs() < tol);
assert!((k.get(b_id, "q", b_id, "T").unwrap() - expected).abs() < tol);
}
#[test]
fn two_seg2_assembly_is_tridiagonal() {
let coords = Handle::new(Coords::new(1).unwrap());
let n0 = Node::create_in(coords.clone(), &[0.0]).unwrap();
let n1 = Node::create_in(coords.clone(), &[1.0]).unwrap();
let n2 = Node::create_in(coords.clone(), &[2.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[n0.id(), n1.id()]).unwrap();
mesh.add_cell(&[n1.id(), n2.id()]).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
let sub = fes.get(0).unwrap();
let mut mat = SubElementField::new(sub.clone(), vec!["k".into()]).unwrap();
mat.set_uniform("k", 1.0).unwrap();
let mut materials = ElementField::empty();
materials.add_sub(Handle::new(mat)).unwrap();
let mut model = Model::empty();
model
.add_sub(Handle::new(SubModel::heat_conduction(sub).unwrap()))
.unwrap();
let k = crate::ops::matrix::stiffness(&model, &materials).unwrap();
assert_eq!(k.n_rows().unwrap(), 3);
assert_eq!(k.n_cols().unwrap(), 3);
let v = |i: NodeId, j: NodeId| k.get(i, "q", j, "T").unwrap();
let tol = 1e-12;
assert!((v(n0.id(), n0.id()) - 1.0).abs() < tol);
assert!((v(n0.id(), n1.id()) + 1.0).abs() < tol);
assert!((v(n0.id(), n2.id())).abs() < tol);
assert!((v(n1.id(), n0.id()) + 1.0).abs() < tol);
assert!((v(n1.id(), n1.id()) - 2.0).abs() < tol);
assert!((v(n1.id(), n2.id()) + 1.0).abs() < tol);
assert!((v(n2.id(), n0.id())).abs() < tol);
assert!((v(n2.id(), n1.id()) + 1.0).abs() < tol);
assert!((v(n2.id(), n2.id()) - 1.0).abs() < tol);
}
#[test]
fn dirichlet_adds_one_multiplier_node_and_two_block_entries() {
let (coords, a_id, _b_id, model, materials) = build_seg2_heat_model(1.0, 1.0, true);
let n_nodes = coords.read().node_count();
assert_eq!(n_nodes, 3);
let k = crate::ops::matrix::stiffness(&model, &materials).unwrap();
assert_eq!(k.n_rows().unwrap(), 3);
assert_eq!(k.n_cols().unwrap(), 3);
let row_dofs = k.row_dofs().unwrap();
let mult = row_dofs
.iter()
.find(|(_, name)| name == "imposed_T")
.expect("multiplier row missing")
.0;
assert_eq!(k.get(mult, "imposed_T", a_id, "T").unwrap(), 1.0);
assert_eq!(k.get(a_id, "q", mult, "lambda_T").unwrap(), 1.0);
let col_dofs = k.col_dofs().unwrap();
let lambda_col_present = col_dofs
.iter()
.any(|(n, name)| name == "lambda_T" && *n == mult);
assert!(lambda_col_present);
}
#[test]
fn multiplier_nodes_live_with_their_mesh() {
let coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let imposed =
Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
let mult_id = multiplier.node(0, 0, 0).unwrap().id();
assert_eq!(coords.read().refcount(mult_id), 1);
let sub = SubModel::dirichlet(
"T".into(),
"q".into(),
&imposed,
&multiplier,
None,
None,
Default::default(),
)
.unwrap();
assert_eq!(coords.read().refcount(mult_id), 1);
assert_eq!(sub.multiplier_nodes().unwrap(), vec![mult_id]);
drop(multiplier);
assert_eq!(coords.read().refcount(mult_id), 1);
drop(sub);
assert_eq!(coords.read().refcount(mult_id), 0);
assert_eq!(coords.write().gc(), 1);
}
#[test]
fn dirichlet_empty_imposed_mesh_rejected() {
let empty = Mesh::empty();
assert!(SubModel::dirichlet(
"T".into(),
"q".into(),
&empty,
&empty,
None,
None,
Default::default()
)
.is_err());
}
#[test]
fn heat_conduction_errors_on_missing_k_component() {
let coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
let sub = fes.get(0).unwrap();
let mat = SubElementField::new(sub.clone(), vec!["rho_cp".into()]).unwrap();
let mut materials = ElementField::empty();
materials.add_sub(Handle::new(mat)).unwrap();
let mut model = Model::empty();
model
.add_sub(Handle::new(SubModel::heat_conduction(sub).unwrap()))
.unwrap();
assert!(crate::ops::matrix::stiffness(&model, &materials).is_err());
}
#[test]
fn empty_model_has_no_vars_and_empty_mass() {
let model = Model::empty();
assert_eq!(model.primal_vars().unwrap(), Vec::<String>::new());
assert_eq!(model.dual_vars().unwrap(), Vec::<String>::new());
let m = crate::ops::matrix::mass(&model, &ElementField::empty()).unwrap();
assert_eq!(m.n_rows().unwrap(), 0);
assert_eq!(m.n_cols().unwrap(), 0);
}
#[test]
fn parent_operators_span_subspaces_and_compose() {
let coords = Handle::new(Coords::new(1).unwrap());
let n0 = Node::create_in(coords.clone(), &[0.0]).unwrap();
let n1 = Node::create_in(coords.clone(), &[1.0]).unwrap();
let n2 = Node::create_in(coords.clone(), &[2.0]).unwrap();
let mut mesh = Mesh::empty();
let sm_a = {
let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
sm.add_cell(&[n0.id(), n1.id()]).unwrap();
Handle::new(sm)
};
let sm_b = {
let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
sm.add_cell(&[n1.id(), n2.id()]).unwrap();
Handle::new(sm)
};
mesh.add_sub(sm_a).unwrap();
mesh.add_sub(sm_b).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
let hc = model::heat_conduction(&fes).unwrap();
assert_eq!(hc.len(), 2);
assert_eq!(hc.primal_vars().unwrap(), vec!["T".to_string()]);
assert_eq!(hc.dual_vars().unwrap(), vec!["q".to_string()]);
let imp = Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&n0)).unwrap());
let mlt = crate::ops::mesh::barycenter(&imp).unwrap();
let dir = model::dirichlet(
"T".into(),
"q".into(),
&imp,
&mlt,
None,
None,
Default::default(),
)
.unwrap();
assert_eq!(dir.len(), 1);
let full = hc.union(&dir).unwrap();
assert_eq!(full.len(), 3);
assert_eq!(
full.primal_vars().unwrap(),
vec!["T".to_string(), "lambda_T".to_string()]
);
}
#[test]
fn parent_heat_conduction_unit_case() {
let coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
let model = model::heat_conduction(&fes).unwrap();
assert_eq!(model.len(), 1);
}
#[test]
fn debug_and_display() {
let (_cfg, _, _, model, _mat) = build_seg2_heat_model(1.0, 1.0, true);
let d = format!("{:?}", model);
assert!(d.contains("Model"));
let s = format!("{}", model);
assert!(s.contains("Model"));
assert!(s.contains("2 sub-model"));
}
#[test]
fn assemble_picks_per_zone_material() {
let coords = Handle::new(Coords::new(1).unwrap());
let n0 = Node::create_in(coords.clone(), &[0.0]).unwrap();
let n1 = Node::create_in(coords.clone(), &[1.0]).unwrap();
let n2 = Node::create_in(coords.clone(), &[2.0]).unwrap();
let mut mesh = Mesh::empty();
let sm_a = {
let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
sm.add_cell(&[n0.id(), n1.id()]).unwrap();
Handle::new(sm)
};
let sm_b = {
let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
sm.add_cell(&[n1.id(), n2.id()]).unwrap();
Handle::new(sm)
};
mesh.add_sub(sm_a).unwrap();
mesh.add_sub(sm_b).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
let sub_a = fes.get(0).unwrap();
let sub_b = fes.get(1).unwrap();
let k_a = 1.0;
let k_b = 4.0;
let mut mat_a = SubElementField::new(sub_a.clone(), vec!["k".into()]).unwrap();
mat_a.set_uniform("k", k_a).unwrap();
let mut mat_b = SubElementField::new(sub_b.clone(), vec!["k".into()]).unwrap();
mat_b.set_uniform("k", k_b).unwrap();
let mut materials = ElementField::empty();
materials.add_sub(Handle::new(mat_a)).unwrap();
materials.add_sub(Handle::new(mat_b)).unwrap();
let mut model = Model::empty();
model
.add_sub(Handle::new(SubModel::heat_conduction(sub_a).unwrap()))
.unwrap();
model
.add_sub(Handle::new(SubModel::heat_conduction(sub_b).unwrap()))
.unwrap();
let k = crate::ops::matrix::stiffness(&model, &materials).unwrap();
let tol = 1e-12;
let v = |i: NodeId, j: NodeId| k.get(i, "q", j, "T").unwrap();
assert!((v(n0.id(), n0.id()) - k_a).abs() < tol);
assert!((v(n1.id(), n1.id()) - (k_a + k_b)).abs() < tol);
assert!((v(n2.id(), n2.id()) - k_b).abs() < tol);
assert!((v(n0.id(), n1.id()) + k_a).abs() < tol);
assert!((v(n1.id(), n2.id()) + k_b).abs() < tol);
}
#[test]
fn physics_declares_material_components() {
let coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
let sub = fes.get(0).unwrap();
let hc = SubModel::heat_conduction(sub).unwrap();
assert_eq!(hc.material_components(), Some(owned_components(&["k"])));
let imposed =
Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
let dir = SubModel::dirichlet(
"T".into(),
"q".into(),
&imposed,
&multiplier,
None,
None,
Default::default(),
)
.unwrap();
assert!(dir.material_components().is_none());
}
#[test]
fn assemble_errors_when_no_material_matches_fespace() {
let coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
let sub = fes.get(0).unwrap();
let materials = ElementField::empty();
let mut model = Model::empty();
model
.add_sub(Handle::new(SubModel::heat_conduction(sub).unwrap()))
.unwrap();
let err = crate::ops::matrix::stiffness(&model, &materials).unwrap_err();
assert!(format!("{}", err).contains("no SubElementField"));
}
#[test]
fn constraint_rhs_dirichlet_writes_g_at_multiplier() {
let coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords, &[0.0]).unwrap();
let imposed =
Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
let dirichlet = model::dirichlet(
"T".into(),
"q".into(),
&imposed,
&multiplier,
None,
None,
Default::default(),
)
.unwrap();
let rhs = dirichlet.constraint_rhs(&[(a.id(), 3.0)]).unwrap();
let mult_id = multiplier.node(0, 0, 0).unwrap().id();
assert_eq!(rhs.value(mult_id, "imposed_T").unwrap(), 3.0);
assert!(rhs.value(a.id(), "imposed_T").is_err());
}
#[test]
fn constraint_rhs_mpc_keyed_by_any_term_node() {
let coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let b = Node::create_in(coords, &[1.0]).unwrap();
let mesh_a =
Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
let mesh_b =
Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&b)).unwrap());
let mult = crate::ops::mesh::barycenter(&mesh_b).unwrap();
let terms = vec![
crate::models::mpc::MpcTerm::new(&mesh_b, "T".into(), "q".into(), 1.0).unwrap(),
crate::models::mpc::MpcTerm::new(&mesh_a, "T".into(), "q".into(), -1.0).unwrap(),
];
let model = model::mpc(terms, &mult, None, None, Default::default()).unwrap();
let mult_id = mult.node(0, 0, 0).unwrap().id();
let rhs = model.constraint_rhs(&[(b.id(), 2.5)]).unwrap();
assert_eq!(rhs.value(mult_id, "mpc_rhs").unwrap(), 2.5);
let rhs2 = model.constraint_rhs(&[(a.id(), 2.5)]).unwrap();
assert_eq!(rhs2.value(mult_id, "mpc_rhs").unwrap(), 2.5);
}
#[test]
fn constraint_rhs_errors_without_constraint() {
let (_c, _a, _b, model, _m) = build_seg2_heat_model(1.0, 1.0, false);
assert!(model.constraint_rhs(&[]).is_err());
}
#[test]
fn constraint_rhs_rejects_node_keying_several_relations() {
let coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
let c = Node::create_in(coords.clone(), &[2.0]).unwrap();
let m0 = Node::create_in(coords.clone(), &[0.5]).unwrap();
let m1 = Node::create_in(coords.clone(), &[1.5]).unwrap();
let mut t1 = SubMesh::new(coords.clone(), ElementType::POI1);
t1.add_cell(&[a.id()]).unwrap();
t1.add_cell(&[a.id()]).unwrap();
let t1_mesh = Mesh::from_submesh(t1);
let mut t2 = SubMesh::new(coords.clone(), ElementType::POI1);
t2.add_cell(&[b.id()]).unwrap();
t2.add_cell(&[c.id()]).unwrap();
let t2_mesh = Mesh::from_submesh(t2);
let mut mm = SubMesh::new(coords, ElementType::POI1);
mm.add_cell(&[m0.id()]).unwrap();
mm.add_cell(&[m1.id()]).unwrap();
let mult = Mesh::from_submesh(mm);
let terms = vec![
crate::models::mpc::MpcTerm::new(&t1_mesh, "T".into(), "q".into(), 1.0).unwrap(),
crate::models::mpc::MpcTerm::new(&t2_mesh, "T".into(), "q".into(), -1.0).unwrap(),
];
let model = model::mpc(terms, &mult, None, None, Default::default()).unwrap();
assert!(model.constraint_rhs(&[(a.id(), 1.0)]).is_err());
let rhs = model.constraint_rhs(&[(b.id(), 1.0)]).unwrap();
assert_eq!(rhs.value(m0.id(), "mpc_rhs").unwrap(), 1.0);
assert_eq!(rhs.value(m1.id(), "mpc_rhs").unwrap(), 0.0);
let by_idx = model.constraint_rhs_by_index(&[(1, 4.0)]).unwrap();
assert_eq!(by_idx.value(m1.id(), "mpc_rhs").unwrap(), 4.0);
assert_eq!(by_idx.value(m0.id(), "mpc_rhs").unwrap(), 0.0);
}
#[test]
fn constraint_rhs_by_index_writes_and_bounds_checks() {
let coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords, &[0.0]).unwrap();
let imposed =
Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
let multiplier = crate::ops::mesh::barycenter(&imposed).unwrap();
let dirichlet = model::dirichlet(
"T".into(),
"q".into(),
&imposed,
&multiplier,
None,
None,
Default::default(),
)
.unwrap();
let mult_id = multiplier.node(0, 0, 0).unwrap().id();
let rhs = dirichlet.constraint_rhs_by_index(&[(0, 2.0)]).unwrap();
assert_eq!(rhs.value(mult_id, "imposed_T").unwrap(), 2.0);
assert!(dirichlet.constraint_rhs_by_index(&[(1, 2.0)]).is_err());
}
}