use crate::containers::element_field::SubElementField;
use crate::containers::field::SubField;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::mesh::SubMesh;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::models::elasticity::{self, ElasticityModel};
use crate::models::owned_components;
use crate::models::plastic::{self, MatParams, PlasticLaw, PrevState};
use crate::models::{CellGeom, Domain, MatrixLayout, Physics, SubModelKind};
use serde::{Deserialize, Serialize};
const AXES: [&str; 3] = ["x", "y", "z"];
use crate::models::plastic::TENSOR_SUFFIXES;
const TENSOR_PAIRS: [(usize, usize); 6] = [(0, 0), (1, 1), (2, 2), (1, 2), (0, 2), (0, 1)];
const AXI_TO_3D: [usize; 4] = [0, 1, 2, 5];
fn primal_name(a: usize) -> String {
format!("u_{}", AXES[a])
}
fn dual_name(a: usize) -> String {
format!("f_{}", AXES[a])
}
fn stress_names(space_dim: usize, model: ElasticityModel) -> Vec<String> {
if space_dim == 2 && model.is_axisymmetric() {
vec![
"sigma_xx".into(),
"sigma_yy".into(),
"sigma_zz".into(),
"sigma_xy".into(),
]
} else if space_dim == 2 {
vec!["sigma_xx".into(), "sigma_yy".into(), "sigma_xy".into()]
} else {
vec![
"sigma_xx".into(),
"sigma_yy".into(),
"sigma_zz".into(),
"sigma_yz".into(),
"sigma_xz".into(),
"sigma_xy".into(),
]
}
}
fn state_names() -> Vec<String> {
let mut v: Vec<String> = TENSOR_SUFFIXES
.iter()
.map(|s| format!("eps_p_{s}"))
.collect();
v.push("p".into());
v
}
fn echo_names(space_dim: usize, model: ElasticityModel) -> Vec<String> {
let mut v: Vec<String> = TENSOR_SUFFIXES.iter().map(|s| format!("eps_{s}")).collect();
if echoes_sigma_zz(space_dim, model) {
v.push("sigma_zz".into());
}
v
}
fn echoes_sigma_zz(space_dim: usize, model: ElasticityModel) -> bool {
space_dim == 2 && !model.is_axisymmetric()
}
#[derive(Clone, Serialize, Deserialize)]
pub struct Plasticity {
pub(crate) fespace: Handle<SubFiniteElementSpace>,
pub(crate) support: Handle<SubMesh>,
pub(crate) space_dim: usize,
pub(crate) model: ElasticityModel,
pub(crate) law: PlasticLaw,
}
impl Plasticity {
pub fn new(fespace: Handle<SubFiniteElementSpace>, model: ElasticityModel) -> Result<Self> {
Self::with_law(fespace, model, PlasticLaw::Perfect)
}
pub fn with_law(
fespace: Handle<SubFiniteElementSpace>,
model: ElasticityModel,
law: PlasticLaw,
) -> Result<Self> {
let (submesh, space_dim, ref_dim, axisymmetric) = {
let s = fespace.read();
(
s.submesh(),
s.space_dim(),
s.ref_dim()?,
s.is_axisymmetric(),
)
};
elasticity::check_continuum_dimensions("Plasticity", 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!(
"Plasticity: 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!(
"Plasticity: model {model:?} on an axisymmetric geometry — a body of \
revolution requires the `axisymmetric` model"
)
} else {
"Plasticity: the `axisymmetric` model requires an axisymmetric geometry \
(build the Coords with Coords::axisymmetric)"
.into()
}));
}
let support = submesh.read().to_poi1()?;
Ok(Self {
fespace,
support,
space_dim,
model,
law,
})
}
}
impl SubModelKind for Plasticity {
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: crate::containers::matrix::DofOrdering::NodesThenVars,
symmetric: true,
})
}
fn mass_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
fn geometric_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
fn element_matrix(
&self,
geoms: &[CellGeom],
material: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let mat = material.expect("Plasticity requires a material field");
elasticity::element_stiffness(
geom,
mat,
self.model,
crate::models::symmetry::MaterialSymmetry::Isotropic,
ke,
)
}
fn element_mass(
&self,
geoms: &[CellGeom],
material: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let mat = material.expect("Plasticity requires a material field");
elasticity::element_mass(geom, mat, ke)
}
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");
elasticity::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 st = state.expect("consistent tangent requires the behaviour state (D_alg)");
elasticity::element_tangent_from_state(geom, st, self.model, ke)
}
fn physics(&self) -> &'static [Physics] {
&[Physics::Mechanical]
}
fn label(&self) -> &'static str {
"Plasticity"
}
fn render(&self, _opts: &DumpOptions) -> String {
let primal = self.primal_vars().join(", ");
let dual = self.dual_vars().join(", ");
let n = self.support.read().cell_count();
format!(
"SubModel<Plasticity({:?})>\n primal var(s): {primal}\n dual var(s): {dual}\n \
support: {n} node(s)",
self.model
)
}
}
impl Domain for Plasticity {
fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn material_components(&self) -> Option<Vec<String>> {
Some(owned_components(self.law.material_components()))
}
fn optional_material_components(&self) -> &'static [&'static str] {
match self.law {
crate::models::plastic::PlasticLaw::DruckerPrager => &[
"alpha",
"rho",
"beta",
"delta",
"H",
"friction_ult",
"beta_ult",
"k_ult",
],
_ => &["alpha", "rho"],
}
}
fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn behavior_output_components(&self) -> Result<Vec<String>> {
let mut comps = stress_names(self.space_dim, self.model);
comps.extend(state_names());
comps.extend(echo_names(self.space_dim, self.model));
comps.extend(self.law.internal_names());
comps.extend(elasticity::tangent_component_names(
self.space_dim,
self.model,
));
Ok(comps)
}
fn integrate_point(
&self,
geom: &CellGeom,
deformation: &SubElementField,
prev: Option<&SubElementField>,
material: Option<&SubElementField>,
g: usize,
dt: Option<f64>,
out: &mut [f64],
) -> Result<()> {
let mat = material.expect("Plasticity declares a material_fespace ⇒ material is supplied");
let (cell, d) = (geom.cell, self.space_dim);
let params = MatParams::new(mat, cell)?;
let eps_b = read_strain(deformation, cell, g, d, self.model)?;
let prev_state = PrevState {
eps: read_prev_strain(prev, cell, g),
sigma: read_prev_stress(prev, cell, g),
eps_p: read_prev_plastic_strain(prev, cell, g),
p: prev_opt(prev, cell, g, "p"),
vars: match prev {
None => Vec::new(),
Some(_) => self
.law
.internal_names()
.iter()
.map(|n| prev_opt(prev, cell, g, n))
.collect(),
},
};
let (step, eps_b_full) =
plastic::incremental_step(self.law, &eps_b, &prev_state, ¶ms, self.model, dt)?;
let v = stress_names(d, self.model).len();
for r in 0..v {
out[r] = voigt_stress(&step.sigma, d, self.model, r);
}
out[v..v + 6].copy_from_slice(&step.eps_p); out[v + 6] = step.p; out[v + 7..v + 13].copy_from_slice(&eps_b_full);
let mut base = v + 13;
if echoes_sigma_zz(d, self.model) {
out[base] = step.sigma[2];
base += 1;
}
for (i, value) in step.vars.iter().enumerate() {
out[base + i] = *value;
}
base += step.vars.len();
let d3 = plastic::consistent_tangent(self.law, &eps_b_full, &prev_state, ¶ms, dt)?;
let dv = crate::models::symmetry::reduce_to_model(&d3, self.model);
let mut idx = base;
for i in 0..dv.len() {
for j in i..dv.len() {
out[idx] = dv[i][j];
idx += 1;
}
}
Ok(())
}
}
fn read_opt(f: &SubElementField, cell: usize, g: usize, name: &str) -> f64 {
if f.component_index(name).is_some() {
f.value(cell, g, name).unwrap_or(0.0)
} else {
0.0
}
}
fn read_strain(
f: &SubElementField,
cell: usize,
g: usize,
space_dim: usize,
model: ElasticityModel,
) -> Result<[f64; 6]> {
let mut eps = [0.0; 6];
if space_dim == 2 {
eps[0] = f.value(cell, g, "eps_xx")?;
eps[1] = f.value(cell, g, "eps_yy")?;
eps[5] = f.value(cell, g, "eps_xy")?;
if model.is_axisymmetric() {
eps[2] = f.value(cell, g, "eps_zz")?;
}
} else {
for (k, suf) in TENSOR_SUFFIXES.iter().enumerate() {
eps[k] = f.value(cell, g, &format!("eps_{suf}"))?;
}
}
Ok(eps)
}
fn prev_opt(prev: Option<&SubElementField>, cell: usize, g: usize, name: &str) -> f64 {
prev.map_or(0.0, |f| read_opt(f, cell, g, name))
}
fn read_prev_strain(prev: Option<&SubElementField>, cell: usize, g: usize) -> [f64; 6] {
std::array::from_fn(|k| prev_opt(prev, cell, g, &format!("eps_{}", TENSOR_SUFFIXES[k])))
}
fn read_prev_stress(prev: Option<&SubElementField>, cell: usize, g: usize) -> [f64; 6] {
std::array::from_fn(|k| prev_opt(prev, cell, g, &format!("sigma_{}", TENSOR_SUFFIXES[k])))
}
fn read_prev_plastic_strain(prev: Option<&SubElementField>, cell: usize, g: usize) -> [f64; 6] {
std::array::from_fn(|k| prev_opt(prev, cell, g, &format!("eps_p_{}", TENSOR_SUFFIXES[k])))
}
fn voigt_stress(sigma: &[f64; 6], space_dim: usize, model: ElasticityModel, r: usize) -> f64 {
if space_dim == 2 && model.is_axisymmetric() {
sigma[AXI_TO_3D[r]]
} else if space_dim == 2 {
match r {
0 => sigma[0],
1 => sigma[1],
_ => sigma[5],
}
} else {
sigma[r]
}
}
#[allow(dead_code)]
fn tensor_index(i: usize, j: usize) -> usize {
TENSOR_PAIRS
.iter()
.position(|&(a, b)| (a, b) == (i.min(j), i.max(j)))
.expect("valid tensor pair")
}
#[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::handle::Handle;
fn unit_quad(model: ElasticityModel) -> Plasticity {
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.clone(), &[1.0, 0.0]).unwrap();
let c = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
let dd = 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(), dd.id()]).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
Plasticity::new(fes.get(0).unwrap(), model).unwrap()
}
fn unit_hex() -> Plasticity {
let coords = Handle::new(Coords::new(3).unwrap());
let p = |x: f64, y: f64, z: f64| Node::create_in(coords.clone(), &[x, y, z]).unwrap();
let n = [
p(0.0, 0.0, 0.0),
p(1.0, 0.0, 0.0),
p(1.0, 1.0, 0.0),
p(0.0, 1.0, 0.0),
p(0.0, 0.0, 1.0),
p(1.0, 0.0, 1.0),
p(1.0, 1.0, 1.0),
p(0.0, 1.0, 1.0),
];
let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::HEX8));
mesh.add_cell(&n.iter().map(|x| x.id()).collect::<Vec<_>>())
.unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
Plasticity::new(fes.get(0).unwrap(), ElasticityModel::Solid).unwrap()
}
fn material(pl: &Plasticity, e: f64, nu: f64, sy: f64) -> Handle<SubElementField> {
let mut mat = SubElementField::new(
pl.fespace.clone(),
vec!["E".into(), "nu".into(), "sigma_y".into()],
)
.unwrap();
mat.set_uniform("E", e).unwrap();
mat.set_uniform("nu", nu).unwrap();
mat.set_uniform("sigma_y", sy).unwrap();
Handle::new(mat)
}
#[test]
fn vars_and_model_validation() {
let pl = unit_quad(ElasticityModel::PlaneStrain);
assert_eq!(pl.primal_vars(), vec!["u_x", "u_y"]);
assert_eq!(pl.dual_vars(), vec!["f_x", "f_y"]);
assert_eq!(
pl.material_components(),
Some(owned_components(PlasticLaw::Perfect.material_components()))
);
}
#[test]
fn elastic_below_yield_solid() {
let pl = unit_hex();
let (e, nu, sy) = (210_000.0, 0.3, 250.0);
let mat = material(&pl, e, nu, sy);
let mut strain = SubElementField::new(
pl.fespace.clone(),
TENSOR_SUFFIXES.iter().map(|s| format!("eps_{s}")).collect(),
)
.unwrap();
strain.set_uniform("eps_xx", 1e-4).unwrap();
let strain = Handle::new(strain);
let out = pl
.integrate_behavior(&strain, None, Some(&mat), None)
.unwrap();
let (lambda, mu) = plastic::lame(e, nu);
for g in 0..out.gauss_count() {
assert!(
(out.value(0, g, "sigma_xx").unwrap() - (lambda + 2.0 * mu) * 1e-4).abs() < 1e-6
);
assert!(out.value(0, g, "p").unwrap().abs() < 1e-14);
}
}
#[test]
fn yields_and_caps_at_sigma_y_solid() {
let pl = unit_hex();
let (e, nu, sy) = (210_000.0, 0.3, 250.0);
let mat = material(&pl, e, nu, sy);
let mut strain = SubElementField::new(
pl.fespace.clone(),
TENSOR_SUFFIXES.iter().map(|s| format!("eps_{s}")).collect(),
)
.unwrap();
strain.set_uniform("eps_xx", 1e-2).unwrap();
let strain = Handle::new(strain);
let out = pl
.integrate_behavior(&strain, None, Some(&mat), None)
.unwrap();
for g in 0..out.gauss_count() {
let s = [
out.value(0, g, "sigma_xx").unwrap(),
out.value(0, g, "sigma_yy").unwrap(),
out.value(0, g, "sigma_zz").unwrap(),
out.value(0, g, "sigma_yz").unwrap(),
out.value(0, g, "sigma_xz").unwrap(),
out.value(0, g, "sigma_xy").unwrap(),
];
assert!(
(plastic::von_mises_stress(&s) - sy).abs() < 1e-3,
"q = {}",
plastic::von_mises_stress(&s)
);
assert!(out.value(0, g, "p").unwrap() > 0.0);
}
}
#[test]
fn plane_stress_zero_out_of_plane_and_matches_elastic() {
let pl = unit_quad(ElasticityModel::PlaneStress);
let (e, nu, sy) = (210_000.0, 0.3, 1e9); let mat = material(&pl, e, nu, sy);
let eps0 = 1e-3;
let mut strain = SubElementField::new(
pl.fespace.clone(),
vec!["eps_xx".into(), "eps_xy".into(), "eps_yy".into()],
)
.unwrap();
strain.set_uniform("eps_xx", eps0).unwrap();
let strain = Handle::new(strain);
let out = pl
.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-3);
assert!((out.value(0, g, "sigma_yy").unwrap() - c * nu * eps0).abs() < 1e-3);
}
}
fn uniaxial(pl: &Plasticity, val: f64) -> Handle<SubElementField> {
let comps: Vec<String> = TENSOR_SUFFIXES.iter().map(|s| format!("eps_{s}")).collect();
let mut s = SubElementField::new(pl.fespace.clone(), comps).unwrap();
s.set_uniform("eps_xx", val).unwrap();
Handle::new(s)
}
#[test]
fn state_round_trip_is_history_dependent() {
let pl = unit_hex();
let (e, nu, sy) = (210_000.0, 0.3, 250.0);
let mat = material(&pl, e, nu, sy);
let st1 = pl
.integrate_behavior(&uniaxial(&pl, 5e-3), None, Some(&mat), None)
.unwrap();
let p1 = st1.value(0, 0, "p").unwrap();
assert!(p1 > 0.0);
let prev = Handle::new(st1);
let st2 = pl
.integrate_behavior(&uniaxial(&pl, 6e-3), Some(&prev), Some(&mat), None)
.unwrap();
assert!(st2.value(0, 0, "p").unwrap() >= p1);
}
#[test]
fn incremental_matches_single_step_on_proportional_path() {
let pl = unit_hex();
let (e, nu, sy) = (210_000.0, 0.3, 250.0);
let mat = material(&pl, e, nu, sy);
let eps_final = 1e-2;
let single = pl
.integrate_behavior(&uniaxial(&pl, eps_final), None, Some(&mat), None)
.unwrap();
let nsteps = 10;
let mut prev: Option<Handle<SubElementField>> = None;
for i in 1..=nsteps {
let val = eps_final * i as f64 / nsteps as f64;
let out = pl
.integrate_behavior(&uniaxial(&pl, val), prev.as_ref(), Some(&mat), None)
.unwrap();
prev = Some(Handle::new(out));
}
let multi = prev.unwrap().read();
for comp in [
"sigma_xx", "sigma_yy", "sigma_zz", "p", "eps_p_xx", "eps_p_yy",
] {
let a = single.value(0, 0, comp).unwrap();
let b = multi.value(0, 0, comp).unwrap();
assert!((a - b).abs() < 1e-9, "{comp}: single={a} multi={b}");
}
}
#[test]
fn partial_unload_is_elastic_and_leaves_yield_surface() {
let pl = unit_hex();
let (e, nu, sy) = (210_000.0, 0.3, 250.0);
let mat = material(&pl, e, nu, sy);
let loaded = Handle::new(
pl.integrate_behavior(&uniaxial(&pl, 1e-2), None, Some(&mat), None)
.unwrap(),
);
let p1 = loaded.read().value(0, 0, "p").unwrap();
assert!(p1 > 0.0);
let unloaded = pl
.integrate_behavior(&uniaxial(&pl, 9.9e-3), Some(&loaded), Some(&mat), None)
.unwrap();
assert!(
(unloaded.value(0, 0, "p").unwrap() - p1).abs() < 1e-12,
"p must not grow on elastic unload"
);
let s = [
unloaded.value(0, 0, "sigma_xx").unwrap(),
unloaded.value(0, 0, "sigma_yy").unwrap(),
unloaded.value(0, 0, "sigma_zz").unwrap(),
unloaded.value(0, 0, "sigma_yz").unwrap(),
unloaded.value(0, 0, "sigma_xz").unwrap(),
unloaded.value(0, 0, "sigma_xy").unwrap(),
];
assert!(
plastic::von_mises_stress(&s) < sy - 1.0,
"elastic unload must drop below σ_y, got q = {}",
plastic::von_mises_stress(&s)
);
}
#[test]
fn stiffness_is_elastic_and_symmetric() {
let pl = unit_quad(ElasticityModel::PlaneStrain);
let mat = material(&pl, 200.0, 0.3, 250.0);
let blocks = pl.build_stiffness_blocks(Some(&mat)).unwrap();
let k = &blocks[0];
let nodes: Vec<NodeId> = pl.support.read().connectivity().to_vec();
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() < 1e-9);
}
}
}
}
}
#[test]
fn tensor_index_matches_layout() {
assert_eq!(tensor_index(0, 0), 0);
assert_eq!(tensor_index(2, 2), 2);
assert_eq!(tensor_index(1, 2), 3);
assert_eq!(tensor_index(0, 1), 5);
assert_eq!(tensor_index(1, 0), 5);
}
}