pub mod damage_tc;
pub mod mazars;
pub mod sic_sic;
use crate::containers::element_field::SubElementField;
use crate::containers::field::SubField;
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::handle::Handle;
use crate::models::elasticity::{self, ElasticityModel};
use crate::models::owned_components;
use crate::models::{CellGeom, Domain, MatrixLayout, Physics, SubModelKind};
use serde::{Deserialize, Serialize};
const AXES: [&str; 3] = ["x", "y", "z"];
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum DamageLaw {
#[default]
Mazars,
DamageTc,
SicSic,
}
impl DamageLaw {
pub fn from_tag(tag: &str) -> Option<Self> {
match tag {
"mazars" => Some(Self::Mazars),
"damage_tc" => Some(Self::DamageTc),
"sic_sic" => Some(Self::SicSic),
_ => None,
}
}
pub fn to_tag(self) -> &'static str {
match self {
Self::Mazars => "mazars",
Self::DamageTc => "damage_tc",
Self::SicSic => "sic_sic",
}
}
pub const ALL: [DamageLaw; 3] = [Self::Mazars, Self::DamageTc, Self::SicSic];
pub fn tag_list() -> String {
Self::ALL
.iter()
.map(|l| l.to_tag())
.collect::<Vec<_>>()
.join("|")
}
pub fn material_components(self, space_dim: usize) -> &'static [&'static str] {
match self {
Self::Mazars => mazars::MATERIAL,
Self::DamageTc => damage_tc::MATERIAL,
Self::SicSic if space_dim == 2 => sic_sic::MATERIAL_2D,
Self::SicSic => sic_sic::MATERIAL_3D,
}
}
pub fn internal_names(self) -> Vec<String> {
match self {
Self::Mazars => vec!["kappa".into()],
Self::DamageTc => vec![
"r_plus".into(),
"r_minus".into(),
"d_plus".into(),
"d_minus".into(),
],
Self::SicSic => vec![
"kappa_1".into(),
"kappa_2".into(),
"kappa_3".into(),
"d_1".into(),
"d_2".into(),
"d_3".into(),
],
}
}
pub fn update(
self,
eps: &[f64; 6],
prev: &[f64],
mat: &MatRead,
space_dim: usize,
) -> Result<DamageUpdate> {
match self {
Self::Mazars => mazars::update(eps, prev, mat),
Self::DamageTc => damage_tc::update(eps, prev, mat),
Self::SicSic => sic_sic::update(eps, prev, mat, space_dim),
}
}
}
impl std::fmt::Display for DamageLaw {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.to_tag())
}
}
pub struct DamageUpdate {
pub sigma: [f64; 6],
pub damage: f64,
pub vars: Vec<f64>,
}
pub struct MatRead<'a> {
pub field: &'a SubElementField,
pub cell: usize,
}
impl MatRead<'_> {
pub fn get(&self, name: &str) -> Result<f64> {
self.field.value(self.cell, 0, name)
}
}
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 pos(x: f64) -> f64 {
x.max(0.0)
}
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(),
]
}
}
#[derive(Clone, Serialize, Deserialize)]
pub struct Damage {
pub(crate) fespace: Handle<SubFiniteElementSpace>,
pub(crate) support: Handle<SubMesh>,
pub(crate) space_dim: usize,
pub(crate) model: ElasticityModel,
pub(crate) law: DamageLaw,
}
impl Damage {
pub fn new(fespace: Handle<SubFiniteElementSpace>, model: ElasticityModel) -> Result<Self> {
Self::with_law(fespace, model, DamageLaw::Mazars)
}
pub fn with_law(
fespace: Handle<SubFiniteElementSpace>,
model: ElasticityModel,
law: DamageLaw,
) -> Result<Self> {
let (submesh, space_dim, ref_dim, axisymmetric) = {
let s = fespace.read();
(
s.submesh(),
s.space_dim(),
s.ref_dim()?,
s.is_axisymmetric(),
)
};
crate::models::elasticity::check_continuum_dimensions("Damage", 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!(
"Damage: 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!(
"Damage: model {model:?} on an axisymmetric geometry — a body of \
revolution requires the `axisymmetric` model"
)
} else {
"Damage: 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 Damage {
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_matrix(
&self,
geoms: &[CellGeom],
material: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let mat = material.expect("Damage 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("Damage 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 physics(&self) -> &'static [Physics] {
&[Physics::Mechanical]
}
fn label(&self) -> &'static str {
"Damage"
}
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<Damage({:?}, {})>\n primal var(s): {primal}\n dual var(s): {dual}\n \
support: {n} node(s)",
self.model, self.law
)
}
}
impl Domain for Damage {
fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn material_components(&self) -> Option<Vec<String>> {
Some(owned_components(
self.law.material_components(self.space_dim),
))
}
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>> {
let mut comps = stress_names(self.space_dim, self.model);
comps.push("damage".into());
comps.extend(self.law.internal_names());
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("Damage declares a material_fespace ⇒ material is supplied");
let (cell, d) = (geom.cell, self.space_dim);
let read = MatRead { field: mat, cell };
let eps = read_strain(deformation, cell, g, d, read.get("nu")?, self.model)?;
let prev_vars: Vec<f64> = match prev {
None => Vec::new(),
Some(_) => self
.law
.internal_names()
.iter()
.map(|n| prev_opt(prev, cell, g, n))
.collect(),
};
let update = self.law.update(&eps, &prev_vars, &read, d)?;
let v = stress_names(d, self.model).len();
for r in 0..v {
out[r] = voigt_stress(&update.sigma, d, self.model, r);
}
out[v] = update.damage;
for (i, value) in update.vars.iter().enumerate() {
out[v + 1 + i] = *value;
}
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 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_strain(
f: &SubElementField,
cell: usize,
g: usize,
space_dim: usize,
nu: f64,
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 == ElasticityModel::PlaneStress {
eps[2] = -nu / (1.0 - nu) * (eps[0] + eps[1]);
} else if model.is_axisymmetric() {
eps[2] = f.value(cell, g, "eps_zz")?;
}
} else {
for (k, suf) in ["xx", "yy", "zz", "yz", "xz", "xy"].iter().enumerate() {
eps[k] = f.value(cell, g, &format!("eps_{suf}"))?;
}
}
Ok(eps)
}
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]
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aggregate::Aggregate;
use crate::atoms::{ElementType, Node};
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) -> Damage {
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();
Damage::new(fes.get(0).unwrap(), model).unwrap()
}
fn material(mz: &Damage) -> Handle<SubElementField> {
let mut mat = SubElementField::new(
mz.fespace.clone(),
mazars::MATERIAL.iter().map(|s| s.to_string()).collect(),
)
.unwrap();
mat.set_uniform("E", 30_000.0).unwrap(); mat.set_uniform("nu", 0.2).unwrap();
mat.set_uniform("eps_d0", 1e-4).unwrap();
mat.set_uniform("A_t", 0.8).unwrap();
mat.set_uniform("B_t", 20_000.0).unwrap();
mat.set_uniform("A_c", 1.4).unwrap();
mat.set_uniform("B_c", 1_900.0).unwrap();
Handle::new(mat)
}
fn strain_field(mz: &Damage, eps_xx: f64) -> Handle<SubElementField> {
let mut s = SubElementField::new(
mz.fespace.clone(),
vec!["eps_xx".into(), "eps_xy".into(), "eps_yy".into()],
)
.unwrap();
s.set_uniform("eps_xx", eps_xx).unwrap();
Handle::new(s)
}
#[test]
fn vars_and_material() {
let mz = unit_quad(ElasticityModel::PlaneStress);
assert_eq!(mz.primal_vars(), vec!["u_x", "u_y"]);
assert_eq!(mz.dual_vars(), vec!["f_x", "f_y"]);
assert_eq!(
mz.material_components(),
Some(owned_components(mazars::MATERIAL))
);
}
#[test]
fn undamaged_below_threshold() {
let mz = unit_quad(ElasticityModel::PlaneStress);
let mat = material(&mz);
let eps0 = 1e-5; let strain = strain_field(&mz, eps0);
let out = mz
.integrate_behavior(&strain, None, Some(&mat), None)
.unwrap();
let (e, nu) = (30_000.0, 0.2);
let c = e / (1.0 - nu * nu);
for g in 0..out.gauss_count() {
assert!(out.value(0, g, "damage").unwrap().abs() < 1e-14);
assert!((out.value(0, g, "sigma_xx").unwrap() - c * eps0).abs() < 1e-6);
}
}
#[test]
fn damages_in_tension() {
let mz = unit_quad(ElasticityModel::PlaneStress);
let mat = material(&mz);
let eps0 = 5e-4; let strain = strain_field(&mz, eps0);
let out = mz
.integrate_behavior(&strain, None, Some(&mat), None)
.unwrap();
let (e, nu) = (30_000.0, 0.2);
let c = e / (1.0 - nu * nu);
for g in 0..out.gauss_count() {
let d = out.value(0, g, "damage").unwrap();
assert!(d > 0.0 && d < 1.0, "D = {d}");
assert!(out.value(0, g, "sigma_xx").unwrap() < c * eps0);
assert!(out.value(0, g, "kappa").unwrap() >= eps0 - 1e-12);
}
}
#[test]
fn kappa_is_monotone() {
let mz = unit_quad(ElasticityModel::PlaneStress);
let mat = material(&mz);
let s1 = strain_field(&mz, 5e-4);
let st1 = mz.integrate_behavior(&s1, None, Some(&mat), None).unwrap();
let k1 = st1.value(0, 0, "kappa").unwrap();
let d1 = st1.value(0, 0, "damage").unwrap();
let prev = Handle::new(st1);
let s2 = strain_field(&mz, 2e-4);
let st2 = mz
.integrate_behavior(&s2, Some(&prev), Some(&mat), None)
.unwrap();
assert!((st2.value(0, 0, "kappa").unwrap() - k1).abs() < 1e-12);
assert!((st2.value(0, 0, "damage").unwrap() - d1).abs() < 1e-9);
}
#[test]
fn solid_3d_damages() {
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();
let mz = Damage::new(fes.get(0).unwrap(), ElasticityModel::Solid).unwrap();
let mat = material(&mz);
let mut s = SubElementField::new(
mz.fespace.clone(),
["xx", "yy", "zz", "yz", "xz", "xy"]
.iter()
.map(|x| format!("eps_{x}"))
.collect(),
)
.unwrap();
s.set_uniform("eps_xx", 5e-4).unwrap();
let s = Handle::new(s);
let out = mz.integrate_behavior(&s, None, Some(&mat), None).unwrap();
for g in 0..out.gauss_count() {
assert!(out.value(0, g, "damage").unwrap() > 0.0);
}
}
}