rustfront 1.0.0

Evaluate MFront material behaviours (constitutive laws) at a material point, in pure Rust, without any C++ build dependency
Documentation
//! Evaluating a material property generated by MFront with the `generic`
//! interface (`@DSL MaterialLaw`), such as a Young modulus depending on the
//! temperature.

use core::ffi::CStr;
use std::path::Path;

use libloading::Library;

use crate::symbols::Symbols;
use crate::{ffi, Error, OutOfBoundsPolicy, Parameter, ParameterValue};

/// What a material property declares about itself, read from the library by
/// [`MaterialProperty::load`].
#[derive(Clone, Debug, PartialEq)]
pub struct MaterialPropertyDescription {
    /// The name of the material property.
    pub name: String,
    /// The name of its output, such as `YoungModulus`.
    pub output: String,
    /// The names of its inputs, such as `Temperature`, in the order
    /// [`MaterialProperty::evaluate`] takes them.
    pub inputs: Vec<String>,
    /// The parameters, with the values the MFront file gives them: those
    /// changed at load are not read back.
    pub parameters: Vec<Parameter>,
    /// The TFEL version that generated the library.
    pub tfel_version: String,
}

/// A value computed by [`MaterialProperty::evaluate`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Evaluation {
    /// The value.
    pub value: f64,
    /// With the [`OutOfBoundsPolicy::Warning`] policy, the index of an input
    /// out of its bounds: the value is computed, to be used with caution.
    pub out_of_bounds: Option<usize>,
}

/// A material property loaded from a library generated by MFront with the
/// `generic` interface.
///
/// It can be shared between threads: evaluating does not modify it.
#[derive(Debug)]
pub struct MaterialProperty {
    description: MaterialPropertyDescription,
    policy: OutOfBoundsPolicy,
    function: ffi::MaterialPropertyFn,
    /// Keeps the library loaded as long as `function` can be called.
    _library: Library,
}

impl MaterialProperty {
    /// Loads the material property `name` from `library`, reads its
    /// [`MaterialPropertyDescription`] and sets the values of `parameters`;
    /// every evaluation then applies `policy` to the bounds of the inputs.
    ///
    /// ```no_run
    /// use rustfront::{MaterialProperty, OutOfBoundsPolicy};
    ///
    /// // SAFETY: the library was generated by `mfront --interface=generic`,
    /// // and no evaluation of YoungModulus runs meanwhile.
    /// let young = unsafe {
    ///     MaterialProperty::load("src/libGenericMaterialLaw.so", "YoungModulus",
    ///         &[("k", 2e-4)], OutOfBoundsPolicy::Strict)?
    /// };
    /// let e = young.evaluate(&[600.0])?;
    /// println!("E(600 K) = {}", e.value);
    /// # Ok::<(), rustfront::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// When the library cannot be opened, when a symbol is missing, and when
    /// the library is not supported: interface other than `generic`, not a
    /// material property, TFEL older than 5.1.0. When a parameter cannot be
    /// set: unknown, or refused by the material property.
    ///
    /// # Safety
    ///
    /// Opening a library runs its initialisation code, and the symbols it
    /// exports are trusted to have the types MFront gives them: `library`
    /// must be a library generated by MFront, which is not modified while the
    /// returned `MaterialProperty` lives.
    ///
    /// The parameters are static variables of the library: no evaluation of
    /// this material property, by any `MaterialProperty` loaded from the same
    /// library, may run during the call; the last load wins.
    pub unsafe fn load(
        library: impl AsRef<Path>,
        name: &str,
        parameters: &[(&str, f64)],
        policy: OutOfBoundsPolicy,
    ) -> Result<Self, Error> {
        let path = library.as_ref();
        // SAFETY: the caller guarantees that the library is a genuine MFront
        // library, whose initialisation code is safe to run.
        let library = unsafe { Library::new(path) }.map_err(|source| Error::Open {
            library: path.to_path_buf(),
            source,
        })?;
        let symbols = Symbols {
            library: &library,
            name,
            hypothesis: None,
        };
        let tfel_version = symbols.check(0)?;
        let output = symbols.strings("output", 1)?.remove(0);
        let n = usize::from(symbols.u16("nargs")?);
        let inputs = if n == 0 {
            Vec::new()
        } else {
            symbols.strings("args", n)?
        };
        // SAFETY: MFront exports `<name>` with the signature of
        // `ffi::MaterialPropertyFn`. The pointer stays valid as long as the
        // library is loaded, which `_library` guarantees.
        let function = *unsafe { library.get::<ffi::MaterialPropertyFn>(name) }.map_err(|_| {
            Error::MissingSymbol {
                symbol: name.to_owned(),
            }
        })?;
        // The object holding the parameters is built at the first call, and
        // reads `<name>-parameters.txt` from the current directory: when there
        // is no such file, this sets `errno`, which makes that evaluation fail
        // (TFEL 5.1). A first call, whose inputs and result do not matter,
        // builds it here, before the parameters are set.
        let mut status = ffi::OutputStatus::CLEARED;
        let ignored = vec![f64::NAN; n];
        // SAFETY: as above, and `ignored` has the number of values it reads.
        unsafe {
            function(
                &mut status,
                ignored.as_ptr(),
                n,
                OutOfBoundsPolicy::None.code(),
            )
        };
        let declared = symbols.parameters()?;
        let values: Vec<_> = parameters
            .iter()
            .map(|&(parameter, value)| (parameter, ParameterValue::Real(value)))
            .collect();
        // SAFETY: the caller guarantees that no evaluation runs meanwhile.
        unsafe { symbols.set_parameters(&declared, &values)? };
        Ok(MaterialProperty {
            description: MaterialPropertyDescription {
                name: name.to_owned(),
                output,
                inputs,
                parameters: declared,
                tfel_version,
            },
            policy,
            function,
            _library: library,
        })
    }

    /// What the material property declares about itself: its output, inputs
    /// and parameters.
    pub fn description(&self) -> &MaterialPropertyDescription {
        &self.description
    }

    /// Evaluates the material property at `inputs`, given in the order of
    /// [`MaterialPropertyDescription::inputs`].
    ///
    /// ```no_run
    /// # use rustfront::{MaterialProperty, OutOfBoundsPolicy};
    /// # let young = unsafe { MaterialProperty::load("src/libGenericMaterialLaw.so",
    /// #     "YoungModulus", &[], OutOfBoundsPolicy::Warning)? };
    /// let e = young.evaluate(&[1200.0])?;
    /// if let Some(i) = e.out_of_bounds {
    ///     eprintln!("{} is out of its bounds", young.description().inputs[i]);
    /// }
    /// # Ok::<(), rustfront::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error::WrongLength`] when `inputs` does not have one value per
    /// input, [`Error::OutOfBounds`] when an input is out of its physical
    /// bounds, or of its bounds with the strict policy,
    /// [`Error::EvaluationFailed`] when the evaluation fails otherwise.
    pub fn evaluate(&self, inputs: &[f64]) -> Result<Evaluation, Error> {
        let expected = self.description.inputs.len();
        if inputs.len() != expected {
            return Err(Error::WrongLength {
                array: "inputs",
                expected,
                found: inputs.len(),
            });
        }
        let mut status = ffi::OutputStatus::CLEARED;
        // SAFETY: `function` was read from the library with its signature at
        // load, and `inputs` has the number of values it reads.
        let value = unsafe {
            (self.function)(
                &mut status,
                inputs.as_ptr(),
                inputs.len(),
                self.policy.code(),
            )
        };
        // The input whose bounds were crossed: its rank, from 1, whose sign is
        // not reliable.
        let input = (status.bounds_status.unsigned_abs() as usize).checked_sub(1);
        let message = CStr::from_bytes_until_nul(&status.msg)
            .map(|m| m.to_string_lossy().trim_end().to_owned())
            .unwrap_or_default();
        match status.status {
            0 | 1 => Ok(Evaluation {
                value,
                out_of_bounds: input,
            }),
            -1 => Err(Error::OutOfBounds {
                input: input
                    .and_then(|i| self.description.inputs.get(i))
                    .cloned()
                    .unwrap_or_default(),
                message,
            }),
            code => {
                let message = match code {
                    _ if !message.is_empty() => message,
                    -3 => format!("error {} of the C library", status.c_error_number),
                    -4 => "the value is not finite".to_owned(),
                    _ => format!("status {code}"),
                };
                Err(Error::EvaluationFailed { message })
            }
        }
    }
}