pub mod drucker_prager;
pub mod gurson;
pub mod law;
pub mod ottosen;
pub mod viscous;
pub mod von_mises;
use crate::containers::element_field::SubElementField;
use crate::containers::field::SubField;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::dump::DumpOptions;
use crate::error::Result;
use crate::handle::Handle;
use crate::models::continuum::Continuum;
use crate::models::owned_components;
use crate::models::symmetry::MaterialSymmetry;
use crate::models::tensor::voigt_stress;
use crate::models::tensor::Kinematics;
use crate::models::tensor::{dual_name, primal_name};
use crate::models::ZoneLayout;
use crate::models::{
Behavior, CellGeom, Domain, MatrixLayout, Physics, StrainOperator, SubModelKind,
};
use crate::models::{ElementLayout, MatrixKind};
use crate::ops::element_field::StrainMeasure;
use law::{MatParams, PlasticLaw, PrevState, MAX_INTERNAL_VARS};
use serde::{Deserialize, Serialize};
use crate::containers::matrix::Symmetry;
use crate::models::plasticity::law::TENSOR_SUFFIXES;
const TENSOR_PAIRS: [(usize, usize); 6] = [(0, 0), (1, 1), (2, 2), (1, 2), (0, 2), (0, 1)];
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(continuum: &Continuum) -> Vec<String> {
let strain = continuum.measure().prefix();
let mut v: Vec<String> = TENSOR_SUFFIXES
.iter()
.map(|s| format!("{strain}_{s}"))
.collect();
if echoes_sigma_zz(continuum.space_dim(), continuum.kinematics()) {
v.push(format!("{}_zz", continuum.stress_prefix()));
}
v
}
fn echoes_sigma_zz(space_dim: usize, kinematics: Kinematics) -> bool {
space_dim == 2 && !kinematics.is_axisymmetric()
}
#[derive(Clone, Serialize, Deserialize)]
pub struct Plasticity {
pub(crate) continuum: Continuum,
pub(crate) law: PlasticLaw,
}
impl Plasticity {
pub fn new(
fespace: Handle<SubFiniteElementSpace>,
kinematics: Kinematics,
law: PlasticLaw,
strain_measure: StrainMeasure,
) -> Result<Self> {
Ok(Self {
continuum: Continuum::new(fespace, kinematics, "Plasticity")?
.with_measure(strain_measure, "Plasticity")?,
law,
})
}
}
impl Plasticity {
fn with_law_inputs<R>(
&self,
lay: &ZoneLayout,
deformation: &[f64],
prev: &[f64],
material: &[f64],
f: impl FnOnce(&MatParams, &[f64; 6], &PrevState) -> Result<R>,
) -> Result<R> {
let d = self.continuum.space_dim();
let params = MatParams::new(material, &lay.material, &lay.optional_material);
let eps_b = read_tensor(
deformation,
&lay.deformation,
strain_slots(d, self.continuum.kinematics()),
);
let n_stress = stress_slots(d, self.continuum.kinematics()).len();
let (i_sigma, i_eps_p, i_p, i_vars) = (6, 6 + n_stress, 12 + n_stress, 13 + n_stress);
let mut vars = [0.0_f64; MAX_INTERNAL_VARS];
let n_vars = lay.state.len() - i_vars;
for (k, v) in vars[..n_vars].iter_mut().enumerate() {
*v = prev[lay.state[i_vars + k] as usize];
}
let prev_state = PrevState {
eps: read_tensor(prev, &lay.state[..6], &[0, 1, 2, 3, 4, 5]),
sigma: read_tensor(
prev,
&lay.state[i_sigma..],
stress_slots(d, self.continuum.kinematics()),
),
eps_p: read_tensor(prev, &lay.state[i_eps_p..], &[0, 1, 2, 3, 4, 5]),
p: prev[lay.state[i_p] as usize],
vars: &vars[..n_vars],
};
f(¶ms, &eps_b, &prev_state)
}
}
impl SubModelKind for Plasticity {
fn primal_vars(&self) -> Vec<String> {
(0..self.continuum.space_dim()).map(primal_name).collect()
}
fn dual_vars(&self) -> Vec<String> {
(0..self.continuum.space_dim()).map(dual_name).collect()
}
fn as_domain(&self) -> Option<&dyn Domain> {
Some(self)
}
fn as_behavior(&self) -> Option<&dyn Behavior> {
Some(self)
}
fn stiffness_layout(&self) -> Option<MatrixLayout> {
Some(MatrixLayout {
fespaces: vec![self.continuum.fespace()],
support: self.continuum.support(),
dual_vars: self.dual_vars(),
primal_vars: self.primal_vars(),
ordering: crate::containers::matrix::DofOrdering::NodesThenVars,
symmetry: Symmetry::Full,
})
}
fn mass_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
fn geometric_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
fn tangent_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
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.continuum.support().read().cell_count();
format!(
"SubModel<Plasticity({:?})>\n primal var(s): {primal}\n dual var(s): {dual}\n \
support: {n} node(s)",
self.continuum.kinematics()
)
}
}
impl Domain for Plasticity {
fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.continuum.fespace()
}
fn material_components(&self) -> Vec<String> {
owned_components(self.law.material_components())
}
fn optional_material_components(&self) -> &'static [&'static str] {
self.law.as_law().optional_material_components()
}
fn element_state_reads(&self, kind: MatrixKind) -> Vec<String> {
self.continuum.element_state_reads(kind)
}
fn element_matrix(
&self,
geoms: &[CellGeom],
material: &SubElementField,
lay: &ElementLayout,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let mat = material;
self.continuum.element_stiffness(
geom,
mat,
lay,
crate::models::symmetry::MaterialSymmetry::Isotropic,
ke,
)
}
fn element_mass(
&self,
geoms: &[CellGeom],
material: &SubElementField,
lay: &ElementLayout,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let mat = material;
self.continuum.element_mass(geom, mat, lay, ke)
}
fn element_geometric(
&self,
geoms: &[CellGeom],
_material: &SubElementField,
lay: &ElementLayout,
state: &SubElementField,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let stress = state;
self.continuum.element_geometric(geom, stress, lay, ke)
}
}
impl Behavior for Plasticity {
fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.continuum.fespace()
}
fn elastic_operator(&self) -> Option<(&Continuum, MaterialSymmetry)> {
Some((&self.continuum, MaterialSymmetry::Isotropic))
}
fn behavior_output_components(&self) -> Vec<String> {
let mut comps = self.continuum.stress_names();
comps.extend(state_names());
comps.extend(echo_names(&self.continuum));
comps.extend(self.law.internal_names());
comps
}
fn tangent_source(&self) -> crate::models::TangentSource {
self.law.tangent_source()
}
fn requires_dt(&self) -> bool {
self.law.is_viscous()
}
fn initial_state(&self, material: &SubElementField) -> Result<SubElementField> {
let mut state =
SubElementField::new(self.continuum.fespace(), self.behavior_output_components())?;
let sources = self.law.as_law().initial_internal_sources();
if sources.is_empty() {
return Ok(state);
}
for (var, source) in self.law.internal_names().iter().zip(sources) {
let slot = state.component_index_or_err(var)?;
let from = material.component_index_or_err(source)?;
for cell in 0..state.cell_count() {
for g in 0..state.gauss_count() {
state.set(cell, g, slot, material.get(cell, g, from)?)?;
}
}
}
Ok(state)
}
fn deformation_reads(&self) -> Vec<String> {
self.continuum.strain_reads()
}
fn strain_operator(&self) -> StrainOperator {
StrainOperator::Deformation(self.continuum.measure())
}
fn state_reads(&self) -> Vec<String> {
let d = self.continuum.space_dim();
let strain = self.continuum.measure().prefix();
let mut v: Vec<String> = TENSOR_SUFFIXES
.iter()
.map(|s| format!("{strain}_{s}"))
.collect();
v.extend(self.continuum.stress_names());
if echoes_sigma_zz(d, self.continuum.kinematics()) {
v.push(format!("{}_zz", self.continuum.stress_prefix()));
}
v.extend(state_names());
v.extend(self.law.internal_names());
v
}
fn integrate_point(
&self,
_geom: &CellGeom,
_g: usize,
lay: &ZoneLayout,
deformation: &[f64],
prev: &[f64],
material: &[f64],
dt: f64,
out: &mut [f64],
) -> Result<()> {
self.with_law_inputs(
lay,
deformation,
prev,
material,
|params, eps_b, prev_state| {
let d = self.continuum.space_dim();
let n_stress = stress_slots(d, self.continuum.kinematics()).len();
let (step, eps_b_full) = self.law.as_law().incremental_step(
eps_b,
prev_state,
params,
self.continuum.kinematics(),
dt,
)?;
let v = n_stress - usize::from(echoes_sigma_zz(d, self.continuum.kinematics()));
for r in 0..v {
out[r] = voigt_stress(&step.sigma, d, self.continuum.kinematics(), 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.continuum.kinematics()) {
out[base] = step.sigma[2];
base += 1;
}
for (i, value) in step.internal().iter().enumerate() {
out[base + i] = *value;
}
Ok(())
},
)
}
fn tangent_point(
&self,
_geom: &CellGeom,
_g: usize,
lay: &ZoneLayout,
deformation: &[f64],
prev: &[f64],
material: &[f64],
dt: f64,
d: &mut [[f64; 6]; 6],
) -> Result<()> {
self.with_law_inputs(
lay,
deformation,
prev,
material,
|params, eps_b, prev_state| {
let (_, eps_b_full) = self.law.as_law().incremental_step(
eps_b,
prev_state,
params,
self.continuum.kinematics(),
dt,
)?;
let d3 =
self.law
.as_law()
.consistent_tangent(&eps_b_full, prev_state, params, dt)?;
crate::models::symmetry::reduce_to_model_into(&d3, self.continuum.kinematics(), d);
Ok(())
},
)
}
fn element_tangent(
&self,
geoms: &[CellGeom],
lay: &ZoneLayout,
deformation: &SubElementField,
prev: &SubElementField,
material: &SubElementField,
dt: f64,
ke: &mut [f64],
) -> Result<()> {
self.continuum
.element_tangent_of(self, geoms, lay, deformation, prev, material, dt, ke)
}
}
fn strain_slots(space_dim: usize, kinematics: Kinematics) -> &'static [usize] {
if space_dim == 2 && kinematics.is_axisymmetric() {
&[0, 1, 2, 5]
} else if space_dim == 2 {
&[0, 1, 5]
} else {
&[0, 1, 2, 3, 4, 5]
}
}
fn stress_slots(space_dim: usize, kinematics: Kinematics) -> &'static [usize] {
if space_dim == 2 && kinematics.is_axisymmetric() {
&[0, 1, 2, 5]
} else if space_dim == 2 {
&[0, 1, 5, 2] } else {
&[0, 1, 2, 3, 4, 5]
}
}
fn read_tensor(row: &[f64], idx: &[u32], slots: &[usize]) -> [f64; 6] {
let mut t = [0.0_f64; 6];
for (r, &slot) in slots.iter().enumerate() {
t[slot] = row[idx[r] as usize];
}
t
}
#[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::*;
fn rest<B: Behavior>(b: &B, mat: &Handle<SubElementField>) -> Handle<SubElementField> {
Handle::new(b.initial_state(&mat.read()).unwrap())
}
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, SubMesh};
use crate::coords::Coords;
use crate::handle::Handle;
use crate::models::tensor;
fn unit_quad(kinematics: Kinematics) -> 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(),
kinematics,
PlasticLaw::Perfect,
StrainMeasure::Linear,
)
.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(),
Kinematics::Full3D,
PlasticLaw::Perfect,
StrainMeasure::Linear,
)
.unwrap()
}
fn material(pl: &Plasticity, e: f64, nu: f64, sy: f64) -> Handle<SubElementField> {
let mut mat = SubElementField::new(
pl.continuum.fespace(),
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(Kinematics::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(),
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.continuum.fespace(),
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, &rest(&pl, &mat), &mat, 0.0)
.unwrap();
let (lambda, mu) = crate::models::continuum::elastic::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.continuum.fespace(),
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, &rest(&pl, &mat), &mat, 0.0)
.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!(
(tensor::von_mises_stress(&s) - sy).abs() < 1e-3,
"q = {}",
tensor::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(Kinematics::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.continuum.fespace(),
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, &rest(&pl, &mat), &mat, 0.0)
.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.continuum.fespace(), 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), &rest(&pl, &mat), &mat, 0.0)
.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), &prev, &mat, 0.0)
.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), &rest(&pl, &mat), &mat, 0.0)
.unwrap();
let nsteps = 10;
let mut prev = rest(&pl, &mat);
for i in 1..=nsteps {
let val = eps_final * i as f64 / nsteps as f64;
let out = pl
.integrate_behavior(&uniaxial(&pl, val), &prev, &mat, 0.0)
.unwrap();
prev = Handle::new(out);
}
let multi = prev.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), &rest(&pl, &mat), &mat, 0.0)
.unwrap(),
);
let p1 = loaded.read().value(0, 0, "p").unwrap();
assert!(p1 > 0.0);
let unloaded = pl
.integrate_behavior(&uniaxial(&pl, 9.9e-3), &loaded, &mat, 0.0)
.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!(
tensor::von_mises_stress(&s) < sy - 1.0,
"elastic unload must drop below σ_y, got q = {}",
tensor::von_mises_stress(&s)
);
}
#[test]
fn stiffness_is_elastic_and_symmetric() {
let pl = unit_quad(Kinematics::PlaneStrain);
let mat = material(&pl, 200.0, 0.3, 250.0);
let blocks = pl.build_stiffness_blocks(&mat).unwrap();
let k = &blocks[0];
let nodes: Vec<NodeId> = pl.continuum.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}")).unwrap();
let rhs = k.get(nj, &format!("f_{b}"), ni, &format!("u_{a}")).unwrap();
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);
}
}