use crate::aggregate::Aggregate;
use crate::containers::element_field::SubElementField;
use crate::containers::mesh::Mesh;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::models::transfer::{constrained_physics, constraint_physics};
use crate::models::{
constraint_block_pair, Constraint, ConstraintTerm, Contribution, MatrixKind, Physics, Relation,
RelationSense, SubModelKind, IMPOSED, MULTIPLIER,
};
use crate::ops::mesh::barycenter;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct Dirichlet {
pub(crate) imposed_variable: String,
pub(crate) target_dual: String,
pub(crate) imposed_mesh: Mesh,
pub(crate) multiplier_mesh: Mesh,
pub(crate) sense: RelationSense,
pub(crate) target_physics: Option<Physics>,
}
impl Dirichlet {
pub fn new(
imposed_mesh: &Mesh,
target: &crate::containers::model::Model,
variable: &str,
sense: RelationSense,
) -> Result<Self> {
let imposed_variable = variable.to_string();
let target_dual = target.dual_of(variable).ok_or_else(|| {
PyrucastError::Message(format!(
"Dirichlet: `{variable}` is not a primal of the model it constrains — it \
declares {:?}",
target.primal_vars()
))
})?;
if imposed_mesh.cell_count() == 0 {
return Err(PyrucastError::Message(
"Dirichlet: imposed_mesh must constrain at least one node".into(),
));
}
let imposed = imposed_mesh.to_poi1().consolidate();
let multiplier_mesh = barycenter(&imposed)?;
let target_physics = constrained_physics(target, [imposed_variable.as_str()]);
Ok(Self {
imposed_variable,
target_dual,
imposed_mesh: imposed,
multiplier_mesh,
sense,
target_physics,
})
}
}
impl SubModelKind for Dirichlet {
fn primal_vars(&self) -> Vec<String> {
vec![MULTIPLIER.to_string()]
}
fn dual_vars(&self) -> Vec<String> {
vec![IMPOSED.to_string()]
}
fn internal_force_contribution(&self) -> Vec<crate::models::ResidualContribution> {
vec![crate::models::ResidualContribution::Relations]
}
fn as_constraint(&self) -> Option<&dyn Constraint> {
Some(self)
}
fn contributions(
&self,
kind: MatrixKind,
_material: Option<&crate::handle::Handle<SubElementField>>,
) -> Result<Vec<Contribution>> {
if kind != MatrixKind::Stiffness {
return Ok(Vec::new());
}
let mut blocks = Vec::with_capacity(self.imposed_mesh.len() * 2);
for i in 0..self.imposed_mesh.len() {
let imp_sm = self.imposed_mesh.get(i)?;
let mult_sm = self.multiplier_mesh.get(i)?;
let (c_block, ct_block) = constraint_block_pair(
&mult_sm,
&imp_sm,
&self.imposed_variable,
&self.target_dual,
1.0,
self.sense,
)?;
blocks.push(c_block);
blocks.push(ct_block);
}
Ok(vec![Contribution::Literal(blocks)])
}
fn tangent_is_stiffness(&self) -> bool {
true
}
fn physics(&self) -> &'static [Physics] {
constraint_physics(self.target_physics)
}
fn label(&self) -> &'static str {
"Dirichlet"
}
fn display(&self) -> String {
let n = self.imposed_mesh.cell_count();
format!(
"SubModel<Dirichlet({})>: {} constrained node(s)",
self.imposed_variable, n
)
}
fn render(&self, _opts: &DumpOptions) -> String {
let nc = self.imposed_mesh.cell_count();
let nm = self.multiplier_mesh.cell_count();
format!(
"SubModel<Dirichlet({imposed_variable})>\n primal var(s): {MULTIPLIER} \
(multiplier)\n dual var(s): {IMPOSED} (imposed value)\n \
targets primary dual: {target_dual}\n sense: {sense}\n \
constrained: {nc} node(s)\n multipliers: {nm} node(s)",
imposed_variable = self.imposed_variable,
target_dual = self.target_dual,
sense = self.sense,
)
}
}
impl Constraint for Dirichlet {
fn multiplier_mesh(&self) -> &Mesh {
&self.multiplier_mesh
}
fn relations(&self) -> Result<Vec<Relation>> {
let mut relations = Vec::with_capacity(self.imposed_mesh.cell_count());
for i in 0..self.imposed_mesh.len() {
let imposed = self.imposed_mesh.get(i)?.read();
let multiplier = self.multiplier_mesh.get(i)?.read();
for (imp, mult) in imposed
.connectivity()
.iter()
.zip(multiplier.connectivity().iter())
{
relations.push(Relation {
multiplier_node: *mult,
terms: vec![ConstraintTerm {
node: *imp,
variable: self.imposed_variable.clone(),
target_dual: self.target_dual.clone(),
coefficient: 1.0,
}],
sense: self.sense,
});
}
}
Ok(relations)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::atoms::{ElementType, Node, NodeId};
use crate::containers::finite_element_space::FiniteElementSpace;
use crate::containers::mesh::SubMesh;
use crate::containers::model::Model;
use crate::containers::node_field::NodeField;
use crate::coords::Coords;
use crate::handle::Handle;
use crate::models::symmetry::MaterialSymmetry;
use crate::ops::{element_field, matrix, mesh, model, node_field, solver};
use std::collections::HashSet;
fn plate() -> (Mesh, FiniteElementSpace, Model) {
let coords = Handle::new(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords, &[0.10, 0.0]).unwrap();
let edge = mesh::line(&a, &b, 20, ElementType::SEG2).unwrap();
let plate = mesh::extrude(&edge, &[0.0, 0.10], 20).unwrap();
let fes = FiniteElementSpace::lagrange1(&plate).unwrap();
let conduction = model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
(plate, fes, conduction)
}
fn solve_holding(fes: &FiniteElementSpace, conduction: &Model, imposed: &Mesh) -> NodeField {
let held = model::dirichlet(imposed, conduction, "T", RelationSense::Equality).unwrap();
let source = model::flux(fes, conduction, "q").unwrap();
let whole = conduction.union(&held).unwrap().union(&source).unwrap();
let materials =
element_field::material_field(&whole, &[("k", 50.0), ("phi_q", 1.0e6)]).unwrap();
let k = matrix::stiffness(&whole, &materials).unwrap();
let rhs = node_field::external_forces(&whole, &materials).unwrap();
solver::solve(&k, &rhs).unwrap()
}
fn distinct_nodes(mesh: &Mesh) -> HashSet<NodeId> {
mesh.iter()
.flat_map(|zone| zone.read().connectivity().to_vec())
.collect()
}
#[test]
fn holds_an_edge_through_its_poi1_companion() {
let (plate, fes, conduction) = plate();
let border = mesh::border(&plate, None).unwrap();
let on_edge = Dirichlet::new(&border, &conduction, "T", RelationSense::Equality).unwrap();
let on_points = Dirichlet::new(
&mesh::to_poi1(&border),
&conduction,
"T",
RelationSense::Equality,
)
.unwrap();
assert_eq!(distinct_nodes(&border).len(), 80);
assert_eq!(on_edge.imposed_mesh.cell_count(), 80);
let companion = SubMesh::to_poi1(&border.get(0).unwrap());
assert!(on_edge.imposed_mesh.get(0).unwrap().same_object(&companion));
assert!(on_points
.imposed_mesh
.get(0)
.unwrap()
.same_object(&companion));
let nodes: Vec<NodeId> = SubMesh::to_poi1(&plate.get(0).unwrap())
.read()
.connectivity()
.to_vec();
let t_edge = solve_holding(&fes, &conduction, &border);
let t_points = solve_holding(&fes, &conduction, &mesh::to_poi1(&border));
let edge_values = t_edge.values_at(&nodes, "T").unwrap();
let points_values = t_points.values_at(&nodes, "T").unwrap();
let t_max = edge_values.iter().cloned().fold(f64::MIN, f64::max);
for (e, p) in edge_values.iter().zip(&points_values) {
assert!((e - p).abs() <= 1e-12 * t_max, "{e} vs {p}");
}
assert!((t_max - 14.76).abs() < 5e-3, "T max = {t_max}");
}
#[test]
fn keeps_a_poi1_zone_given_as_it_is() {
let (plate, _fes, conduction) = plate();
let corner = mesh::poi1_from_nodes(&[plate.node(0, 0, 0).unwrap()]).unwrap();
let held = Dirichlet::new(&corner, &conduction, "T", RelationSense::Equality).unwrap();
assert!(held
.imposed_mesh
.get(0)
.unwrap()
.same_object(&corner.get(0).unwrap()));
}
#[test]
fn gives_a_node_two_zones_share_one_relation() {
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 d = Node::create_in(coords, &[2.0]).unwrap();
let bar = mesh::line(&a, &d, 2, ElementType::SEG2).unwrap();
let halves = mesh::line(&a, &b, 1, ElementType::SEG2)
.unwrap()
.union(&mesh::line(&b, &d, 1, ElementType::SEG2).unwrap())
.unwrap();
assert_eq!(halves.len(), 2);
let fes = FiniteElementSpace::lagrange1(&bar).unwrap();
let conduction = model::heat_conduction(&fes, MaterialSymmetry::Isotropic).unwrap();
let held = Dirichlet::new(&halves, &conduction, "T", RelationSense::Equality).unwrap();
assert_eq!(distinct_nodes(&halves).len(), 3);
assert_eq!(held.imposed_mesh.len(), 1);
assert_eq!(held.imposed_mesh.cell_count(), 3);
let whole = conduction
.union(&model::dirichlet(&halves, &conduction, "T", RelationSense::Equality).unwrap())
.unwrap();
let materials = element_field::material_field(&whole, &[("k", 1.0)]).unwrap();
let k = matrix::stiffness(&whole, &materials).unwrap();
let rhs = node_field::external_forces(&whole, &materials).unwrap();
let t = solver::solve(&k, &rhs).unwrap();
assert_eq!(t.value(b.id(), "T").unwrap(), 0.0);
}
}