use crate::containers::element_field::SubElementField;
use crate::error::{PyrucastError, Result};
use crate::models::elasticity::ElasticityModel;
use serde::{Deserialize, Serialize};
pub mod drucker_prager;
pub mod gurson;
pub mod ottosen;
pub mod viscous;
pub mod von_mises;
pub const TENSOR_SUFFIXES: [&str; 6] = ["xx", "yy", "zz", "yz", "xz", "xy"];
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum PlasticLaw {
#[default]
Perfect,
Isotropic,
DruckerPrager,
Ottosen,
CreepNorton,
CreepBlackburn,
CreepLemaitre,
ViscoplasticChaboche,
ViscoplasticLemaitreChaboche,
Gurson,
}
impl PlasticLaw {
pub fn from_tag(tag: &str) -> Option<Self> {
match tag {
"perfect" => Some(Self::Perfect),
"isotropic" => Some(Self::Isotropic),
"drucker_prager" => Some(Self::DruckerPrager),
"ottosen" => Some(Self::Ottosen),
"creep_norton" => Some(Self::CreepNorton),
"creep_blackburn" => Some(Self::CreepBlackburn),
"creep_lemaitre" => Some(Self::CreepLemaitre),
"viscoplastic_chaboche" => Some(Self::ViscoplasticChaboche),
"viscoplastic_lemaitre_chaboche" => Some(Self::ViscoplasticLemaitreChaboche),
"gurson" => Some(Self::Gurson),
_ => None,
}
}
pub fn to_tag(self) -> &'static str {
match self {
Self::Perfect => "perfect",
Self::Isotropic => "isotropic",
Self::DruckerPrager => "drucker_prager",
Self::Ottosen => "ottosen",
Self::CreepNorton => "creep_norton",
Self::CreepBlackburn => "creep_blackburn",
Self::CreepLemaitre => "creep_lemaitre",
Self::ViscoplasticChaboche => "viscoplastic_chaboche",
Self::ViscoplasticLemaitreChaboche => "viscoplastic_lemaitre_chaboche",
Self::Gurson => "gurson",
}
}
pub const ALL: [PlasticLaw; 10] = [
Self::Perfect,
Self::Isotropic,
Self::DruckerPrager,
Self::Ottosen,
Self::CreepNorton,
Self::CreepBlackburn,
Self::CreepLemaitre,
Self::ViscoplasticChaboche,
Self::ViscoplasticLemaitreChaboche,
Self::Gurson,
];
pub fn tag_list() -> String {
Self::ALL
.iter()
.map(|l| l.to_tag())
.collect::<Vec<_>>()
.join("|")
}
pub fn material_components(self) -> &'static [&'static str] {
match self {
Self::Perfect => &["E", "nu", "sigma_y"],
Self::Isotropic => &["E", "nu", "sigma_y", "H"],
Self::DruckerPrager => &["E", "nu", "friction", "k", "psi"],
Self::Ottosen => &["E", "nu", "a", "b", "k_1", "k_2", "sigma_c"],
Self::CreepNorton => &["E", "nu", "K", "n"],
Self::CreepBlackburn => &["E", "nu", "A_1", "alpha_1", "r_1", "B_s", "beta_s"],
Self::CreepLemaitre => &["E", "nu", "K", "N", "M"],
Self::ViscoplasticChaboche => &["E", "nu", "k", "K", "n", "C_1", "gamma_1", "b", "Q"],
Self::ViscoplasticLemaitreChaboche => &[
"E", "nu", "k", "K", "n", "C_1", "gamma_1", "b", "Q", "S", "s", "D_c",
],
Self::Gurson => &[
"E", "nu", "sigma_y", "q_1", "q_2", "q_3", "f_0", "f_c", "f_f",
],
}
}
fn has_analytic_tangent(self) -> bool {
matches!(self, Self::Perfect | Self::Isotropic)
}
pub fn internal_names(self) -> Vec<String> {
match self {
Self::Perfect
| Self::Isotropic
| Self::DruckerPrager
| Self::Ottosen
| Self::CreepNorton
| Self::CreepLemaitre => Vec::new(),
Self::Gurson => vec!["porosity".to_string()],
Self::CreepBlackburn => vec!["p_prim".to_string()],
Self::ViscoplasticChaboche => back_stress_names(false),
Self::ViscoplasticLemaitreChaboche => back_stress_names(true),
}
}
pub fn is_viscous(self) -> bool {
matches!(
self,
Self::CreepNorton
| Self::CreepBlackburn
| Self::CreepLemaitre
| Self::ViscoplasticChaboche
| Self::ViscoplasticLemaitreChaboche
)
}
pub fn return_map(
&self,
trial: &[f64; 6],
prev: &PrevState,
mat: &MatParams,
dt: Option<f64>,
) -> Result<PlasticStep> {
if self.is_viscous() && dt.is_none() {
return Err(PyrucastError::Message(format!(
"plasticity ({self}): this law is rate-dependent and needs a time increment — pass `dt` to integrate_behavior"
)));
}
match self {
Self::Perfect => von_mises::return_map(trial, prev, mat, 0.0),
Self::Isotropic => von_mises::return_map(trial, prev, mat, mat.get("H")?),
Self::DruckerPrager => drucker_prager::return_map(trial, prev, mat),
Self::Ottosen => ottosen::return_map(trial, prev, mat),
Self::CreepNorton => viscous::norton(trial, prev, mat, dt.unwrap()),
Self::CreepBlackburn => viscous::blackburn(trial, prev, mat, dt.unwrap()),
Self::CreepLemaitre => viscous::lemaitre(trial, prev, mat, dt.unwrap()),
Self::ViscoplasticChaboche => viscous::chaboche(trial, prev, mat, dt.unwrap(), false),
Self::ViscoplasticLemaitreChaboche => {
viscous::chaboche(trial, prev, mat, dt.unwrap(), true)
}
Self::Gurson => gurson::return_map(trial, prev, mat),
}
}
}
impl std::fmt::Display for PlasticLaw {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.to_tag())
}
}
fn back_stress_names(damage: bool) -> Vec<String> {
let mut names: Vec<String> = TENSOR_SUFFIXES.iter().map(|s| format!("X_{s}")).collect();
names.push("R".to_string());
if damage {
names.push("damage".to_string());
}
names
}
pub struct MatParams<'a> {
pub lambda: f64,
pub mu: f64,
material: &'a SubElementField,
cell: usize,
}
impl<'a> MatParams<'a> {
pub fn new(material: &'a SubElementField, cell: usize) -> Result<Self> {
let (lambda, mu) = lame(
material.value(cell, 0, "E")?,
material.value(cell, 0, "nu")?,
);
Ok(Self {
lambda,
mu,
material,
cell,
})
}
pub fn get(&self, name: &str) -> Result<f64> {
self.material.value(self.cell, 0, name)
}
pub fn bulk(&self) -> f64 {
self.lambda + 2.0 * self.mu / 3.0
}
}
pub fn lame(e: f64, nu: f64) -> (f64, f64) {
let lambda = e * nu / ((1.0 + nu) * (1.0 - 2.0 * nu));
let mu = e / (2.0 * (1.0 + nu));
(lambda, mu)
}
pub fn elastic_stress(eps: &[f64; 6], lambda: f64, mu: f64) -> [f64; 6] {
let tr = eps[0] + eps[1] + eps[2];
[
lambda * tr + 2.0 * mu * eps[0],
lambda * tr + 2.0 * mu * eps[1],
lambda * tr + 2.0 * mu * eps[2],
2.0 * mu * eps[3],
2.0 * mu * eps[4],
2.0 * mu * eps[5],
]
}
pub fn i1(sigma: &[f64; 6]) -> f64 {
sigma[0] + sigma[1] + sigma[2]
}
pub fn deviator(sigma: &[f64; 6]) -> [f64; 6] {
let mean = i1(sigma) / 3.0;
[
sigma[0] - mean,
sigma[1] - mean,
sigma[2] - mean,
sigma[3],
sigma[4],
sigma[5],
]
}
pub fn j2(sigma: &[f64; 6]) -> f64 {
let s = deviator(sigma);
0.5 * (s[0] * s[0]
+ s[1] * s[1]
+ s[2] * s[2]
+ 2.0 * (s[3] * s[3] + s[4] * s[4] + s[5] * s[5]))
}
pub fn j3(sigma: &[f64; 6]) -> f64 {
let s = deviator(sigma);
s[0] * (s[1] * s[2] - s[3] * s[3]) - s[5] * (s[5] * s[2] - s[3] * s[4])
+ s[4] * (s[5] * s[3] - s[1] * s[4])
}
pub fn von_mises_stress(sigma: &[f64; 6]) -> f64 {
(3.0 * j2(sigma)).sqrt()
}
#[derive(Clone, Default)]
pub struct PrevState {
pub eps: [f64; 6],
pub sigma: [f64; 6],
pub eps_p: [f64; 6],
pub p: f64,
pub vars: Vec<f64>,
}
impl PrevState {
pub fn var(&self, i: usize) -> f64 {
self.vars.get(i).copied().unwrap_or(0.0)
}
}
pub struct PlasticStep {
pub sigma: [f64; 6],
pub eps_p: [f64; 6],
pub p: f64,
pub vars: Vec<f64>,
}
impl PlasticStep {
pub fn elastic(trial: &[f64; 6], prev: &PrevState) -> Self {
Self {
sigma: *trial,
eps_p: prev.eps_p,
p: prev.p,
vars: prev.vars.clone(),
}
}
}
pub fn elastic_predictor(eps_b: &[f64; 6], prev: &PrevState, lambda: f64, mu: f64) -> [f64; 6] {
let deps: [f64; 6] = std::array::from_fn(|i| eps_b[i] - prev.eps[i]);
let c_deps = elastic_stress(&deps, lambda, mu);
std::array::from_fn(|i| prev.sigma[i] + c_deps[i])
}
pub fn incremental_step(
law: PlasticLaw,
eps_b: &[f64; 6],
prev: &PrevState,
mat: &MatParams,
model: ElasticityModel,
dt: Option<f64>,
) -> Result<(PlasticStep, [f64; 6])> {
if model == ElasticityModel::PlaneStress {
return plane_stress_step(law, eps_b, prev, mat, dt);
}
let trial = elastic_predictor(eps_b, prev, mat.lambda, mat.mu);
Ok((law.return_map(&trial, prev, mat, dt)?, *eps_b))
}
fn plane_stress_step(
law: PlasticLaw,
eps_in_b: &[f64; 6],
prev: &PrevState,
mat: &MatParams,
dt: Option<f64>,
) -> Result<(PlasticStep, [f64; 6])> {
let eval = |ezz: f64| -> Result<(PlasticStep, [f64; 6])> {
let mut eps_b = *eps_in_b;
eps_b[2] = ezz;
eps_b[3] = 0.0;
eps_b[4] = 0.0;
let trial = elastic_predictor(&eps_b, prev, mat.lambda, mat.mu);
Ok((law.return_map(&trial, prev, mat, dt)?, eps_b))
};
let nu_term = mat.lambda / (mat.lambda + 2.0 * mat.mu); let mut z0 = prev.eps[2] - nu_term * (eps_in_b[0] - prev.eps[0] + eps_in_b[1] - prev.eps[1]);
let mut z1 = z0 + 1e-6_f64.max(z0.abs() * 1e-3);
let mut f0 = eval(z0)?.0.sigma[2];
let mut f1 = eval(z1)?.0.sigma[2];
for _ in 0..50 {
if f1.abs() < 1e-10 * (mat.mu + 1.0) {
break;
}
let denom = f1 - f0;
if denom.abs() < f64::MIN_POSITIVE {
break;
}
let z2 = z1 - f1 * (z1 - z0) / denom;
z0 = z1;
f0 = f1;
z1 = z2;
f1 = eval(z1)?.0.sigma[2];
}
eval(z1)
}
pub fn consistent_tangent(
law: PlasticLaw,
eps_b: &[f64; 6],
prev: &PrevState,
mat: &MatParams,
dt: Option<f64>,
) -> Result<[[f64; 6]; 6]> {
let d = raw_consistent_tangent(law, eps_b, prev, mat, dt)?;
Ok(symmetrise(d))
}
fn symmetrise(d: [[f64; 6]; 6]) -> [[f64; 6]; 6] {
let mut out = [[0.0; 6]; 6];
for i in 0..6 {
for j in 0..6 {
out[i][j] = 0.5 * (d[i][j] + d[j][i]);
}
}
out
}
fn raw_consistent_tangent(
law: PlasticLaw,
eps_b: &[f64; 6],
prev: &PrevState,
mat: &MatParams,
dt: Option<f64>,
) -> Result<[[f64; 6]; 6]> {
if law.has_analytic_tangent() {
let trial = elastic_predictor(eps_b, prev, mat.lambda, mat.mu);
let hardening = match law {
PlasticLaw::Perfect => 0.0,
PlasticLaw::Isotropic => mat.get("H")?,
_ => unreachable!("only von Mises has an analytic tangent"),
};
return Ok(von_mises::tangent(&trial, mat, hardening, prev.p));
}
finite_difference_tangent(law, eps_b, prev, mat, dt)
}
fn finite_difference_tangent(
law: PlasticLaw,
eps_b: &[f64; 6],
prev: &PrevState,
mat: &MatParams,
dt: Option<f64>,
) -> Result<[[f64; 6]; 6]> {
let scale = eps_b.iter().fold(0.0_f64, |m, v| m.max(v.abs())).max(1e-8);
let h = 1e-6 * scale;
let mut d = [[0.0; 6]; 6];
for j in 0..6 {
let run = |sign: f64| -> Result<[f64; 6]> {
let mut e = *eps_b;
e[j] += sign * h;
let trial = elastic_predictor(&e, prev, mat.lambda, mat.mu);
Ok(law.return_map(&trial, prev, mat, dt)?.sigma)
};
let (sp, sm) = (run(1.0)?, run(-1.0)?);
let factor = if j < 3 { 1.0 } else { 0.5 };
for i in 0..6 {
d[i][j] = factor * (sp[i] - sm[i]) / (2.0 * h);
}
}
Ok(d)
}
pub fn elastic_tangent(lambda: f64, mu: f64) -> [[f64; 6]; 6] {
let mut c = [[0.0; 6]; 6];
for i in 0..3 {
for j in 0..3 {
c[i][j] = if i == j { lambda + 2.0 * mu } else { lambda };
}
}
for i in 3..6 {
c[i][i] = mu;
}
c
}
pub fn require_positive(law: PlasticLaw, name: &str, value: f64) -> Result<f64> {
if value <= 0.0 {
return Err(PyrucastError::Message(format!(
"plasticity ({law}): {name} = {value} must be positive"
)));
}
Ok(value)
}