use crate::containers::element_field::SubElementField;
use crate::error::{PyrucastError, Result};
use crate::models::elasticity::{self, ElasticityModel};
use nalgebra::{Matrix3, Vector3};
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum MaterialSymmetry {
#[default]
Isotropic,
Orthotropic,
Anisotropic,
}
impl MaterialSymmetry {
pub fn from_tag(tag: &str) -> Option<Self> {
match tag {
"isotropic" => Some(Self::Isotropic),
"orthotropic" => Some(Self::Orthotropic),
"anisotropic" => Some(Self::Anisotropic),
_ => None,
}
}
pub fn to_tag(self) -> &'static str {
match self {
Self::Isotropic => "isotropic",
Self::Orthotropic => "orthotropic",
Self::Anisotropic => "anisotropic",
}
}
pub fn has_frame(self) -> bool {
self != Self::Isotropic
}
}
impl std::fmt::Display for MaterialSymmetry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.to_tag())
}
}
pub const FRAME_2D: [&str; 2] = ["V1X", "V1Y"];
pub const FRAME_3D: [&str; 6] = ["V1X", "V1Y", "V1Z", "V2X", "V2Y", "V2Z"];
pub fn frame_components(symmetry: MaterialSymmetry, space_dim: usize) -> &'static [&'static str] {
if !symmetry.has_frame() {
&[]
} else if space_dim == 2 {
&FRAME_2D
} else {
&FRAME_3D
}
}
pub fn frame_rotation(
material: &SubElementField,
cell: usize,
space_dim: usize,
) -> Result<Matrix3<f64>> {
let read = |name: &str| material.value(cell, 0, name);
let degenerate = |what: &str| {
PyrucastError::Message(format!(
"material frame: {what} — the orthotropy axes must be non-null and independent \
(V1, V2 are orthonormalised, so V2 need only be roughly perpendicular to V1)"
))
};
if space_dim == 2 {
let v1 = Vector3::new(read("V1X")?, read("V1Y")?, 0.0);
let e1 = v1
.try_normalize(f64::EPSILON)
.ok_or_else(|| degenerate("V1 is null"))?;
let e2 = Vector3::new(-e1[1], e1[0], 0.0);
let e3 = Vector3::new(0.0, 0.0, 1.0);
return Ok(Matrix3::from_columns(&[e1, e2, e3]));
}
let v1 = Vector3::new(read("V1X")?, read("V1Y")?, read("V1Z")?);
let v2 = Vector3::new(read("V2X")?, read("V2Y")?, read("V2Z")?);
let e1 = v1
.try_normalize(f64::EPSILON)
.ok_or_else(|| degenerate("V1 is null"))?;
let e2 = (v2 - e1 * v2.dot(&e1))
.try_normalize(f64::EPSILON)
.ok_or_else(|| degenerate("V2 is null or parallel to V1"))?;
let e3 = e1.cross(&e2);
Ok(Matrix3::from_columns(&[e1, e2, e3]))
}
const VOIGT_OF: [[usize; 3]; 3] = [[0, 5, 4], [5, 1, 3], [4, 3, 2]];
type Tensor4 = [[[[f64; 3]; 3]; 3]; 3];
fn to_tensor(d: &[[f64; 6]; 6]) -> Tensor4 {
let mut c = [[[[0.0; 3]; 3]; 3]; 3];
for (i, ci) in c.iter_mut().enumerate() {
for (j, cij) in ci.iter_mut().enumerate() {
for (k, cijk) in cij.iter_mut().enumerate() {
for (l, v) in cijk.iter_mut().enumerate() {
*v = d[VOIGT_OF[i][j]][VOIGT_OF[k][l]];
}
}
}
}
c
}
fn from_tensor(c: &Tensor4) -> [[f64; 6]; 6] {
const PAIRS: [(usize, usize); 6] = [(0, 0), (1, 1), (2, 2), (1, 2), (0, 2), (0, 1)];
let mut d = [[0.0; 6]; 6];
for (a, &(i, j)) in PAIRS.iter().enumerate() {
for (b, &(k, l)) in PAIRS.iter().enumerate() {
d[a][b] = c[i][j][k][l];
}
}
d
}
fn rotate_tensor(c: &Tensor4, r: &Matrix3<f64>) -> Tensor4 {
let mut a = *c;
for _axis in 0..4 {
let mut b = [[[[0.0; 3]; 3]; 3]; 3];
for (p, bp) in b.iter_mut().enumerate() {
for (j, bpj) in bp.iter_mut().enumerate() {
for (k, bpjk) in bpj.iter_mut().enumerate() {
for (l, v) in bpjk.iter_mut().enumerate() {
let mut acc = 0.0;
for i in 0..3 {
acc += r[(p, i)] * a[i][j][k][l];
}
*v = acc;
}
}
}
}
let mut rotated = [[[[0.0; 3]; 3]; 3]; 3];
for (i, ri) in rotated.iter_mut().enumerate() {
for (j, rij) in ri.iter_mut().enumerate() {
for (k, rijk) in rij.iter_mut().enumerate() {
for (l, v) in rijk.iter_mut().enumerate() {
*v = b[j][k][l][i];
}
}
}
}
a = rotated;
}
a
}
pub fn rotate_voigt(d: &[[f64; 6]; 6], r: &Matrix3<f64>) -> [[f64; 6]; 6] {
from_tensor(&rotate_tensor(&to_tensor(d), r))
}
pub const ORTHOTROPIC_ELASTIC: [&str; 9] = [
"E_1", "E_2", "E_3", "nu_12", "nu_13", "nu_23", "G_12", "G_13", "G_23",
];
pub const ANISOTROPIC_ELASTIC: [&str; 21] = [
"C_11", "C_12", "C_13", "C_14", "C_15", "C_16", "C_22", "C_23", "C_24", "C_25", "C_26", "C_33",
"C_34", "C_35", "C_36", "C_44", "C_45", "C_46", "C_55", "C_56", "C_66",
];
fn orthotropic_stiffness(material: &SubElementField, cell: usize) -> Result<[[f64; 6]; 6]> {
let v = |name: &str| material.value(cell, 0, name);
orthotropic_from_constants(
[v("E_1")?, v("E_2")?, v("E_3")?],
[v("nu_12")?, v("nu_13")?, v("nu_23")?],
[v("G_12")?, v("G_13")?, v("G_23")?],
)
}
pub fn orthotropic_from_constants(e: [f64; 3], nu: [f64; 3], g: [f64; 3]) -> Result<[[f64; 6]; 6]> {
let ([e1, e2, e3], [nu12, nu13, nu23], [g12, g13, g23]) = (e, nu, g);
for (name, value) in [("E_1", e1), ("E_2", e2), ("E_3", e3)] {
if value <= 0.0 {
return Err(PyrucastError::Message(format!(
"orthotropic elasticity: {name} = {value} — the Young moduli must be positive"
)));
}
}
let compliance = Matrix3::new(
1.0 / e1,
-nu12 / e1,
-nu13 / e1,
-nu12 / e1,
1.0 / e2,
-nu23 / e2,
-nu13 / e1,
-nu23 / e2,
1.0 / e3,
);
let normal = compliance.try_inverse().ok_or_else(|| {
PyrucastError::Message(
"orthotropic elasticity: the compliance is singular — check the Poisson ratios \
(a physical set satisfies nu_ij² < E_i/E_j)"
.into(),
)
})?;
let mut d = [[0.0; 6]; 6];
for i in 0..3 {
for j in 0..3 {
d[i][j] = normal[(i, j)];
}
}
d[3][3] = g23;
d[4][4] = g13;
d[5][5] = g12;
Ok(d)
}
fn anisotropic_stiffness(material: &SubElementField, cell: usize) -> Result<[[f64; 6]; 6]> {
let mut d = [[0.0; 6]; 6];
let mut names = ANISOTROPIC_ELASTIC.iter();
for i in 0..6 {
for j in i..6 {
let name = names.next().expect("21 names cover the upper triangle");
let value = material.value(cell, 0, name)?;
d[i][j] = value;
d[j][i] = value;
}
}
Ok(d)
}
pub fn elastic_constitutive(
material: &SubElementField,
cell: usize,
symmetry: MaterialSymmetry,
model: ElasticityModel,
space_dim: usize,
) -> Result<Vec<Vec<f64>>> {
if symmetry == MaterialSymmetry::Isotropic {
return Ok(elasticity::constitutive(
material.value(cell, 0, "E")?,
material.value(cell, 0, "nu")?,
model,
space_dim,
));
}
let d_mat = match symmetry {
MaterialSymmetry::Orthotropic => orthotropic_stiffness(material, cell)?,
MaterialSymmetry::Anisotropic => anisotropic_stiffness(material, cell)?,
MaterialSymmetry::Isotropic => unreachable!("handled above"),
};
let r = frame_rotation(material, cell, space_dim)?;
Ok(reduce_to_model(&rotate_voigt(&d_mat, &r), model))
}
pub fn reduce_to_model(d3: &[[f64; 6]; 6], model: ElasticityModel) -> Vec<Vec<f64>> {
const AXI_TO_3D: [usize; 4] = [0, 1, 2, 5];
const PLANE: [usize; 3] = [0, 1, 5];
match model {
ElasticityModel::Axisymmetric => AXI_TO_3D
.iter()
.map(|&i| AXI_TO_3D.iter().map(|&j| d3[i][j]).collect())
.collect(),
ElasticityModel::Solid => d3.iter().map(|r| r.to_vec()).collect(),
ElasticityModel::PlaneStrain => PLANE
.iter()
.map(|&i| PLANE.iter().map(|&j| d3[i][j]).collect())
.collect(),
ElasticityModel::PlaneStress => {
let z = 2usize;
let dzz = d3[z][z];
let cond = |i: usize, j: usize| d3[i][j] - d3[i][z] * d3[z][j] / dzz;
PLANE
.iter()
.map(|&i| PLANE.iter().map(|&j| cond(i, j)).collect())
.collect()
}
}
}
pub fn orthotropic_scalar(prefix: &str) -> [String; 3] {
[
format!("{prefix}_1"),
format!("{prefix}_2"),
format!("{prefix}_3"),
]
}
pub fn anisotropic_scalar(prefix: &str) -> [String; 6] {
[
format!("{prefix}_11"),
format!("{prefix}_12"),
format!("{prefix}_13"),
format!("{prefix}_22"),
format!("{prefix}_23"),
format!("{prefix}_33"),
]
}
pub fn transport_tensor(
material: &SubElementField,
cell: usize,
g: usize,
symmetry: MaterialSymmetry,
space_dim: usize,
prefix: &str,
) -> Result<Matrix3<f64>> {
let k3 = match symmetry {
MaterialSymmetry::Isotropic => {
let k = material.value(cell, g, prefix)?;
Matrix3::from_diagonal_element(k)
}
MaterialSymmetry::Orthotropic => {
let n = orthotropic_scalar(prefix);
let d = Matrix3::from_diagonal(&Vector3::new(
material.value(cell, 0, &n[0])?,
material.value(cell, 0, &n[1])?,
material.value(cell, 0, &n[2])?,
));
let r = frame_rotation(material, cell, space_dim)?;
r * d * r.transpose()
}
MaterialSymmetry::Anisotropic => {
let n = anisotropic_scalar(prefix);
let v = |i: usize| material.value(cell, 0, &n[i]);
let (k11, k12, k13) = (v(0)?, v(1)?, v(2)?);
let (k22, k23, k33) = (v(3)?, v(4)?, v(5)?);
let d = Matrix3::new(k11, k12, k13, k12, k22, k23, k13, k23, k33);
let r = frame_rotation(material, cell, space_dim)?;
r * d * r.transpose()
}
};
Ok(k3)
}
#[cfg(test)]
mod tests {
use super::*;
fn rot_z(theta: f64) -> Matrix3<f64> {
let (c, s) = (theta.cos(), theta.sin());
Matrix3::new(c, -s, 0.0, s, c, 0.0, 0.0, 0.0, 1.0)
}
fn isotropic_6x6(e: f64, nu: f64) -> [[f64; 6]; 6] {
let d = elasticity::constitutive(e, nu, ElasticityModel::Solid, 3);
let mut out = [[0.0; 6]; 6];
for (i, row) in d.iter().enumerate() {
out[i].copy_from_slice(row);
}
out
}
#[test]
fn tags_round_trip() {
for s in [
MaterialSymmetry::Isotropic,
MaterialSymmetry::Orthotropic,
MaterialSymmetry::Anisotropic,
] {
assert_eq!(MaterialSymmetry::from_tag(s.to_tag()), Some(s));
}
assert_eq!(MaterialSymmetry::from_tag("cubic"), None);
}
#[test]
fn voigt_tensor_round_trip_is_the_identity() {
let mut d = [[0.0; 6]; 6];
for i in 0..6 {
for j in i..6 {
let v = (i * 6 + j) as f64 + 1.0;
d[i][j] = v;
d[j][i] = v;
}
}
let back = from_tensor(&to_tensor(&d));
for i in 0..6 {
for j in 0..6 {
assert!((back[i][j] - d[i][j]).abs() < 1e-12, "slot ({i},{j})");
}
}
}
#[test]
fn rotating_an_isotropic_stiffness_changes_nothing() {
let d = isotropic_6x6(210e9, 0.3);
for theta in [0.1, 0.7, 1.3, 2.9] {
let r = rot_z(theta);
let rotated = rotate_voigt(&d, &r);
for i in 0..6 {
for j in 0..6 {
assert!(
(rotated[i][j] - d[i][j]).abs() < 1e-3,
"theta = {theta}, slot ({i},{j}): {} vs {}",
rotated[i][j],
d[i][j]
);
}
}
}
}
#[test]
fn rotating_by_a_quarter_turn_swaps_the_material_axes() {
let mut d = [[0.0; 6]; 6];
d[0][0] = 3.0;
d[1][1] = 5.0;
d[2][2] = 7.0;
d[3][3] = 11.0;
d[4][4] = 13.0;
d[5][5] = 17.0;
let rotated = rotate_voigt(&d, &rot_z(std::f64::consts::FRAC_PI_2));
assert!((rotated[0][0] - 5.0).abs() < 1e-9);
assert!((rotated[1][1] - 3.0).abs() < 1e-9);
assert!((rotated[2][2] - 7.0).abs() < 1e-9);
assert!((rotated[5][5] - 17.0).abs() < 1e-9);
assert!((rotated[3][3] - 13.0).abs() < 1e-9);
assert!((rotated[4][4] - 11.0).abs() < 1e-9);
}
#[test]
fn orthotropy_with_equal_constants_is_isotropy() {
let (e, nu) = (210e9, 0.3);
let g = e / (2.0 * (1.0 + nu));
let d = orthotropic_from_constants([e, e, e], [nu, nu, nu], [g, g, g])
.expect("isotropic constants are admissible");
let iso = isotropic_6x6(e, nu);
for i in 0..6 {
for j in 0..6 {
assert!((d[i][j] - iso[i][j]).abs() < 1e-3, "slot ({i},{j})");
}
}
}
#[test]
fn plane_stress_reduction_kills_the_out_of_plane_stress() {
let (e, nu) = (210e9, 0.3);
let reduced = reduce_to_model(&isotropic_6x6(e, nu), ElasticityModel::PlaneStress);
let expect = elasticity::constitutive(e, nu, ElasticityModel::PlaneStress, 2);
for i in 0..3 {
for j in 0..3 {
assert!(
(reduced[i][j] - expect[i][j]).abs() < 1e-3,
"slot ({i},{j}): {} vs {}",
reduced[i][j],
expect[i][j]
);
}
}
}
#[test]
fn frame_components_follow_the_symmetry_and_the_dimension() {
assert!(frame_components(MaterialSymmetry::Isotropic, 3).is_empty());
assert_eq!(
frame_components(MaterialSymmetry::Orthotropic, 2),
&FRAME_2D
);
assert_eq!(
frame_components(MaterialSymmetry::Anisotropic, 3),
&FRAME_3D
);
}
}