use crate::containers::element_field::SubElementField;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::matrix::DofOrdering;
use crate::containers::mesh::SubMesh;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::models::{CellGeom, Domain, MatrixLayout, Physics, SubModelKind};
use crate::store::{read, Handle};
use serde::{Deserialize, Serialize};
const AXES: [&str; 3] = ["x", "y", "z"];
const MATERIAL_COMPONENTS: &[&str] = &["E", "nu"];
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ElasticityModel {
PlaneStress,
PlaneStrain,
Axisymmetric,
Solid,
}
impl ElasticityModel {
pub fn from_tag(tag: &str) -> Option<Self> {
match tag {
"plane_stress" => Some(Self::PlaneStress),
"plane_strain" => Some(Self::PlaneStrain),
"axisymmetric" => Some(Self::Axisymmetric),
"solid" => Some(Self::Solid),
_ => None,
}
}
pub fn is_axisymmetric(self) -> bool {
self == Self::Axisymmetric
}
}
fn primal_name(a: usize) -> String {
format!("u_{}", AXES[a])
}
fn dual_name(a: usize) -> String {
format!("f_{}", AXES[a])
}
fn voigt_size(space_dim: usize, model: ElasticityModel) -> usize {
match (space_dim, model) {
(2, ElasticityModel::Axisymmetric) => 4,
(2, _) => 3,
_ => 6,
}
}
fn stress_names(space_dim: usize, model: ElasticityModel) -> Vec<String> {
match (space_dim, model) {
(2, ElasticityModel::Axisymmetric) => vec![
"sigma_xx".into(),
"sigma_yy".into(),
"sigma_zz".into(),
"sigma_xy".into(),
],
(2, _) => vec!["sigma_xx".into(), "sigma_yy".into(), "sigma_xy".into()],
_ => vec![
"sigma_xx".into(),
"sigma_yy".into(),
"sigma_zz".into(),
"sigma_yz".into(),
"sigma_xz".into(),
"sigma_xy".into(),
],
}
}
pub(crate) fn check_continuum_dimensions(
label: &str,
space_dim: usize,
ref_dim: usize,
) -> Result<()> {
if ref_dim != space_dim {
return Err(PyrucastError::Message(format!(
"{label}: a {ref_dim}-D element in a {space_dim}-D space is a manifold, not a \
solid — a boundary mesh carries loads (flux, convection), and a bar or beam \
is a structural physics of its own (truss, frame, timoshenko)"
)));
}
Ok(())
}
#[derive(Clone, Serialize, Deserialize)]
pub struct Elasticity {
pub(crate) fespace: Handle<SubFiniteElementSpace>,
pub(crate) support: Handle<SubMesh>,
pub(crate) space_dim: usize,
pub(crate) model: ElasticityModel,
}
impl Elasticity {
pub fn new(fespace: Handle<SubFiniteElementSpace>, model: ElasticityModel) -> Result<Self> {
let (submesh, space_dim, ref_dim, axisymmetric) = {
let s = read(&fespace)?;
(
s.submesh(),
s.space_dim(),
s.ref_dim()?,
s.is_axisymmetric(),
)
};
check_continuum_dimensions("Elasticity", space_dim, ref_dim)?;
#[allow(clippy::match_like_matches_macro)]
let ok = match (space_dim, model) {
(2, ElasticityModel::PlaneStress | ElasticityModel::PlaneStrain) => true,
(2, ElasticityModel::Axisymmetric) => true,
(3, ElasticityModel::Solid) => true,
_ => false,
};
if !ok {
return Err(PyrucastError::Message(format!(
"Elasticity: model {model:?} is incompatible with a {space_dim}-D space \
(2-D ⇒ plane_stress|plane_strain|axisymmetric, 3-D ⇒ solid)"
)));
}
if axisymmetric != model.is_axisymmetric() {
return Err(PyrucastError::Message(if axisymmetric {
format!(
"Elasticity: model {model:?} on an axisymmetric geometry — a body of \
revolution requires the `axisymmetric` model (its integrals already \
carry the 2πr factor)"
)
} else {
"Elasticity: the `axisymmetric` model requires an axisymmetric geometry \
(build the Coords with Coords::axisymmetric)"
.into()
}));
}
let support = read(&submesh)?.to_poi1()?;
Ok(Self {
fespace,
support,
space_dim,
model,
})
}
}
impl SubModelKind for Elasticity {
fn primal_vars(&self) -> Vec<String> {
(0..self.space_dim).map(primal_name).collect()
}
fn dual_vars(&self) -> Vec<String> {
(0..self.space_dim).map(dual_name).collect()
}
fn as_domain(&self) -> Option<&dyn Domain> {
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,
symmetric: true,
})
}
fn mass_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
fn geometric_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
fn element_geometric(
&self,
geoms: &[CellGeom],
_material: Option<&SubElementField>,
state: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let stress = state.expect("geometric stiffness requires the current stress field");
element_geometric(geom, stress, ke)
}
fn tangent_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
fn element_tangent(
&self,
geoms: &[CellGeom],
material: Option<&SubElementField>,
_state: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let mat = material.expect("Elasticity declares a material_fespace ⇒ material is supplied");
element_stiffness(geom, mat, self.model, ke)
}
fn element_matrix(
&self,
geoms: &[CellGeom],
material: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let mat = material.expect("Elasticity declares a material_fespace ⇒ material is supplied");
element_stiffness(geom, mat, self.model, ke)
}
fn element_mass(
&self,
geoms: &[CellGeom],
material: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let mat = material.expect("Elasticity declares a material_fespace ⇒ material is supplied");
element_mass(geom, mat, ke)
}
fn physics(&self) -> &'static [Physics] {
&[Physics::Mechanical]
}
fn label(&self) -> &'static str {
"Elasticity"
}
fn render(&self, _opts: &DumpOptions) -> String {
let primal = self.primal_vars().join(", ");
let dual = self.dual_vars().join(", ");
let n = read(&self.support).map(|s| s.cell_count()).unwrap_or(0);
format!(
"SubModel<Elasticity({:?})>\n primal var(s): {primal}\n dual var(s): {dual}\n \
support: {n} node(s)",
self.model
)
}
}
impl Domain for Elasticity {
fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn material_components(&self) -> Option<&'static [&'static str]> {
Some(MATERIAL_COMPONENTS)
}
fn optional_material_components(&self) -> &'static [&'static str] {
&["alpha", "rho"]
}
fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn behavior_output_components(&self) -> Result<Vec<String>> {
Ok(stress_names(self.space_dim, self.model))
}
fn integrate_point(
&self,
geom: &CellGeom,
input: &SubElementField,
_prev: Option<&SubElementField>,
material: Option<&SubElementField>,
g: usize,
_dt: Option<f64>,
out: &mut [f64],
) -> Result<()> {
let mat = material.expect("Elasticity declares a material_fespace ⇒ material is supplied");
let (cell, d) = (geom.cell, self.space_dim);
let e = mat.value(cell, 0, "E")?;
let nu = mat.value(cell, 0, "nu")?;
let dmat = constitutive(e, nu, self.model, d);
let strain = voigt_strain(&|name| input.value(cell, g, name), d, self.model)?;
for (r, drow) in dmat.iter().enumerate() {
out[r] = drow.iter().zip(&strain).map(|(dv, s)| dv * s).sum();
}
Ok(())
}
}
pub fn constitutive(e: f64, nu: f64, model: ElasticityModel, space_dim: usize) -> Vec<Vec<f64>> {
match (space_dim, model) {
(2, ElasticityModel::PlaneStress) => {
let c = e / (1.0 - nu * nu);
vec![
vec![c, c * nu, 0.0],
vec![c * nu, c, 0.0],
vec![0.0, 0.0, c * (1.0 - nu) / 2.0],
]
}
(2, ElasticityModel::PlaneStrain) => {
let c = e / ((1.0 + nu) * (1.0 - 2.0 * nu));
vec![
vec![c * (1.0 - nu), c * nu, 0.0],
vec![c * nu, c * (1.0 - nu), 0.0],
vec![0.0, 0.0, c * (1.0 - 2.0 * nu) / 2.0],
]
}
(2, ElasticityModel::Axisymmetric) => {
let c = e / ((1.0 + nu) * (1.0 - 2.0 * nu));
let (d_n, d_off) = (c * (1.0 - nu), c * nu);
vec![
vec![d_n, d_off, d_off, 0.0],
vec![d_off, d_n, d_off, 0.0],
vec![d_off, d_off, d_n, 0.0],
vec![0.0, 0.0, 0.0, c * (1.0 - 2.0 * nu) / 2.0],
]
}
_ => {
let c = e / ((1.0 + nu) * (1.0 - 2.0 * nu));
let g = c * (1.0 - 2.0 * nu) / 2.0;
let mut d = vec![vec![0.0; 6]; 6];
for i in 0..3 {
for j in 0..3 {
d[i][j] = if i == j { c * (1.0 - nu) } else { c * nu };
}
}
d[3][3] = g;
d[4][4] = g;
d[5][5] = g;
d
}
}
}
fn voigt_strain(
eps: &dyn Fn(&str) -> Result<f64>,
space_dim: usize,
model: ElasticityModel,
) -> Result<Vec<f64>> {
if space_dim == 2 && model.is_axisymmetric() {
Ok(vec![
eps("eps_xx")?,
eps("eps_yy")?,
eps("eps_zz")?,
2.0 * eps("eps_xy")?,
])
} else if space_dim == 2 {
Ok(vec![eps("eps_xx")?, eps("eps_yy")?, 2.0 * eps("eps_xy")?])
} else {
Ok(vec![
eps("eps_xx")?,
eps("eps_yy")?,
eps("eps_zz")?,
2.0 * eps("eps_yz")?,
2.0 * eps("eps_xz")?,
2.0 * eps("eps_xy")?,
])
}
}
fn b_matrix(
dn_dx: &[f64],
n_nodes: usize,
space_dim: usize,
hoop: Option<(&[f64], f64)>,
) -> Vec<Vec<f64>> {
let v = match hoop {
Some(_) => 4,
None => voigt_size(space_dim, ElasticityModel::PlaneStrain),
};
let dofs = space_dim * n_nodes;
let mut b = vec![vec![0.0; dofs]; v];
let dn = |i: usize, a: usize| dn_dx[i * space_dim + a];
for i in 0..n_nodes {
if let Some((n, r)) = hoop {
let (cr, cz) = (2 * i, 2 * i + 1);
b[0][cr] = dn(i, 0); b[1][cz] = dn(i, 1); b[2][cr] = n[i] / r; b[3][cr] = dn(i, 1); b[3][cz] = dn(i, 0);
} else if space_dim == 2 {
let (cx, cy) = (2 * i, 2 * i + 1);
b[0][cx] = dn(i, 0); b[1][cy] = dn(i, 1); b[2][cx] = dn(i, 1); b[2][cy] = dn(i, 0);
} else {
let (cx, cy, cz) = (3 * i, 3 * i + 1, 3 * i + 2);
b[0][cx] = dn(i, 0); b[1][cy] = dn(i, 1); b[2][cz] = dn(i, 2); b[3][cy] = dn(i, 2); b[3][cz] = dn(i, 1);
b[4][cx] = dn(i, 2); b[4][cz] = dn(i, 0);
b[5][cx] = dn(i, 1); b[5][cy] = dn(i, 0);
}
}
b
}
pub fn element_stiffness(
geom: &CellGeom,
material: &SubElementField,
model: ElasticityModel,
ke: &mut [f64],
) -> Result<()> {
let n_nodes = geom.n_nodes;
let space_dim = geom.space_dim;
let dofs = space_dim * n_nodes;
let d = constitutive(
material.value(geom.cell, 0, "E")?,
material.value(geom.cell, 0, "nu")?,
model,
space_dim,
);
let v = d.len();
for g in 0..geom.n_gauss {
let hoop = if model.is_axisymmetric() {
Some((geom.n_at_g(g)?, geom.radius(g)?))
} else {
None
};
let b = b_matrix(&geom.dn_dx(g)?, n_nodes, space_dim, hoop);
let mut db = vec![vec![0.0; dofs]; v];
for r in 0..v {
for c in 0..dofs {
let mut acc = 0.0;
for w in 0..v {
acc += d[r][w] * b[w][c];
}
db[r][c] = acc;
}
}
let w = geom.det_j_w(g)?;
for r in 0..dofs {
for c in 0..dofs {
let mut acc = 0.0;
for vv in 0..v {
acc += b[vv][r] * db[vv][c];
}
ke[r * dofs + c] += acc * w;
}
}
}
Ok(())
}
pub fn element_mass(geom: &CellGeom, material: &SubElementField, ke: &mut [f64]) -> Result<()> {
let n_nodes = geom.n_nodes;
let space_dim = geom.space_dim;
let dofs = space_dim * n_nodes;
let rho = material.value(geom.cell, 0, "rho").map_err(|_| {
PyrucastError::Message(
"Elasticity mass matrix: material component `rho` (density) is required".into(),
)
})?;
for g in 0..geom.n_gauss {
let n = geom.n_at_g(g)?;
let w = geom.det_j_w(g)? * rho;
for i in 0..n_nodes {
for j in 0..n_nodes {
let m = n[i] * n[j] * w;
for a in 0..space_dim {
let r = i * space_dim + a;
let c = j * space_dim + a;
ke[r * dofs + c] += m;
}
}
}
}
Ok(())
}
pub fn element_geometric(geom: &CellGeom, stress: &SubElementField, ke: &mut [f64]) -> Result<()> {
let n_nodes = geom.n_nodes;
let d = geom.space_dim;
let dofs = d * n_nodes;
for g in 0..geom.n_gauss {
let dn = geom.dn_dx(g)?; let w = geom.det_j_w(g)?;
let sig = crate::models::voigt_stress_matrix(stress, geom.cell, g, d)?; let hoop = if geom.axisymmetric {
let r = geom.radius(g)?;
Some((
geom.n_at_g(g)?,
stress.value(geom.cell, g, "sigma_zz")? / (r * r),
))
} else {
None
};
for i in 0..n_nodes {
for j in 0..n_nodes {
let mut gij = 0.0;
for c in 0..d {
for e in 0..d {
gij += dn[i * d + c] * sig[c * d + e] * dn[j * d + e];
}
}
gij *= w;
for a in 0..d {
ke[(i * d + a) * dofs + (j * d + a)] += gij;
}
if let Some((n, s_hoop)) = hoop {
ke[(i * d) * dofs + (j * d)] += s_hoop * n[i] * n[j] * w;
}
}
}
}
Ok(())
}
pub fn tangent_component_names(space_dim: usize, model: ElasticityModel) -> Vec<String> {
let v = voigt_size(space_dim, model);
let mut names = Vec::with_capacity(v * (v + 1) / 2);
for i in 0..v {
for j in i..v {
names.push(format!("ktan_{i}_{j}"));
}
}
names
}
pub fn read_tangent_matrix(
state: &SubElementField,
cell: usize,
g: usize,
space_dim: usize,
model: ElasticityModel,
) -> Result<Vec<Vec<f64>>> {
let v = voigt_size(space_dim, model);
let mut d = vec![vec![0.0; v]; v];
for i in 0..v {
for j in i..v {
let val = state.value(cell, g, &format!("ktan_{i}_{j}"))?;
d[i][j] = val;
d[j][i] = val;
}
}
Ok(d)
}
pub fn element_tangent_from_state(
geom: &CellGeom,
state: &SubElementField,
model: ElasticityModel,
ke: &mut [f64],
) -> Result<()> {
let n_nodes = geom.n_nodes;
let space_dim = geom.space_dim;
let dofs = space_dim * n_nodes;
let v = voigt_size(space_dim, model);
for g in 0..geom.n_gauss {
let hoop = if model.is_axisymmetric() {
Some((geom.n_at_g(g)?, geom.radius(g)?))
} else {
None
};
let b = b_matrix(&geom.dn_dx(g)?, n_nodes, space_dim, hoop);
let d = read_tangent_matrix(state, geom.cell, g, space_dim, model)?;
let mut db = vec![vec![0.0; dofs]; v];
for (r, dbr) in db.iter_mut().enumerate() {
for (c, dbrc) in dbr.iter_mut().enumerate() {
let mut acc = 0.0;
for w in 0..v {
acc += d[r][w] * b[w][c];
}
*dbrc = acc;
}
}
let w = geom.det_j_w(g)?;
for r in 0..dofs {
for c in 0..dofs {
let mut acc = 0.0;
for vv in 0..v {
acc += b[vv][r] * db[vv][c];
}
ke[r * dofs + c] += acc * w;
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aggregate::Aggregate;
use crate::atoms::{ElementType, Node, NodeId};
use crate::containers::field::SubField;
use crate::containers::finite_element_space::FiniteElementSpace;
use crate::containers::mesh::Mesh;
use crate::coords::Coords;
use crate::store::insert;
fn unit_quad(model: ElasticityModel) -> Elasticity {
let coords = insert(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let c = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
let d = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::QUA4));
mesh.add_cell(&[a.id(), b.id(), c.id(), d.id()]).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
Elasticity::new(fes.get(0).unwrap(), model).unwrap()
}
#[test]
fn vars_and_model_validation() {
let el = unit_quad(ElasticityModel::PlaneStress);
assert_eq!(el.primal_vars(), vec!["u_x", "u_y"]);
assert_eq!(el.dual_vars(), vec!["f_x", "f_y"]);
let coords = insert(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
let c = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::TRI3));
mesh.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
assert!(Elasticity::new(fes.get(0).unwrap(), ElasticityModel::Solid).is_err());
}
#[test]
fn plane_stress_constitutive_known_values() {
let (e, nu) = (1.0, 0.25);
let d = constitutive(e, nu, ElasticityModel::PlaneStress, 2);
let c = e / (1.0 - nu * nu);
assert!((d[0][0] - c).abs() < 1e-12);
assert!((d[0][1] - c * nu).abs() < 1e-12);
assert!((d[2][2] - c * (1.0 - nu) / 2.0).abs() < 1e-12);
assert!((d[2][2] - e / (2.0 * (1.0 + nu))).abs() < 1e-12); }
#[test]
fn integrate_behavior_plane_stress_uniaxial() {
let (e, nu, eps0) = (210.0, 0.3, 0.001);
let el = unit_quad(ElasticityModel::PlaneStress);
let mut mat =
SubElementField::new(el.fespace.clone(), vec!["E".into(), "nu".into()]).unwrap();
mat.set_uniform("E", e).unwrap();
mat.set_uniform("nu", nu).unwrap();
let mat = insert(mat);
let mut strain = SubElementField::new(
el.fespace.clone(),
vec!["eps_xx".into(), "eps_xy".into(), "eps_yy".into()],
)
.unwrap();
strain.set_uniform("eps_xx", eps0).unwrap();
let strain = insert(strain);
let out = el
.integrate_behavior(&strain, None, Some(&mat), None)
.unwrap();
let c = e / (1.0 - nu * nu);
for g in 0..out.gauss_count() {
assert!((out.value(0, g, "sigma_xx").unwrap() - c * eps0).abs() < 1e-9);
assert!((out.value(0, g, "sigma_yy").unwrap() - c * nu * eps0).abs() < 1e-9);
assert!(out.value(0, g, "sigma_xy").unwrap().abs() < 1e-9);
}
}
#[test]
fn element_stiffness_symmetric_and_rigid_body_free() {
let el = unit_quad(ElasticityModel::PlaneStrain);
let mut mat =
SubElementField::new(el.fespace.clone(), vec!["E".into(), "nu".into()]).unwrap();
mat.set_uniform("E", 200.0).unwrap();
mat.set_uniform("nu", 0.3).unwrap();
let mat = insert(mat);
let blocks = el.build_stiffness_blocks(Some(&mat)).unwrap();
let k = &blocks[0];
let nodes: Vec<NodeId> = read(&el.support).unwrap().connectivity().to_vec();
let tol = 1e-9;
for &ni in &nodes {
for &nj in &nodes {
for a in ["x", "y"] {
for b in ["x", "y"] {
let lhs = k.get(ni, &format!("f_{a}"), nj, &format!("u_{b}"));
let rhs = k.get(nj, &format!("f_{b}"), ni, &format!("u_{a}"));
assert!((lhs - rhs).abs() < tol);
}
}
}
}
for &ni in &nodes {
let row: f64 = nodes.iter().map(|&nj| k.get(ni, "f_x", nj, "u_x")).sum();
assert!(row.abs() < tol, "row sum {row} ≠ 0");
}
}
}