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, flux,
heat_conduction, interface_transfer, mpc, plasticity, radiation, shell, timoshenko, truss,
Constraint, MatrixKind, Physics, RelationSense, SubModelKind,
};
use crate::ops::element_field::StrainMeasure;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::sync::{Arc, OnceLock};
fn insert_relation_value(
values: &mut std::collections::HashMap<NodeId, f64>,
multiplier_node: NodeId,
g: f64,
caller: &str,
) -> Result<()> {
if let Some(prev) = values.insert(multiplier_node, g)
&& prev != g
{
return Err(PyrucastError::Message(format!(
"{caller}: conflicting values ({prev} and {g}) for the same relation \
(multiplier node {multiplier_node})"
)));
}
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),
Damage(damage::Damage),
Timoshenko(timoshenko::Timoshenko),
Fick(fick::Fick),
InterfaceTransfer(interface_transfer::InterfaceTransfer),
Radiation(radiation::Radiation),
Bernoulli(bernoulli::Bernoulli),
Shell(shell::Shell),
Flux(flux::Flux),
}
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::Damage(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,
SubModel::Flux(p) => p,
}
}
pub fn flux(
fespace: Handle<SubFiniteElementSpace>,
target: &Model,
dual: &str,
) -> Result<Self> {
Ok(SubModel::Flux(flux::Flux::new(fespace, target, dual)?))
}
pub fn heat_conduction(
fespace: Handle<SubFiniteElementSpace>,
symmetry: MaterialSymmetry,
) -> Result<Self> {
Ok(SubModel::HeatConduction(
heat_conduction::HeatConduction::new(fespace, symmetry)?,
))
}
pub fn boundary_transfer(
fespace: Handle<SubFiniteElementSpace>,
target: &Model,
variables: Vec<String>,
) -> Result<Self> {
Ok(SubModel::BoundaryTransfer(
boundary_transfer::BoundaryTransfer::new(fespace, target, variables)?,
))
}
pub fn truss(
fespace: Handle<SubFiniteElementSpace>,
strain_measure: StrainMeasure,
) -> Result<Self> {
Ok(SubModel::Truss(truss::Truss::new(fespace, strain_measure)?))
}
pub fn elasticity(
fespace: Handle<SubFiniteElementSpace>,
kinematics: Kinematics,
symmetry: MaterialSymmetry,
strain_measure: StrainMeasure,
) -> Result<Self> {
Ok(SubModel::Elasticity(elasticity::Elasticity::new(
fespace,
kinematics,
symmetry,
strain_measure,
)?))
}
pub fn fick(
fespace: Handle<SubFiniteElementSpace>,
species: &str,
symmetry: MaterialSymmetry,
) -> Result<Self> {
Ok(SubModel::Fick(fick::Fick::new(fespace, species, symmetry)?))
}
pub fn radiation(fespace: Handle<SubFiniteElementSpace>, target: &Model) -> Result<Self> {
Ok(SubModel::Radiation(radiation::Radiation::new(
fespace, target,
)?))
}
pub fn bernoulli(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
Ok(SubModel::Bernoulli(bernoulli::Bernoulli::new(fespace)?))
}
pub fn shell(
fespace: Handle<SubFiniteElementSpace>,
formulation: shell::ShellFormulation,
) -> Result<Self> {
Ok(SubModel::Shell(shell::Shell::new(fespace, formulation)?))
}
pub fn interface_transfer(
side_a: Handle<SubFiniteElementSpace>,
side_b: Handle<SubFiniteElementSpace>,
target: &Model,
variables: Vec<String>,
tol: f64,
) -> Result<Self> {
Ok(SubModel::InterfaceTransfer(
interface_transfer::InterfaceTransfer::new(side_a, side_b, target, variables, tol)?,
))
}
pub fn plasticity(
fespace: Handle<SubFiniteElementSpace>,
kinematics: Kinematics,
law: plasticity::law::PlasticLaw,
strain_measure: StrainMeasure,
) -> Result<Self> {
Ok(SubModel::Plasticity(plasticity::Plasticity::new(
fespace,
kinematics,
law,
strain_measure,
)?))
}
pub fn damage(
fespace: Handle<SubFiniteElementSpace>,
kinematics: Kinematics,
law: damage::law::DamageLaw,
strain_measure: StrainMeasure,
) -> Result<Self> {
Ok(SubModel::Damage(damage::Damage::new(
fespace,
kinematics,
law,
strain_measure,
)?))
}
pub fn timoshenko(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
Ok(SubModel::Timoshenko(timoshenko::Timoshenko::new(fespace)?))
}
pub fn dirichlet(
imposed_mesh: &Mesh,
target: &Model,
variable: &str,
sense: RelationSense,
) -> Result<Self> {
Ok(SubModel::Dirichlet(dirichlet::Dirichlet::new(
imposed_mesh,
target,
variable,
sense,
)?))
}
pub fn mpc(terms: &[(&Mesh, &str, f64)], target: &Model, sense: RelationSense) -> Result<Self> {
Ok(SubModel::Mpc(mpc::Mpc::new(terms, target, sense)?))
}
pub fn embedded(
immersed: &Mesh,
host: &Mesh,
target: &Model,
variables: Vec<String>,
tol: f64,
) -> Result<Self> {
Ok(SubModel::Embedded(embedded::Embedded::new(
immersed, host, target, variables, tol,
)?))
}
pub fn contact(
slave: &Mesh,
master: &Mesh,
target: &Model,
variables: Vec<String>,
) -> Result<Self> {
Ok(SubModel::Contact(contact::Contact::new(
slave, master, target, variables,
)?))
}
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) -> 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());
}
}
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 relations = self.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, 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,
};
insert_relation_value(
&mut values,
relations[idx].multiplier_node,
g,
"constraint_rhs",
)?;
}
self.multiplier_load(&values)
}
pub fn constraint_rhs_by_index(&self, imposed: &[(usize, f64)]) -> Result<NodeField> {
let relations = self.constraint()?.relations()?;
let mut values: std::collections::HashMap<NodeId, 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,
g,
"constraint_rhs_by_index",
)?;
}
self.multiplier_load(&values)
}
fn constraint(&self) -> Result<&dyn Constraint> {
let kind = self.as_kind();
kind.as_constraint().ok_or_else(|| {
PyrucastError::Message(format!(
"constraint_rhs: sub-model {} is not a constraint (it has no multipliers)",
kind.label()
))
})
}
fn multiplier_load(
&self,
values: &std::collections::HashMap<NodeId, f64>,
) -> Result<NodeField> {
use crate::containers::field::SubField;
let mut field = NodeField::default();
for sm in &self.multiplier_mesh()? {
let mut sub = SubNodeField::from_poi1(sm, vec![crate::models::IMPOSED.to_string()])?;
let support = sm.read();
let index = support.node_index();
let vals = sub.values_mut();
for (nid, &g) in values {
let Some(&ni) = index.get(nid) else {
continue; };
vals[ni] = g;
}
drop(support);
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 label(&self) -> &'static str {
self.as_kind().label()
}
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_behavior().map(|b| b.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_behavior()
.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_behavior()
.is_some_and(|b| b.requires_dt())
}
pub(crate) fn initial_state(
&self,
material: &Handle<SubElementField>,
) -> Result<SubElementField> {
self.as_kind()
.as_behavior()
.ok_or_else(|| {
crate::error::PyrucastError::Message(format!(
"{}: no behaviour — initial_state is undefined",
self.as_kind().label()
))
})?
.initial_state(&material.read())
}
}
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 {
format!(
"{}\n physics: {:?}",
self.as_kind().render(opts).trim_end(),
self.as_kind().physics()
)
}
}
#[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 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) -> Option<String> {
for h in self {
if let Some(dual) = h.read().dual_of(variable) {
return Some(dual);
}
}
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) -> Vec<String> {
let mut all: Vec<String> = Vec::new();
for h in self {
all.extend(h.read().primal_vars());
}
union_names(all)
}
pub fn dual_vars(&self) -> Vec<String> {
let mut all: Vec<String> = Vec::new();
for h in self {
all.extend(h.read().dual_vars());
}
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) -> Model {
self.keep(|natures| natures.contains(&physics))
}
pub fn exclude(&self, physics: Physics) -> Model {
self.keep(|natures| !natures.contains(&physics))
}
pub(crate) fn map_contacts(
&self,
update: impl Fn(&crate::models::contact::Contact) -> crate::models::contact::Contact,
) -> Model {
let mut out = Model::empty();
for h in self {
let updated = match &*h.read() {
SubModel::Contact(c) => Some(Handle::new(SubModel::Contact(update(c)))),
_ => None,
};
out.push(updated.unwrap_or_else(|| h.clone()));
}
out.post_push();
out
}
fn keep(&self, keep: impl Fn(&[Physics]) -> bool) -> Model {
let mut out = Model::empty();
for h in self {
if keep(h.read().physics()) {
out.push(h.clone());
}
}
out.post_push();
out
}
}
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 {
#[cfg(test)]
fn target_conduction(coords: &Handle<Coords>, a: &Node) -> Model {
let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
let mut sm = SubMesh::new(coords.clone(), crate::atoms::ElementType::SEG2);
sm.add_cell(&[a.id(), b.id()]).unwrap();
let fes = crate::containers::finite_element_space::FiniteElementSpace::lagrange1(
&Mesh::from_submesh(sm),
)
.unwrap();
crate::ops::model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap()
}
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, IMPOSED};
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, MaterialSymmetry::Isotropic).unwrap(),
))
.unwrap();
if dirichlet_at_left {
let imposed =
Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
model
.add_sub(Handle::new(
SubModel::dirichlet(&imposed, &model, "T", 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(), vec!["T".to_string()]);
assert_eq!(model.dual_vars(), 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(),
vec!["T".to_string(), "lambda".to_string()]
);
assert_eq!(
model.dual_vars(),
vec!["q".to_string(), "imposed".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, Physics::Thermal]
]
);
}
#[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);
assert_eq!(thermal.len(), 2);
let conduction = thermal.exclude(Physics::Constraint);
assert_eq!(conduction.len(), 1);
assert_eq!(
conduction.get(0).unwrap().read().physics(),
&[Physics::Thermal]
);
let constraint = model.filter(Physics::Constraint);
assert_eq!(constraint.len(), 1);
assert_eq!(
constraint.get(0).unwrap().read().physics(),
&[Physics::Constraint, Physics::Thermal]
);
assert_eq!(model.filter(Physics::Mechanical).len(), 0);
assert_eq!(model.exclude(Physics::Mechanical).len(), 2);
}
#[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();
assert!(present.contains(&Physics::Thermal));
assert!(present.contains(&Physics::Constraint));
let constraint = k.filter(Physics::Constraint);
assert_eq!(constraint.len(), 2);
for h in &constraint {
assert_eq!(h.read().physics(), &[Physics::Constraint, Physics::Thermal]);
}
let thermal = k.filter(Physics::Thermal);
assert_eq!(thermal.len(), 3);
assert_eq!(thermal.exclude(Physics::Constraint).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, MaterialSymmetry::Isotropic).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")
.expect("multiplier row missing")
.0;
assert_eq!(k.get(mult, "imposed", a_id, "T").unwrap(), 1.0);
assert_eq!(k.get(a_id, "q", mult, "lambda").unwrap(), 1.0);
let col_dofs = k.col_dofs().unwrap();
let lambda_col_present = col_dofs
.iter()
.any(|(n, name)| name == "lambda" && *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 cible = target_conduction(&coords, &a);
let sub = SubModel::dirichlet(&imposed, &cible, "T", Default::default()).unwrap();
let mult_id = sub.multiplier_nodes()[0];
assert_ne!(mult_id, a.id());
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 coords = Handle::new(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let cible = target_conduction(&coords, &a);
let empty = Mesh::empty();
assert!(SubModel::dirichlet(&empty, &cible, "T", 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, MaterialSymmetry::Isotropic).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(), Vec::<String>::new());
assert_eq!(model.dual_vars(), 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, MaterialSymmetry::Isotropic).unwrap();
assert_eq!(hc.len(), 2);
assert_eq!(hc.primal_vars(), vec!["T".to_string()]);
assert_eq!(hc.dual_vars(), vec!["q".to_string()]);
let imp = Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&n0)).unwrap());
let dir = model::dirichlet(&imp, &hc, "T", Default::default()).unwrap();
assert_eq!(dir.len(), 1);
let full = hc.union(&dir).unwrap();
assert_eq!(full.len(), 3);
assert_eq!(
full.primal_vars(),
vec!["T".to_string(), "lambda".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, MaterialSymmetry::Isotropic).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, MaterialSymmetry::Isotropic).unwrap(),
))
.unwrap();
model
.add_sub(Handle::new(
SubModel::heat_conduction(sub_b, MaterialSymmetry::Isotropic).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, MaterialSymmetry::Isotropic).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 cible = target_conduction(&coords, &a);
let dir = SubModel::dirichlet(&imposed, &cible, "T", 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, MaterialSymmetry::Isotropic).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.clone(), &[0.0]).unwrap();
let imposed =
Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
let cible = target_conduction(&coords, &a);
let dirichlet = model::dirichlet(&imposed, &cible, "T", Default::default()).unwrap();
let rhs = dirichlet.constraint_rhs(&[(a.id(), 3.0)]).unwrap();
let mult_id = dirichlet
.multiplier_mesh()
.unwrap()
.node(0, 0, 0)
.unwrap()
.id();
assert_eq!(rhs.value(mult_id, "imposed").unwrap(), 3.0);
assert!(rhs.value(a.id(), "imposed").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 cible = target_conduction(&a.coords(), &a);
let model = model::mpc(
&[(&mesh_b, "T", 1.0), (&mesh_a, "T", -1.0)],
&cible,
Default::default(),
)
.unwrap();
let mult_id = model.multiplier_mesh().unwrap().node(0, 0, 0).unwrap().id();
let rhs = model.constraint_rhs(&[(b.id(), 2.5)]).unwrap();
assert_eq!(rhs.value(mult_id, IMPOSED).unwrap(), 2.5);
let rhs2 = model.constraint_rhs(&[(a.id(), 2.5)]).unwrap();
assert_eq!(rhs2.value(mult_id, IMPOSED).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 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, ElementType::POI1);
t2.add_cell(&[b.id()]).unwrap();
t2.add_cell(&[c.id()]).unwrap();
let t2_mesh = Mesh::from_submesh(t2);
let cible = target_conduction(&a.coords(), &a);
let model = model::mpc(
&[(&t1_mesh, "T", 1.0), (&t2_mesh, "T", -1.0)],
&cible,
Default::default(),
)
.unwrap();
let mults = model.multiplier_mesh().unwrap();
let (m0, m1) = (
mults.node(0, 0, 0).unwrap().id(),
mults.node(0, 1, 0).unwrap().id(),
);
assert_ne!(m0, m1);
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, IMPOSED).unwrap(), 1.0);
assert_eq!(rhs.value(m1, IMPOSED).unwrap(), 0.0);
let by_idx = model.constraint_rhs_by_index(&[(1, 4.0)]).unwrap();
assert_eq!(by_idx.value(m1, IMPOSED).unwrap(), 4.0);
assert_eq!(by_idx.value(m0, IMPOSED).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.clone(), &[0.0]).unwrap();
let imposed =
Mesh::from_submesh(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
let cible = target_conduction(&coords, &a);
let dirichlet = model::dirichlet(&imposed, &cible, "T", Default::default()).unwrap();
let mult_id = dirichlet
.multiplier_mesh()
.unwrap()
.node(0, 0, 0)
.unwrap()
.id();
let rhs = dirichlet.constraint_rhs_by_index(&[(0, 2.0)]).unwrap();
assert_eq!(rhs.value(mult_id, "imposed").unwrap(), 2.0);
assert!(dirichlet.constraint_rhs_by_index(&[(1, 2.0)]).is_err());
}
}