rustfront 0.4.0

Evaluate MFront material behaviours (constitutive laws) at a material point, in pure Rust, without MGIS or any C++ build dependency
Documentation
//! The errors of this crate.

use core::fmt;
use std::path::PathBuf;

use crate::{Hypothesis, ParameterValue};

/// Everything that can go wrong when loading a behaviour, a model or a
/// material property, and when integrating or evaluating it. `name` is the
/// name of the behaviour, model or material property.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// The shared library could not be opened.
    Open {
        /// The path given to the loader.
        library: PathBuf,
        /// Why the system refused it.
        source: libloading::Error,
    },
    /// A symbol that must be exported is missing from the library: the name
    /// is wrong, or the library was not generated by MFront.
    MissingSymbol {
        /// The symbol searched for.
        symbol: String,
    },
    /// A string exported by the library is not valid UTF-8.
    InvalidString {
        /// The symbol holding the string.
        symbol: String,
    },
    /// The library was generated for another interface than `generic`.
    NotGeneric {
        /// The behaviour, model or material property.
        name: String,
        /// The interface it was generated for.
        interface: String,
    },
    /// A material property was loaded as a behaviour, or the other way round.
    UnexpectedKind {
        /// The behaviour, model or material property.
        name: String,
        /// What the loader expects: `behaviour or model`, `material property`.
        expected: &'static str,
    },
    /// The version of the `generic` interface is not 1, the only one this
    /// crate knows.
    UnsupportedApiVersion {
        /// The behaviour or model.
        name: String,
        /// The version found.
        version: u16,
    },
    /// The library was generated by a TFEL version older than 5.1.0.
    UnsupportedTfelVersion {
        /// The behaviour, model or material property.
        name: String,
        /// The version found.
        version: String,
    },
    /// The behaviour is a cohesive zone model, not supported yet.
    UnsupportedBehaviourType {
        /// The behaviour.
        name: String,
        /// The `_BehaviourType` symbol: 3 for a cohesive zone model.
        code: u16,
    },
    /// A finite strain behaviour of another kinematic than the deformation
    /// gradient and the Cauchy stress.
    UnsupportedKinematic {
        /// The behaviour.
        name: String,
        /// The `_BehaviourKinematic` symbol; 3 is the one supported.
        kinematic: u16,
    },
    /// [`crate::Settings`] chooses a stress measure or a tangent operator for
    /// a behaviour that is not a finite strain one.
    FiniteStrainSettings {
        /// The behaviour.
        name: String,
    },
    /// The behaviour was not generated for the requested hypothesis.
    UnsupportedHypothesis {
        /// The behaviour or model.
        name: String,
        /// The requested hypothesis.
        hypothesis: Hypothesis,
        /// The hypotheses the library provides.
        supported: Vec<String>,
    },
    /// A variable has a type this crate does not handle yet (arrays,
    /// dimensioned types).
    UnsupportedVariableType {
        /// The variable.
        variable: String,
        /// Its type code in MFront's encoding.
        code: i32,
    },
    /// A block of the tangent operator names a variable the behaviour does not
    /// declare.
    InvalidTangentOperatorBlock {
        /// The unknown variable.
        variable: String,
    },
    /// The string is not the name of a modelling hypothesis.
    UnknownHypothesis(String),
    /// A setting names a parameter that is not declared.
    UnknownParameter {
        /// The behaviour, model or material property.
        name: String,
        /// The unknown parameter.
        parameter: String,
    },
    /// A setting gives a parameter a value of another type.
    WrongParameterType {
        /// The parameter.
        parameter: String,
        /// Its default value, of the expected type.
        expected: ParameterValue,
    },
    /// The library refused the value of a parameter, and printed why on the
    /// standard error.
    ParameterRejected {
        /// The parameter.
        parameter: String,
    },
    /// An array given to [`crate::Behaviour::integrate`] or
    /// [`crate::MaterialProperty::evaluate`] does not have the expected
    /// length.
    WrongLength {
        /// The array, such as `s1.internal_state_variables` or `inputs`.
        array: &'static str,
        /// The length expected.
        expected: usize,
        /// The length given.
        found: usize,
    },
    /// An array given to [`crate::Behaviour::rotate_gradients`] or its
    /// siblings does not hold whole points.
    IncompletePoint {
        /// The array: `gradients`, `thermodynamic forces` or `tangent operator`.
        array: &'static str,
        /// The size of one point.
        size: usize,
        /// The length given.
        found: usize,
    },
    /// The behaviour is isotropic: it exports no rotation, and needs none.
    NotOrthotropic {
        /// The behaviour.
        name: String,
    },
    /// A variable to rotate is a vector, which the rotations TFEL 5.1
    /// generates do not support: they would end the process.
    UnsupportedRotation {
        /// The behaviour.
        name: String,
        /// The vector.
        variable: String,
    },
    /// The matrix given to [`crate::Rotation`] is not a rotation.
    InvalidRotation {
        /// What is wrong with it.
        reason: &'static str,
    },
    /// The behaviour failed to integrate. The state at the end of the time
    /// step is meaningless.
    IntegrationFailed {
        /// The message the behaviour left, possibly empty.
        message: String,
        /// The factor by which the behaviour proposes to scale the time step
        /// before trying again.
        time_step_scaling_factor: f64,
    },
    /// An input of a material property is out of its physical bounds, or of
    /// its bounds with the strict policy: no value.
    OutOfBounds {
        /// The input.
        input: String,
        /// What the material property says, such as `T is over its upper
        /// bound (1200>1000).`
        message: String,
    },
    /// The evaluation of a material property failed: C++ exception, error of
    /// the C library, value that is not finite.
    EvaluationFailed {
        /// What went wrong.
        message: String,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Open { library, source } => {
                write!(f, "cannot open `{}`: {source}", library.display())
            }
            Error::MissingSymbol { symbol } => {
                write!(f, "the library does not export the symbol `{symbol}`")
            }
            Error::InvalidString { symbol } => {
                write!(f, "the symbol `{symbol}` is not a valid UTF-8 string")
            }
            Error::NotGeneric { name, interface } => write!(
                f,
                "`{name}` was generated for the `{interface}` interface, \
                 not for the `generic` one"
            ),
            Error::UnexpectedKind { name, expected } => {
                write!(f, "`{name}` is not a {expected}")
            }
            Error::UnsupportedApiVersion { name, version } => write!(
                f,
                "`{name}` uses version {version} of the `generic` interface, \
                 only version 1 is supported"
            ),
            Error::UnsupportedTfelVersion { name, version } => write!(
                f,
                "`{name}` was generated by TFEL {version}, TFEL 5.1.0 or later is required"
            ),
            Error::UnsupportedBehaviourType { name, code } => write!(
                f,
                "`{name}` is a cohesive zone model (behaviour type {code}): not supported yet"
            ),
            Error::UnsupportedKinematic { name, kinematic } => write!(
                f,
                "`{name}` is a finite strain behaviour of kinematic {kinematic}, \
                 only the deformation gradient and the Cauchy stress (3) are supported"
            ),
            Error::FiniteStrainSettings { name } => write!(
                f,
                "`{name}` is not a finite strain behaviour: it has no stress measure \
                 nor finite strain tangent operator to choose"
            ),
            Error::UnsupportedHypothesis {
                name,
                hypothesis,
                supported,
            } => write!(
                f,
                "`{name}` was not generated for the `{hypothesis}` hypothesis (available: {})",
                supported.join(", ")
            ),
            Error::UnsupportedVariableType { variable, code } => write!(
                f,
                "the variable `{variable}` has a type (code {code}) that is not supported yet"
            ),
            Error::InvalidTangentOperatorBlock { variable } => write!(
                f,
                "the tangent operator names `{variable}`, which the behaviour does not declare"
            ),
            Error::UnknownHypothesis(name) => {
                write!(f, "`{name}` is not a modelling hypothesis")
            }
            Error::UnknownParameter { name, parameter } => {
                write!(f, "`{name}` has no parameter `{parameter}`")
            }
            Error::WrongParameterType {
                parameter,
                expected,
            } => {
                let kind = match expected {
                    ParameterValue::Real(_) => "real",
                    ParameterValue::Integer(_) => "integer",
                    ParameterValue::UnsignedShort(_) => "unsigned short",
                };
                write!(f, "the parameter `{parameter}` is {kind}")
            }
            Error::ParameterRejected { parameter } => write!(
                f,
                "the library refused the value of `{parameter}` (see the standard error)"
            ),
            Error::WrongLength {
                array,
                expected,
                found,
            } => write!(f, "`{array}` has {found} values, {expected} expected"),
            Error::IncompletePoint { array, size, found } => write!(
                f,
                "`{array}` has {found} values, not a multiple of {size}, the size of one point"
            ),
            Error::NotOrthotropic { name } => {
                write!(f, "`{name}` is isotropic: it has no rotation")
            }
            Error::UnsupportedRotation { name, variable } => write!(
                f,
                "`{name}` cannot rotate `{variable}`: the rotation of vectors is not supported"
            ),
            Error::InvalidRotation { reason } => write!(f, "not a rotation matrix: {reason}"),
            Error::IntegrationFailed {
                message,
                time_step_scaling_factor,
            } => write!(
                f,
                "integration failed (proposed time step scaling factor: \
                 {time_step_scaling_factor}): {message}"
            ),
            Error::OutOfBounds { input, message } => {
                write!(f, "`{input}` is out of its bounds: {message}")
            }
            Error::EvaluationFailed { message } => write!(f, "evaluation failed: {message}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Error::Open { source, .. } => Some(source),
            _ => None,
        }
    }
}