# rustfront
[](https://github.com/Pyrucast/rustfront/actions/workflows/ci.yml)
[](https://crates.io/crates/rustfront)
[](https://docs.rs/rustfront)
Evaluate [MFront] material behaviours (constitutive laws) at a material point,
in pure Rust.
MFront compiles material behaviours (elasticity, plasticity, creep, …) into
shared libraries. `rustfront` loads the libraries generated with MFront's
`generic` interface, reads the description each behaviour exports, and
integrates the behaviour at one material point, from Rust code such as the
[pyrucast] finite-element library.
It talks to the generated library directly: no C or C++ build dependency,
nothing to compile but Rust, and a single dependency, `libloading`. The
values of the material points stay in the caller's arrays, which `rustfront`
borrows without copying them. Only loading a library is `unsafe`; integrating
is safe.
For libraries generated by TFEL 5.1.0 or later, it handles:
- small strain, finite strain and general behaviours, and cohesive zone
models, isotropic or orthotropic, for every modelling hypothesis;
- for finite strain behaviours, the Cauchy stress or either Piola-Kirchhoff
stress, with any of their tangent operators;
- for orthotropic behaviours, the rotations between the global frame and their
material frame;
- point-wise models (`@DSL DefaultModel`, …) and material properties
(`@DSL MaterialLaw`);
- the parameters and the out of bounds policy, set at load;
- the elastic, secant, tangent and consistent tangent operators, and the
prediction operators, computed alone before the integration.
> **Status:** early development. [mtest-rs], built on `rustfront`, reproduces
> MTest's results on 1109 of the 1209 cases of the tests of TFEL's generic
> interface; the others are explained in the [README of the repository].
## Requirements
- Behaviours compiled by MFront (TFEL 5.1.0 or later) with the `generic`
interface: `mfront --obuild --interface=generic Norton.mfront`.
- Rust 1.88 or later.
- To run the tests, `mfront` in the `PATH`: the tests compile the behaviours
of `tests/behaviours` and fail without it.
## Minimal example
[`examples/minimal.rs`](examples/minimal.rs) loads the isotropic linear
elasticity of [`tests/behaviours/Elasticity.mfront`](tests/behaviours/Elasticity.mfront),
which also stores the von Mises stress as an auxiliary state variable and
computes its stored energy. It prints the description of the behaviour,
integrates it once at one material point, under a tension and a shear
strain, and prints the stress and the tangent operator. From the directory of the crate (`rustfront/` in the
repository):
```bash
mfront --obuild --interface=generic tests/behaviours/Elasticity.mfront
cargo run --example minimal -- src/libBehaviour.so
```
```rust
//! The smallest use of rustfront: load a behaviour, integrate it once at one
//! material point, print what comes out.
//!
//! Compile the test behaviours first, then give the library to the example,
//! from the directory of the crate (`rustfront/` in the repository):
//!
//! ```text
//! mfront --obuild --interface=generic tests/behaviours/Elasticity.mfront
//! cargo run --example minimal -- src/libBehaviour.so
//! ```
use rustfront::voigt::{self, Shear};
use rustfront::{
Behaviour, BehaviourData, FinalState, Hypothesis, InitialState, IntegrationOptions, Settings,
};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let library = std::env::args()
.nth(1)
.ok_or("usage: minimal <path to the library generated by mfront>")?;
// Loading is the only unsafe step: opening a library runs its code.
// SAFETY: the library was generated by MFront with the `generic` interface.
let behaviour = unsafe {
Behaviour::load(
&library,
"Elasticity",
Hypothesis::Tridimensional,
&Settings::default(),
)?
};
// The description tells what the behaviour expects: the variables of each
// array of the material point, in their order, and where they sit.
let d = behaviour.description();
println!("{} (TFEL {}, {})", d.name, d.tfel_version, d.hypothesis);
for (kind, variables) in [
("gradient", &d.gradients),
("thermodynamic force", &d.thermodynamic_forces),
("material property", &d.material_properties),
("internal state variable", &d.internal_state_variables),
("external state variable", &d.external_state_variables),
] {
for v in &variables.list {
println!(
" {kind:<24} {:<16} offset {}, {} value(s)",
v.name, v.offset, v.size
);
}
}
// The arrays of the material point belong to the caller, in the order of
// the description.
let material = [200e9, 0.3]; // YoungModulus, PoissonRatio
let temperature = [293.15];
let isv0 = vec![0.0; d.internal_state_variables.size];
let mut isv1 = isv0.clone();
// Symmetric tensors follow TFEL's convention: xx, yy, zz, √2·xy, √2·xz,
// √2·yz. The strain at the end of the step is written in Voigt notation,
// xx, yy, zz, yz, xz, xy, with an engineering shear γxy = 2·εxy.
let strain0 = [0.0; 6];
let mut strain1 = [0.0; 6];
voigt::to_tfel(
&[1e-3, 0.0, 0.0, 0.0, 0.0, 1e-3],
Shear::Engineering,
&mut strain1,
);
let stress0 = [0.0; 6];
let mut stress1 = [0.0; 6];
let mut tangent = vec![0.0; d.tangent_operator_size];
// The data of the integration, as MGIS's BehaviourDataView: the time
// step, the factor by which the behaviour may scale it, the tangent
// operator and the speed of sound it writes, the two states.
let mut data = BehaviourData {
dt: 1.0,
rdt: 1.0,
k: &mut tangent,
speed_of_sound: 0.0,
s0: InitialState {
gradients: &strain0,
thermodynamic_forces: &stress0,
material_properties: &material,
internal_state_variables: &isv0,
external_state_variables: &temperature,
..Default::default()
},
s1: FinalState {
gradients: &strain1,
thermodynamic_forces: &mut stress1,
material_properties: &material,
internal_state_variables: &mut isv1,
external_state_variables: &temperature,
..Default::default()
},
};
// The integration and the consistent tangent operator, by default.
let status = behaviour.integrate(&mut data, IntegrationOptions::default())?;
println!(
"integrated: {status:?}, time step scaling factor {}, stored energy {:.4e}",
data.rdt, data.s1.stored_energy
);
// Back to the standard Voigt notation: xx, yy, zz, yz, xz, xy.
let mut stress = [0.0; 6];
voigt::from_tfel(&stress1, Shear::Tensor, &mut stress);
println!(
"stress (Voigt) {}",
stress.map(|s| format!("{s:.4e}")).join(" ")
);
let seq = d
.internal_state_variables
.list
.iter()
.find(|v| v.name == "VonMisesStress")
.ok_or("no VonMisesStress")?;
println!("von Mises stress {:.4e}", isv1[seq.offset]);
let mut stiffness = [0.0; 36];
voigt::tangent_from_tfel(&tangent, Shear::Engineering, &mut stiffness);
println!("tangent (Voigt, engineering shears)");
for row in stiffness.chunks(6) {
let row: Vec<_> = row.iter().map(|v| format!("{v:10.3e}")).collect();
println!(" {}", row.join(" "));
}
Ok(())
}
```
It prints:
```text
Elasticity (TFEL 5.1.0, Tridimensional)
gradient Strain offset 0, 6 value(s)
thermodynamic force Stress offset 0, 6 value(s)
material property YoungModulus offset 0, 1 value(s)
material property PoissonRatio offset 1, 1 value(s)
internal state variable VonMisesStress offset 0, 1 value(s)
external state variable Temperature offset 0, 1 value(s)
integrated: Reliable, time step scaling factor 1, stored energy 1.7308e5
stress (Voigt) 2.6923e8 1.1538e8 1.1538e8 0.0000e0 0.0000e0 7.6923e7
von Mises stress 2.0352e8
tangent (Voigt, engineering shears)
2.692e11 1.154e11 1.154e11 0.000e0 0.000e0 0.000e0
1.154e11 2.692e11 1.154e11 0.000e0 0.000e0 0.000e0
1.154e11 1.154e11 2.692e11 0.000e0 0.000e0 0.000e0
0.000e0 0.000e0 0.000e0 7.692e10 0.000e0 0.000e0
0.000e0 0.000e0 0.000e0 0.000e0 7.692e10 0.000e0
0.000e0 0.000e0 0.000e0 0.000e0 0.000e0 7.692e10
```
## The API, through the example
The example takes the four steps of any use of `rustfront`: load a behaviour,
read its description, give it a material point, integrate it.
### Load: `Behaviour`, `Hypothesis`, `Settings`
`Behaviour::load(library, name, hypothesis, settings)` opens the library,
finds the behaviour `name` compiled for the modelling `hypothesis`, reads and
checks what it declares, and applies the `settings`. A `Behaviour` is one
behaviour of one library for one hypothesis: load it once, then integrate it
at every material point. It can be shared between threads, since integrating
does not modify it. `Hypothesis` lists MFront's modelling hypotheses
(`Tridimensional`, `PlaneStrain`, `Axisymmetrical`, …), parses and prints
their MFront names, and fixes the number of components of the tensors: 6, 4
or 3 for a symmetric one in 3D, 2D or 1D.
Loading is the only `unsafe` call: opening a library runs its initialisation
code, and the symbols it exports are trusted to have the types MFront gives
them. Every other call is safe: `integrate` checks the length of each array
against the description before calling the behaviour.
`Settings` is what loading changes in the library: the values of parameters,
the out of bounds policy and, for a finite strain behaviour, the stress
measure and the tangent operator to compute. They are static variables of the
library, shared by every `Behaviour` loaded from it for the same behaviour:
the last load wins. `Settings::default()`, as in the example, changes nothing
(and asks a finite strain behaviour for the Cauchy stress and its derivative
with respect to the deformation gradient).
Every failure, at load or later, is a `rustfront::Error`, an enum that says
what went wrong: a missing symbol, a hypothesis the library does not provide
(with the ones it provides), an unknown parameter, an array of the wrong
length, an integration that failed, …
### Describe: `Description`, `Variables`, `Variable`
`behaviour.description()` returns what the behaviour declares about itself,
read once at load: its name, the TFEL version that generated it, the
hypothesis, its symmetry (`Symmetry::Isotropic` or `Orthotropic`), its
parameters with their default values, and the layout of each array of a
material point. An array is described by a `Variables`: `list`, its variables
in order, and `size`, its length. Each `Variable` has a `name`, a
`variable_type` (`Scalar`, `Vector`, `Stensor` or `Tensor`), the `offset` of
its first component in the array and its `size`, and its `bounds` and
`physical_bounds`, `Bounds { lower, upper }`, `None` where MFront gives none.
The description also tells what the MFront file says of itself (`source`,
`author`, `date`, `description`, `validator`, `build_id`), its `unit_system`
(`SI` with `@UnitSystem SI`, which gives physical bounds to the temperature
and the elastic properties), its `behaviour_type` (`General`, `SmallStrain`,
`FiniteStrain`, `CohesiveZoneModel`) and its `kinematic`, and whether it
computes its stored and dissipated energies.
| gradients | `gradients` | `Strain` (6) |
| thermodynamic forces | `thermodynamic_forces` | `Stress` (6) |
| material properties | `material_properties` | `YoungModulus`, `PoissonRatio` |
| internal state variables | `internal_state_variables` | `VonMisesStress` |
| external state variables | `external_state_variables` | `Temperature` |
| tangent operator | `tangent_operator_blocks`, `tangent_operator_size` | (`Stress`, `Strain`): 36 values |
The internal state variables include the auxiliary ones, such as the von
Mises stress here, and the external state variables start with the
temperature. The example sizes `isv0` and `tangent` from the description,
finds the von Mises stress by its name, and gives the material properties in
the order the description lists them.
### The material point: `BehaviourData`, `InitialState`, `FinalState`
The data of an integration are laid out as MGIS's `BehaviourDataView`, the
structure the function MFront generates reads: a `BehaviourData` holds the
time increment `dt`, the factor `rdt` by which the behaviour may scale the
time step, the array `k` of the operator it computes, the `speed_of_sound`
it computes on request, and the two states, `s0` and `s1`, made of slices
the caller owns. `InitialState` is the state at the beginning of the time
step, which the behaviour only reads. `FinalState` is the state at the end:
the caller gives the gradients, the mass density, the material properties
and the external state variables, the behaviour writes the thermodynamic
forces, the internal state variables and the stored and dissipated energies
it computes (`Description::computes_stored_energy`). `rustfront` copies
nothing and allocates nothing, so a solver can keep the values of all its
points in a few contiguous arrays and hand out one slice per point, such as
`&mut stress[6 * i..6 * (i + 1)]`. The mass density, in the reference
configuration, serves only the speed of sound; it is left at zero by
`..Default::default()`, as the energies.
Symmetric tensors are stored in TFEL's convention, `xx, yy, zz, √2·xy, √2·xz,
√2·yz`. The `voigt` module converts them, and the tangent operators, to and
from the standard Voigt notation `xx, yy, zz, yz, xz, xy`, without allocating:
the example writes its strain in Voigt notation, with the engineering shear
`γxy = 2·εxy`, and converts it with `voigt::to_tfel`.
### Integrate: `IntegrationOptions`, `IntegrationType`, `Status`
`behaviour.integrate(&mut data, options)` integrates the behaviour over the
time step, as MGIS's `integrate`. `IntegrationOptions` are those of MGIS's
`BehaviourIntegrationOptions`: the `IntegrationType`, what is computed, and
`compute_speed_of_sound`. The default is the integration and the consistent
tangent operator, `IntegrationConsistentTangentOperator`; the integration
may also come with the elastic, secant or tangent operator, or none
(`IntegrationNoTangentOperator`, for a point-wise model, `k` then possibly
empty); the `Prediction…Operator` compute a prediction operator alone,
without integrating. The operator is written in `k`:
`tangent_operator_size` values, the blocks of `tangent_operator_blocks` one
after the other, each row major. Elasticity has one block, the derivative of
the stress with respect to the strain, 6 × 6. `rustfront` writes the code
the behaviour reads in `k[0]`, from -3 to 4, 100 more for the speed of
sound.
On success, the `Status` is that of MGIS: `Reliable`, or `Unreliable` when
the behaviour proposes a smaller time step, `rdt` below 0.99; `rdt` holds
the factor it proposes. When the behaviour fails, `Error::IntegrationFailed`
carries its message and the factor by which to scale the step before trying
again.
Back in Voigt notation, `voigt::from_tfel` gives the stress, and
`voigt::tangent_from_tfel` with `Shear::Engineering` the usual stiffness
matrix, the one that multiplies strains written with engineering shears: the
shear modulus `E / (2·(1 + ν))`, 7.692e10, on the diagonal of its shear block.
### Beyond the example
- **Finite strain behaviours** (`@DSL DefaultFiniteStrain`, or a strain
measure such as `@StrainMeasure Hencky`) take the deformation gradient, an
unsymmetric tensor (`VariableType::Tensor`), and compute the stress chosen
by `Settings::stress_measure` (`StressMeasure::Cauchy`,
`SecondPiolaKirchhoff` or `FirstPiolaKirchhoff`) and the tangent operator
chosen by `Settings::finite_strain_tangent_operator`.
- **Orthotropic behaviours** (`Symmetry::Orthotropic`) integrate in their
material frame. `Behaviour::rotate(what, &r, to, values)` rotates in place,
with a `Rotation` built from a matrix (`Rotation::new`) or from two axes
(`Rotation::from_axes`), the gradients and the initial thermodynamic forces
to `Frame::Material` before the integration, the thermodynamic forces and
the tangent operator back to `Frame::Global` after it. One call rotates any
number of contiguous points.
- **Point-wise models** (`@DSL DefaultModel`, …) are loaded and integrated as
a `Behaviour`: they have no gradient, their outputs are internal state
variables and their inputs external state variables.
- **Material properties** (`@DSL MaterialLaw`) have their own C interface:
`MaterialProperty::load(library, name, parameters, policy)`, `unsafe` too,
then `evaluate(&inputs)`, with the inputs in the order of
`description().inputs`, which returns an `Evaluation`: the value and, with
`OutOfBoundsPolicy::Warning`, the input out of its bounds, if any.
## mtest-rs
[mtest-rs], from the same repository, tests a behaviour at one material
point over a loading history: an unofficial, independent reimplementation of
a subset of MTest built on `rustfront`, reading the same `.mtest` files and
writing the same `.res` files.
## Relation to MGIS
[MGIS] is the official library for calling MFront behaviours from a solver,
with C, Fortran, Python and Julia bindings; Rust bindings are on its roadmap
([thelfer/MFrontGenericInterfaceSupport#376](https://github.com/thelfer/MFrontGenericInterfaceSupport/issues/376)).
`rustfront` takes another route: it reads the description each behaviour
exports and calls the behaviour itself, without going through MGIS. It
follows MGIS's layout of the data of one material point, and leaves their
storage for many points (MGIS's `MaterialDataManager`) to the caller:
| `load(options, library, behaviour, h)` | `Behaviour::load(library, behaviour, h, &settings)` |
| `FiniteStrainBehaviourOptions` | `Settings::stress_measure`, `finite_strain_tangent_operator` |
| `setParameter`, `setOutOfBoundsPolicy` | `Settings::parameters`, `out_of_bounds_policy`, at load |
| `BehaviourDescription` | `Description`, `behaviour.description()` |
| `btype`, `kinematic`, `symmetry` | `behaviour_type`, `kinematic`, `symmetry` |
| `mps`, `isvs`, `esvs`, `to_blocks` | `material_properties`, `internal_state_variables`, `external_state_variables`, `tangent_operator_blocks` |
| `hasBounds`, `getLowerBound`, … | `Variable::bounds`, `physical_bounds` |
| `computesStoredEnergy`, `computesDissipatedEnergy` | `computes_stored_energy`, `computes_dissipated_energy` |
| `BehaviourDataView` | `BehaviourData` |
| `InitialStateView`, `StateView` | `InitialState`, `FinalState` |
| `IntegrationType` | `IntegrationType` |
| `BehaviourIntegrationOptions` | `IntegrationOptions` |
| `integrate(d, b)`: -1, 0, 1 | `behaviour.integrate(&mut d, options)`: `Err`, `Status::Unreliable`, `Status::Reliable` |
| `rotateGradients`, `rotateThermodynamicForces`, `rotateTangentOperatorBlocks` | `behaviour.rotate(Rotated::…, &r, Frame::…, values)` |
| `RotationMatrix2D`, `RotationMatrix3D` | `Rotation::from_axes`, `Rotation::new` |
## License
Licensed under either of
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or
<https://www.apache.org/licenses/LICENSE-2.0>)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or
<https://opensource.org/licenses/MIT>)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this work by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions.
[MFront]: https://thelfer.github.io/tfel/web/index.html
[MGIS]: https://github.com/thelfer/MFrontGenericInterfaceSupport
[pyrucast]: https://github.com/Pyrucast/pyrucast
[mtest-rs]: https://crates.io/crates/mtest-rs
[README of the repository]: https://github.com/Pyrucast/rustfront#try-it