use core::ffi::{c_int, CStr};
use std::path::Path;
use libloading::Library;
use crate::symbols::Symbols;
use crate::{ffi, Error, Frame, Hypothesis, Rotated, Rotation};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VariableType {
Scalar,
Vector,
Stensor,
Tensor,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Bounds {
pub lower: Option<f64>,
pub upper: Option<f64>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Variable {
pub name: String,
pub variable_type: VariableType,
pub offset: usize,
pub size: usize,
pub bounds: Bounds,
pub physical_bounds: Bounds,
}
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Variables {
pub list: Vec<Variable>,
pub size: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Symmetry {
Isotropic,
Orthotropic,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BehaviourType {
General,
SmallStrain,
FiniteStrain,
CohesiveZoneModel,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kinematic {
Undefined,
SmallStrain,
CohesiveZone,
FiniteStrainFCauchy,
FiniteStrainEtoPk1,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ParameterValue {
Real(f64),
Integer(i32),
UnsignedShort(u16),
}
#[derive(Clone, Debug, PartialEq)]
pub struct Parameter {
pub name: String,
pub default: ParameterValue,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OutOfBoundsPolicy {
None,
Warning,
Strict,
}
impl OutOfBoundsPolicy {
pub(crate) fn code(self) -> c_int {
match self {
OutOfBoundsPolicy::None => 0,
OutOfBoundsPolicy::Warning => 1,
OutOfBoundsPolicy::Strict => 2,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StressMeasure {
#[default]
Cauchy,
SecondPiolaKirchhoff,
FirstPiolaKirchhoff,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FiniteStrainTangentOperator {
#[default]
CauchyByDeformationGradient,
SecondPiolaKirchhoffByGreenLagrange,
FirstPiolaKirchhoffByDeformationGradient,
KirchhoffBySpatialIncrement,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Settings<'a> {
pub parameters: &'a [(&'a str, ParameterValue)],
pub out_of_bounds_policy: Option<OutOfBoundsPolicy>,
pub stress_measure: StressMeasure,
pub finite_strain_tangent_operator: FiniteStrainTangentOperator,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Description {
pub name: String,
pub hypothesis: Hypothesis,
pub tfel_version: String,
pub source: String,
pub author: String,
pub date: String,
pub description: String,
pub validator: String,
pub build_id: String,
pub unit_system: String,
pub behaviour_type: BehaviourType,
pub kinematic: Kinematic,
pub computes_stored_energy: bool,
pub computes_dissipated_energy: bool,
pub symmetry: Symmetry,
pub gradients: Variables,
pub thermodynamic_forces: Variables,
pub material_properties: Variables,
pub internal_state_variables: Variables,
pub external_state_variables: Variables,
pub tangent_operator_blocks: Vec<(String, String)>,
pub tangent_operator_size: usize,
pub parameters: Vec<Parameter>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[expect(
clippy::enum_variant_names,
reason = "the names of MGIS's IntegrationType, which all end with Operator"
)]
pub enum IntegrationType {
PredictionTangentOperator,
PredictionSecantOperator,
PredictionElasticOperator,
IntegrationNoTangentOperator,
IntegrationElasticOperator,
IntegrationSecantOperator,
IntegrationTangentOperator,
#[default]
IntegrationConsistentTangentOperator,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct IntegrationOptions {
pub integration_type: IntegrationType,
pub compute_speed_of_sound: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
Reliable,
Unreliable,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct InitialState<'a> {
pub gradients: &'a [f64],
pub thermodynamic_forces: &'a [f64],
pub mass_density: f64,
pub material_properties: &'a [f64],
pub internal_state_variables: &'a [f64],
pub stored_energy: f64,
pub dissipated_energy: f64,
pub external_state_variables: &'a [f64],
}
#[derive(Debug, Default)]
pub struct FinalState<'a> {
pub gradients: &'a [f64],
pub thermodynamic_forces: &'a mut [f64],
pub mass_density: f64,
pub material_properties: &'a [f64],
pub internal_state_variables: &'a mut [f64],
pub stored_energy: f64,
pub dissipated_energy: f64,
pub external_state_variables: &'a [f64],
}
#[derive(Debug)]
pub struct BehaviourData<'a> {
pub dt: f64,
pub rdt: f64,
pub k: &'a mut [f64],
pub speed_of_sound: f64,
pub s0: InitialState<'a>,
pub s1: FinalState<'a>,
}
#[derive(Debug)]
enum Rotations {
Isotropic,
Vector(String),
Functions([ffi::RotateFn; 3]),
}
#[derive(Debug)]
pub struct Behaviour {
description: Description,
integrate: ffi::IntegrateFn,
finite_strain: Option<[f64; 2]>,
rotations: Rotations,
_library: Library,
}
impl Behaviour {
pub unsafe fn load(
library: impl AsRef<Path>,
name: &str,
hypothesis: Hypothesis,
settings: &Settings<'_>,
) -> Result<Self, Error> {
let path = library.as_ref();
let library = unsafe { Library::new(path) }.map_err(|source| Error::Open {
library: path.to_path_buf(),
source,
})?;
let h = hypothesis.name();
let symbols = Symbols {
library: &library,
name,
hypothesis: Some(h),
};
let dimension = hypothesis.space_dimension();
let tfel_version = symbols.check(1)?;
let version = symbols.u16("api_version")?;
if version != 1 {
return Err(Error::UnsupportedApiVersion {
name: name.to_owned(),
version,
});
}
let behaviour_type = match symbols.u16("BehaviourType")? {
0 => BehaviourType::General,
1 => BehaviourType::SmallStrain,
2 => BehaviourType::FiniteStrain,
3 => BehaviourType::CohesiveZoneModel,
code => {
return Err(Error::UnsupportedBehaviourType {
name: name.to_owned(),
code,
})
}
};
let finite_strain = behaviour_type == BehaviourType::FiniteStrain;
if !finite_strain
&& (settings.stress_measure != StressMeasure::default()
|| settings.finite_strain_tangent_operator
!= FiniteStrainTangentOperator::default())
{
return Err(Error::FiniteStrainSettings {
name: name.to_owned(),
});
}
let n = usize::from(symbols.u16("nModellingHypotheses")?);
let supported = symbols.strings("ModellingHypotheses", n)?;
if !supported.iter().any(|s| s == h) {
return Err(Error::UnsupportedHypothesis {
name: name.to_owned(),
hypothesis,
supported,
});
}
let kinematic = match symbols.u16("BehaviourKinematic")? {
1 => Kinematic::SmallStrain,
2 => Kinematic::CohesiveZone,
3 => Kinematic::FiniteStrainFCauchy,
4 => Kinematic::FiniteStrainEtoPk1,
_ => Kinematic::Undefined,
};
let text = |suffix| symbols.strings(suffix, 1).map(|mut s| s.remove(0));
let symmetry = match symbols.u16("SymmetryType")? {
0 => Symmetry::Isotropic,
_ => Symmetry::Orthotropic,
};
let gradients = layout(symbols.variables("Gradients", true)?, dimension, &symbols);
let (stress, stress_code, stress_rotation) = match settings.stress_measure {
StressMeasure::Cauchy => (("Stress", VariableType::Stensor), 0.0, "CauchyStress"),
StressMeasure::SecondPiolaKirchhoff => (
("SecondPiolaKirchhoffStress", VariableType::Stensor),
1.0,
"PK2Stress",
),
StressMeasure::FirstPiolaKirchhoff => (
("FirstPiolaKirchhoffStress", VariableType::Tensor),
2.0,
"PK1Stress",
),
};
let (block, tangent_code, tangent_rotation) = match settings.finite_strain_tangent_operator
{
FiniteStrainTangentOperator::CauchyByDeformationGradient => (
[
("Stress", VariableType::Stensor),
("DeformationGradient", VariableType::Tensor),
],
0.0,
"dsig_dF",
),
FiniteStrainTangentOperator::SecondPiolaKirchhoffByGreenLagrange => (
[
("SecondPiolaKirchhoffStress", VariableType::Stensor),
("GreenLagrangeStrain", VariableType::Stensor),
],
1.0,
"dPK2_dEGL",
),
FiniteStrainTangentOperator::FirstPiolaKirchhoffByDeformationGradient => (
[
("FirstPiolaKirchhoffStress", VariableType::Tensor),
("DeformationGradient", VariableType::Tensor),
],
2.0,
"dPK1_dF",
),
FiniteStrainTangentOperator::KirchhoffBySpatialIncrement => (
[
("KirchhoffStress", VariableType::Stensor),
(
"SpatialIncrementOfTheDeformationGradient",
VariableType::Tensor,
),
],
3.0,
"dtau_ddF",
),
};
let thermodynamic_forces = if finite_strain {
vec![(stress.0.to_owned(), stress.1)]
} else {
symbols.variables("ThermodynamicForces", true)?
};
let thermodynamic_forces = layout(thermodynamic_forces, dimension, &symbols);
let mut material_properties = Vec::new();
let mut scalars = |names: &[&str]| {
material_properties.extend(names.iter().map(|n| (n.to_string(), VariableType::Scalar)));
};
if symbols.u16("requiresStiffnessTensor")? == 1 {
if symbols.u16("ElasticSymmetryType")? == 0 {
scalars(&["YoungModulus", "PoissonRatio"]);
} else {
scalars(&["YoungModulus1", "YoungModulus2", "YoungModulus3"]);
scalars(&["PoissonRatio12", "PoissonRatio23", "PoissonRatio13"]);
match dimension {
1 => {}
2 => scalars(&["ShearModulus12"]),
_ => scalars(&["ShearModulus12", "ShearModulus23", "ShearModulus13"]),
}
}
}
if symbols.u16("requiresThermalExpansionCoefficientTensor")? == 1 {
match symmetry {
Symmetry::Isotropic => scalars(&["ThermalExpansion"]),
Symmetry::Orthotropic => scalars(&[
"ThermalExpansion1",
"ThermalExpansion2",
"ThermalExpansion3",
]),
}
}
material_properties.extend(symbols.variables("MaterialProperties", false)?);
let material_properties = layout(material_properties, dimension, &symbols);
let internal_state_variables = layout(
symbols.variables("InternalStateVariables", true)?,
dimension,
&symbols,
);
let mut external_state_variables = Vec::new();
if symbols.u16("TemperatureRemovedFromExternalStateVariables")? == 1 {
external_state_variables.push(("Temperature".to_owned(), VariableType::Scalar));
}
external_state_variables.extend(symbols.variables("ExternalStateVariables", true)?);
let external_state_variables = layout(external_state_variables, dimension, &symbols);
let (tangent_operator_blocks, tangent_operator_size) = if finite_strain {
let block = layout(
block.map(|(n, t)| (n.to_owned(), t)).to_vec(),
dimension,
&symbols,
);
let size = block.list[0].size * block.list[1].size;
let [of, with_respect_to] = [0, 1].map(|i| block.list[i].name.clone());
(vec![(of, with_respect_to)], size)
} else {
let n = usize::from(symbols.u16("nTangentOperatorBlocks")?);
let names = symbols.strings("TangentOperatorBlocks", n)?;
let mut size = 0;
let mut blocks = Vec::new();
for [of, with_respect_to] in names.as_chunks::<2>().0 {
let mut block = 1;
for variable in [of, with_respect_to] {
block *= [
&gradients,
&thermodynamic_forces,
&internal_state_variables,
&external_state_variables,
]
.iter()
.flat_map(|v| &v.list)
.find(|v| &v.name == variable)
.expect("MFront names the variables of the tangent operator blocks")
.size;
}
size += block;
blocks.push((of.clone(), with_respect_to.clone()));
}
(blocks, size)
};
let vector = gradients
.list
.iter()
.chain(&thermodynamic_forces.list)
.chain(
internal_state_variables
.list
.iter()
.chain(&external_state_variables.list)
.filter(|v| {
tangent_operator_blocks.iter().any(|(of, with_respect_to)| {
*of == v.name || *with_respect_to == v.name
})
}),
)
.find(|v| v.variable_type == VariableType::Vector);
let rotations = match (symmetry, vector) {
(Symmetry::Isotropic, _) => Rotations::Isotropic,
(Symmetry::Orthotropic, Some(v)) => Rotations::Vector(v.name.clone()),
(Symmetry::Orthotropic, None) => {
let [forces, tangent] = if finite_strain {
[
format!("rotateArrayOfThermodynamicForces_{stress_rotation}"),
format!("rotateArrayOfTangentOperatorBlocks_{tangent_rotation}"),
]
} else {
[
"rotateArrayOfThermodynamicForces".to_owned(),
"rotateArrayOfTangentOperatorBlocks".to_owned(),
]
};
Rotations::Functions(unsafe {
[
symbols.get("rotateArrayOfGradients")?,
symbols.get(&forces)?,
symbols.get(&tangent)?,
]
})
}
};
let parameters = symbols.parameters()?;
unsafe { symbols.set_parameters(¶meters, settings.parameters)? };
if let Some(policy) = settings.out_of_bounds_policy {
unsafe {
symbols.get::<ffi::SetOutOfBoundsPolicyFn>("setOutOfBoundsPolicy")?(policy.code())
};
}
let symbol = format!("{name}_{h}");
let integrate = *unsafe { library.get::<ffi::IntegrateFn>(symbol.as_str()) }
.map_err(|_| Error::MissingSymbol { symbol })?;
Ok(Behaviour {
description: Description {
name: name.to_owned(),
hypothesis,
tfel_version,
source: text("src")?,
author: text("author")?,
date: text("date")?,
description: text("description")?,
validator: text("validator")?,
build_id: text("build_id")?,
unit_system: text("unit_system")?,
behaviour_type,
kinematic,
computes_stored_energy: symbols.u16("ComputesInternalEnergy")? == 1,
computes_dissipated_energy: symbols.u16("ComputesDissipatedEnergy")? == 1,
symmetry,
gradients,
thermodynamic_forces,
material_properties,
internal_state_variables,
external_state_variables,
tangent_operator_blocks,
tangent_operator_size,
parameters,
},
integrate,
finite_strain: finite_strain.then_some([stress_code, tangent_code]),
rotations,
_library: library,
})
}
pub fn rotate(
&self,
what: Rotated,
r: &Rotation,
to: Frame,
values: &mut [f64],
) -> Result<(), Error> {
let d = &self.description;
let [gradients, forces, tangent] = match &self.rotations {
Rotations::Isotropic => {
return Err(Error::NotOrthotropic {
name: d.name.clone(),
});
}
Rotations::Vector(variable) => {
return Err(Error::UnsupportedRotation {
name: d.name.clone(),
variable: variable.clone(),
});
}
Rotations::Functions(functions) => *functions,
};
let (function, array, size, native) = match what {
Rotated::Gradients => (gradients, "gradients", d.gradients.size, Frame::Material),
Rotated::ThermodynamicForces => (
forces,
"thermodynamic forces",
d.thermodynamic_forces.size,
Frame::Global,
),
Rotated::TangentOperator => (
tangent,
"tangent operator",
d.tangent_operator_size,
Frame::Global,
),
};
let points = values.len().checked_div(size).unwrap_or(0);
if points * size != values.len() {
return Err(Error::IncompletePoint {
array,
size,
found: values.len(),
});
}
let m = r.matrix;
let matrix = if to == native {
m.concat()
} else {
(0..9).map(|k| m[k % 3][k / 3]).collect()
};
let values = values.as_mut_ptr();
unsafe { function(values, values, matrix.as_ptr(), points) };
Ok(())
}
pub fn description(&self) -> &Description {
&self.description
}
pub fn integrate(
&self,
d: &mut BehaviourData<'_>,
options: IntegrationOptions,
) -> Result<Status, Error> {
let description = &self.description;
let BehaviourData {
dt,
rdt,
k,
speed_of_sound,
s0,
s1,
} = d;
let code = match options.integration_type {
IntegrationType::PredictionTangentOperator => -3.0,
IntegrationType::PredictionSecantOperator => -2.0,
IntegrationType::PredictionElasticOperator => -1.0,
IntegrationType::IntegrationNoTangentOperator => 0.0,
IntegrationType::IntegrationElasticOperator => 1.0,
IntegrationType::IntegrationSecantOperator => 2.0,
IntegrationType::IntegrationTangentOperator => 3.0,
IntegrationType::IntegrationConsistentTangentOperator => 4.0,
};
let no_operator = code == 0.0 && k.is_empty();
let lengths = [
(
"s0.gradients",
description.gradients.size,
s0.gradients.len(),
),
(
"s1.gradients",
description.gradients.size,
s1.gradients.len(),
),
(
"s0.thermodynamic_forces",
description.thermodynamic_forces.size,
s0.thermodynamic_forces.len(),
),
(
"s1.thermodynamic_forces",
description.thermodynamic_forces.size,
s1.thermodynamic_forces.len(),
),
(
"s0.material_properties",
description.material_properties.size,
s0.material_properties.len(),
),
(
"s1.material_properties",
description.material_properties.size,
s1.material_properties.len(),
),
(
"s0.internal_state_variables",
description.internal_state_variables.size,
s0.internal_state_variables.len(),
),
(
"s1.internal_state_variables",
description.internal_state_variables.size,
s1.internal_state_variables.len(),
),
(
"s0.external_state_variables",
description.external_state_variables.size,
s0.external_state_variables.len(),
),
(
"s1.external_state_variables",
description.external_state_variables.size,
s1.external_state_variables.len(),
),
(
"k",
if no_operator {
0
} else {
description.tangent_operator_size
},
k.len(),
),
];
if let Some(&(array, expected, found)) = lengths.iter().find(|(_, e, f)| e != f) {
return Err(Error::WrongLength {
array,
expected,
found,
});
}
let mut no_tangent = [0.0; 3];
let k: &mut [f64] = if k.is_empty() { &mut no_tangent } else { k };
k[0] = code
+ if options.compute_speed_of_sound {
100.0
} else {
0.0
};
if let Some(finite_strain) = self.finite_strain {
k[1..3].copy_from_slice(&finite_strain);
}
let mut message = [0_u8; ffi::ERROR_MESSAGE_SIZE];
let mut data = ffi::BehaviourData {
error_message: message.as_mut_ptr().cast(),
dt: *dt,
k: k.as_mut_ptr(),
rdt,
speed_of_sound,
s0: ffi::InitialState {
gradients: s0.gradients.as_ptr(),
thermodynamic_forces: s0.thermodynamic_forces.as_ptr(),
mass_density: &s0.mass_density,
material_properties: s0.material_properties.as_ptr(),
internal_state_variables: s0.internal_state_variables.as_ptr(),
stored_energy: &s0.stored_energy,
dissipated_energy: &s0.dissipated_energy,
external_state_variables: s0.external_state_variables.as_ptr(),
},
s1: ffi::State {
gradients: s1.gradients.as_ptr(),
thermodynamic_forces: s1.thermodynamic_forces.as_mut_ptr(),
mass_density: &s1.mass_density,
material_properties: s1.material_properties.as_ptr(),
internal_state_variables: s1.internal_state_variables.as_mut_ptr(),
stored_energy: &mut s1.stored_energy,
dissipated_energy: &mut s1.dissipated_energy,
external_state_variables: s1.external_state_variables.as_ptr(),
},
};
let status = unsafe { (self.integrate)(&mut data) };
match status {
1.. => Ok(Status::Reliable),
0 => Ok(Status::Unreliable),
_ => {
let message = CStr::from_bytes_until_nul(&message)
.map(|m| m.to_string_lossy().into_owned())
.unwrap_or_default();
Err(Error::IntegrationFailed {
message,
time_step_scaling_factor: *rdt,
})
}
}
}
}
fn layout(list: Vec<(String, VariableType)>, dimension: usize, symbols: &Symbols) -> Variables {
let mut offset = 0;
let list = list
.into_iter()
.map(|(name, variable_type)| {
let size = match (variable_type, dimension) {
(VariableType::Scalar, _) => 1,
(VariableType::Vector, d) => d,
(VariableType::Stensor | VariableType::Tensor, 1) => 3,
(VariableType::Stensor, 2) => 4,
(VariableType::Tensor, 2) => 5,
(VariableType::Stensor, _) => 6,
(VariableType::Tensor, _) => 9,
};
let base = name.split_once('[').map_or(name.as_str(), |(base, _)| base);
let [lower, upper, physical_lower, physical_upper] = [
"LowerBound",
"UpperBound",
"LowerPhysicalBound",
"UpperPhysicalBound",
]
.map(|bound| symbols.long_double(&format!("{base}_{bound}")));
let variable = Variable {
variable_type,
offset,
size,
bounds: Bounds { lower, upper },
physical_bounds: Bounds {
lower: physical_lower,
upper: physical_upper,
},
name,
};
offset += size;
variable
})
.collect();
Variables { list, size: offset }
}