rustfront 0.1.0

Evaluate MFront material behaviours (constitutive laws) at a material point, in pure Rust, without MGIS or any C++ build dependency
Documentation
//! Loads and integrates the behaviours of `tests/behaviours`, compiled by
//! `mfront` when the tests start. Without `mfront` in the `PATH`, the tests
//! fail: they never pass without checking anything.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;

use rustfront::voigt::{self, Shear};
use rustfront::{
    Behaviour, Error, FinalState, Hypothesis, InitialState, Symmetry, TangentOperator, VariableType,
};

const YOUNG: f64 = 200e9;
const POISSON: f64 = 0.3;
const LAMBDA: f64 = YOUNG * POISSON / ((1.0 + POISSON) * (1.0 - 2.0 * POISSON));
const MU: f64 = YOUNG / (2.0 * (1.0 + POISSON));
const TEMPERATURE: [f64; 1] = [293.15];

/// Loads `name` from the library compiled, once for all the tests, from the
/// sources of `tests/behaviours`.
fn load(name: &str, hypothesis: Hypothesis) -> Result<Behaviour, Error> {
    static LIBRARY: OnceLock<PathBuf> = OnceLock::new();
    let library = LIBRARY.get_or_init(|| {
        let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("behaviours");
        std::fs::create_dir_all(&dir).unwrap();
        let sources = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/behaviours");
        let output = Command::new("mfront")
            .args(["--obuild", "--interface=generic"])
            .arg(sources.join("Elasticity.mfront"))
            .arg(sources.join("Norton.mfront"))
            .current_dir(&dir)
            .output()
            .unwrap_or_else(|e| {
                panic!(
                    "cannot run `mfront` ({e}): these tests need MFront (TFEL ≥ 5.1.0) in the PATH"
                )
            });
        assert!(
            output.status.success(),
            "mfront failed:\n{}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        let file = format!(
            "{}Behaviour{}",
            std::env::consts::DLL_PREFIX,
            std::env::consts::DLL_SUFFIX
        );
        dir.join("src").join(file)
    });
    // SAFETY: the library was just generated by MFront.
    unsafe { Behaviour::load(library, name, hypothesis) }
}

/// Integrates `Elasticity` in 3D from rest to the strain `eps` (TFEL
/// convention): the stress, the von Mises stress and the tangent operator.
fn elastic(eps: [f64; 6]) -> ([f64; 6], f64, Vec<f64>) {
    let behaviour = load("Elasticity", Hypothesis::Tridimensional).unwrap();
    let material = [YOUNG, POISSON];
    let (isv0, mut isv1) = ([0.0], [0.0]);
    let (zero, mut sig) = ([0.0; 6], [0.0; 6]);
    let mut k = vec![0.0; 36];
    let s0 = InitialState {
        gradients: &zero,
        thermodynamic_forces: &zero,
        material_properties: &material,
        internal_state_variables: &isv0,
        external_state_variables: &TEMPERATURE,
        ..Default::default()
    };
    let mut s1 = FinalState {
        gradients: &eps,
        thermodynamic_forces: &mut sig,
        material_properties: &material,
        internal_state_variables: &mut isv1,
        external_state_variables: &TEMPERATURE,
    };
    let tangent = Some((TangentOperator::ConsistentTangent, k.as_mut_slice()));
    let r = behaviour.integrate(0.0, &s0, &mut s1, tangent).unwrap();
    assert_eq!(r.time_step_scaling_factor, 1.0);
    (sig, isv1[0], k)
}

fn assert_close(found: f64, expected: f64) {
    let tolerance = 1e-12 * expected.abs().max(1.0);
    assert!(
        (found - expected).abs() <= tolerance,
        "found {found}, expected {expected}"
    );
}

#[test]
fn elasticity_describes_itself() {
    let behaviour = load("Elasticity", Hypothesis::Tridimensional).unwrap();
    let d = behaviour.description();
    assert_eq!(d.name, "Elasticity");
    assert_eq!(d.hypothesis, Hypothesis::Tridimensional);
    // The version of the `mfront` that compiled the library: `Version : 5.1.0`.
    let output = Command::new("mfront").arg("--version").output().unwrap();
    let version = String::from_utf8_lossy(&output.stdout);
    assert!(
        version.contains(&format!("Version : {}", d.tfel_version)),
        "{} is not the version of mfront: {version}",
        d.tfel_version
    );
    assert_eq!(d.symmetry, Symmetry::Isotropic);
    let names =
        |v: &rustfront::Variables| v.list.iter().map(|v| v.name.clone()).collect::<Vec<_>>();
    assert_eq!(names(&d.gradients), ["Strain"]);
    assert_eq!(d.gradients.list[0].variable_type, VariableType::Stensor);
    assert_eq!(d.gradients.size, 6);
    assert_eq!(names(&d.thermodynamic_forces), ["Stress"]);
    assert_eq!(
        names(&d.material_properties),
        ["YoungModulus", "PoissonRatio"]
    );
    assert_eq!(names(&d.internal_state_variables), ["VonMisesStress"]);
    assert_eq!(names(&d.external_state_variables), ["Temperature"]);
    assert_eq!(
        d.tangent_operator_blocks,
        [("Stress".to_owned(), "Strain".to_owned())]
    );
    assert_eq!(d.tangent_operator_size, 36);
}

#[test]
fn sizes_follow_the_hypothesis() {
    let behaviour = load("Norton", Hypothesis::PlaneStrain).unwrap();
    let d = behaviour.description();
    let isvs = &d.internal_state_variables;
    assert_eq!(isvs.list[0].name, "ElasticStrain");
    assert_eq!((isvs.list[0].offset, isvs.list[0].size), (0, 4));
    assert_eq!(isvs.list[1].name, "EquivalentViscoplasticStrain");
    assert_eq!((isvs.list[1].offset, isvs.list[1].size), (4, 1));
    assert_eq!(isvs.size, 5);
    assert_eq!(d.gradients.size, 4);
    assert_eq!(d.tangent_operator_size, 16);
    let mps: Vec<_> = d
        .material_properties
        .list
        .iter()
        .map(|v| v.name.as_str())
        .collect();
    assert_eq!(
        mps,
        [
            "NortonCoefficient",
            "NortonExponent",
            "YoungModulus",
            "PoissonRatio"
        ]
    );
}

#[test]
fn unsupported_requests_are_refused() {
    assert!(matches!(
        load("Elasticity", Hypothesis::PlaneStress),
        Err(Error::UnsupportedHypothesis { .. })
    ));
    assert!(matches!(
        load("Plasticity", Hypothesis::Tridimensional),
        Err(Error::MissingSymbol { .. })
    ));
    // SAFETY: the file does not exist, nothing is run.
    let missing = unsafe {
        Behaviour::load(
            "no/such/library.so",
            "Elasticity",
            Hypothesis::Tridimensional,
        )
    };
    assert!(matches!(missing, Err(Error::Open { .. })));
}

#[test]
fn uniaxial_strain_gives_the_elastic_stress_and_tangent() {
    let e = 1e-3;
    let (sig, _, k) = elastic([e, 0.0, 0.0, 0.0, 0.0, 0.0]);
    assert_close(sig[0], (LAMBDA + 2.0 * MU) * e);
    assert_close(sig[1], LAMBDA * e);
    assert_close(sig[2], LAMBDA * e);
    assert_eq!(&sig[3..], [0.0; 3]);
    // Row major, λ I⊗I + 2μ I: λ + 2μ on the normal diagonal, λ off it, 2μ on
    // the shear diagonal.
    assert_close(k[0], LAMBDA + 2.0 * MU);
    assert_close(k[1], LAMBDA);
    assert_close(k[3 * 6 + 3], 2.0 * MU);
    assert_eq!(k[3], 0.0);
}

#[test]
fn the_voigt_tangent_has_the_shear_modulus() {
    // Any strain: the tangent of linear elasticity does not depend on it.
    let (_, _, k) = elastic([1e-3, 0.0, 0.0, 0.0, 0.0, 0.0]);
    let mut d = [0.0; 36];
    voigt::tangent_from_tfel(&k, Shear::Engineering, &mut d);
    for i in 0..6 {
        for j in 0..6 {
            let expected = match (i < 3, j < 3) {
                (true, true) if i == j => LAMBDA + 2.0 * MU,
                (true, true) => LAMBDA,
                (false, false) if i == j => MU,
                _ => 0.0,
            };
            assert_close(d[6 * i + j], expected);
        }
    }
}

#[test]
fn shear_components_carry_a_square_root_of_two() {
    // A pure shear ε_xy = γ/2: TFEL stores √2·ε_xy.
    let e = 1e-3;
    let (sig, seq, _) = elastic([0.0, 0.0, 0.0, 2f64.sqrt() * e, 0.0, 0.0]);
    let tau = 2.0 * MU * e;
    assert_close(sig[3], 2f64.sqrt() * tau);
    // The von Mises stress of a pure shear τ is √3·τ: this only holds if the
    // behaviour reads the shear components with the √2 factor.
    assert_close(seq, 3f64.sqrt() * tau);
}

#[test]
fn norton_creeps() {
    let behaviour = load("Norton", Hypothesis::Tridimensional).unwrap();
    let material = [8e-67, 8.2, YOUNG, POISSON];
    let e = 1e-3;
    let eps1 = [e, 0.0, 0.0, 0.0, 0.0, 0.0];
    let (zero, mut sig) = ([0.0; 6], [0.0; 6]);
    let isv0 = [0.0; 7];
    let mut isv1 = [0.0; 7];
    let mut k = [0.0; 36];
    let s0 = InitialState {
        gradients: &zero,
        thermodynamic_forces: &zero,
        material_properties: &material,
        internal_state_variables: &isv0,
        external_state_variables: &TEMPERATURE,
        ..Default::default()
    };
    let mut s1 = FinalState {
        gradients: &eps1,
        thermodynamic_forces: &mut sig,
        material_properties: &material,
        internal_state_variables: &mut isv1,
        external_state_variables: &TEMPERATURE,
    };
    let tangent = Some((TangentOperator::ConsistentTangent, k.as_mut_slice()));
    behaviour.integrate(0.1, &s0, &mut s1, tangent).unwrap();
    // The viscoplastic strain grows, and the stress relaxes below the elastic
    // one; the elastic strain (first six values) carries what is left.
    let p = isv1[6];
    assert!(p > 0.0, "p = {p}");
    assert!(sig[0] < (LAMBDA + 2.0 * MU) * e);
    assert!(isv1[0] < e);
    assert!(k[0] < LAMBDA + 2.0 * MU);
}

#[test]
fn no_tangent_operator_can_be_requested() {
    let behaviour = load("Elasticity", Hypothesis::Tridimensional).unwrap();
    let material = [YOUNG, POISSON];
    let eps1 = [1e-3, 0.0, 0.0, 0.0, 0.0, 0.0];
    let (zero, mut sig) = ([0.0; 6], [0.0; 6]);
    let (isv0, mut isv1) = ([0.0], [0.0]);
    let s0 = InitialState {
        gradients: &zero,
        thermodynamic_forces: &zero,
        material_properties: &material,
        internal_state_variables: &isv0,
        external_state_variables: &TEMPERATURE,
        ..Default::default()
    };
    let mut s1 = FinalState {
        gradients: &eps1,
        thermodynamic_forces: &mut sig,
        material_properties: &material,
        internal_state_variables: &mut isv1,
        external_state_variables: &TEMPERATURE,
    };
    behaviour.integrate(0.0, &s0, &mut s1, None).unwrap();
    assert_close(sig[0], (LAMBDA + 2.0 * MU) * 1e-3);
}

#[test]
fn arrays_of_the_wrong_length_are_refused() {
    let behaviour = load("Norton", Hypothesis::Tridimensional).unwrap();
    let material = [8e-67, 8.2, YOUNG, POISSON];
    let (zero, mut sig) = ([0.0; 6], [0.0; 6]);
    // Six values instead of seven: the elastic strain without p.
    let isv0 = [0.0; 7];
    let mut isv1 = [0.0; 6];
    let s0 = InitialState {
        gradients: &zero,
        thermodynamic_forces: &zero,
        material_properties: &material,
        internal_state_variables: &isv0,
        external_state_variables: &TEMPERATURE,
        ..Default::default()
    };
    let mut s1 = FinalState {
        gradients: &zero,
        thermodynamic_forces: &mut sig,
        material_properties: &material,
        internal_state_variables: &mut isv1,
        external_state_variables: &TEMPERATURE,
    };
    let r = behaviour.integrate(0.1, &s0, &mut s1, None);
    assert!(
        matches!(
            r,
            Err(Error::WrongLength {
                array: "s1.internal_state_variables",
                expected: 7,
                found: 6
            })
        ),
        "{r:?}"
    );
}