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, Debug, PartialEq, Eq)]
pub struct Variable {
pub name: String,
pub variable_type: VariableType,
pub offset: usize,
pub size: usize,
}
#[derive(Clone, Debug, PartialEq, Eq, 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)]
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, Copy, Debug, PartialEq)]
pub struct TimeStep {
pub dt: f64,
pub max_scaling_factor: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Description {
pub name: String,
pub hypothesis: Hypothesis,
pub tfel_version: String,
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, PartialEq, Eq)]
pub enum TangentOperator {
Elastic,
Secant,
Tangent,
ConsistentTangent,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct InitialState<'a> {
pub gradients: &'a [f64],
pub thermodynamic_forces: &'a [f64],
pub material_properties: &'a [f64],
pub internal_state_variables: &'a [f64],
pub external_state_variables: &'a [f64],
pub stored_energy: f64,
pub dissipated_energy: f64,
}
#[derive(Debug, Default)]
pub struct FinalState<'a> {
pub gradients: &'a [f64],
pub thermodynamic_forces: &'a mut [f64],
pub material_properties: &'a [f64],
pub internal_state_variables: &'a mut [f64],
pub external_state_variables: &'a [f64],
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Integration {
pub time_step_scaling_factor: f64,
pub stored_energy: f64,
pub dissipated_energy: f64,
}
#[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 code = symbols.u16("BehaviourType")?;
if code > 2 {
return Err(Error::UnsupportedBehaviourType {
name: name.to_owned(),
code,
});
}
let finite_strain = code == 2;
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 symmetry = match symbols.u16("SymmetryType")? {
0 => Symmetry::Isotropic,
_ => Symmetry::Orthotropic,
};
let gradients = layout(symbols.variables("Gradients", true)?, dimension);
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);
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);
let internal_state_variables = layout(
symbols.variables("InternalStateVariables", true)?,
dimension,
);
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);
let (tangent_operator_blocks, tangent_operator_size) = if finite_strain {
let block = layout(block.map(|(n, t)| (n.to_owned(), t)).to_vec(), dimension);
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,
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,
step: TimeStep,
s0: &InitialState<'_>,
s1: &mut FinalState<'_>,
tangent: Option<(TangentOperator, &mut [f64])>,
) -> Result<Integration, Error> {
let d = &self.description;
let tangent_length = tangent.as_ref().map(|(_, k)| k.len());
let lengths = [
("s0.gradients", d.gradients.size, s0.gradients.len()),
("s1.gradients", d.gradients.size, s1.gradients.len()),
(
"s0.thermodynamic_forces",
d.thermodynamic_forces.size,
s0.thermodynamic_forces.len(),
),
(
"s1.thermodynamic_forces",
d.thermodynamic_forces.size,
s1.thermodynamic_forces.len(),
),
(
"s0.material_properties",
d.material_properties.size,
s0.material_properties.len(),
),
(
"s1.material_properties",
d.material_properties.size,
s1.material_properties.len(),
),
(
"s0.internal_state_variables",
d.internal_state_variables.size,
s0.internal_state_variables.len(),
),
(
"s1.internal_state_variables",
d.internal_state_variables.size,
s1.internal_state_variables.len(),
),
(
"s0.external_state_variables",
d.external_state_variables.size,
s0.external_state_variables.len(),
),
(
"s1.external_state_variables",
d.external_state_variables.size,
s1.external_state_variables.len(),
),
(
"tangent",
d.tangent_operator_size,
tangent_length.unwrap_or(d.tangent_operator_size),
),
];
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 = match tangent {
Some((operator, k)) if !k.is_empty() => {
k[0] = match operator {
TangentOperator::Elastic => 1.0,
TangentOperator::Secant => 2.0,
TangentOperator::Tangent => 3.0,
TangentOperator::ConsistentTangent => 4.0,
};
k
}
_ => &mut no_tangent[..],
};
if let Some(options) = self.finite_strain {
k[1..3].copy_from_slice(&options);
}
let mut stored_energy = s0.stored_energy;
let mut dissipated_energy = s0.dissipated_energy;
let mass_density = 0.0;
let mut speed_of_sound = 0.0;
let mut rdt = step.max_scaling_factor;
let mut message = [0_u8; ffi::ERROR_MESSAGE_SIZE];
let mut data = ffi::BehaviourData {
error_message: message.as_mut_ptr().cast(),
dt: step.dt,
k: k.as_mut_ptr(),
rdt: &mut rdt,
speed_of_sound: &mut speed_of_sound,
s0: ffi::InitialState {
gradients: s0.gradients.as_ptr(),
thermodynamic_forces: s0.thermodynamic_forces.as_ptr(),
mass_density: &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: &mass_density,
material_properties: s1.material_properties.as_ptr(),
internal_state_variables: s1.internal_state_variables.as_mut_ptr(),
stored_energy: &mut stored_energy,
dissipated_energy: &mut dissipated_energy,
external_state_variables: s1.external_state_variables.as_ptr(),
},
};
let status = unsafe { (self.integrate)(&mut data) };
if status < 0 {
let message = CStr::from_bytes_until_nul(&message)
.map(|m| m.to_string_lossy().into_owned())
.unwrap_or_default();
return Err(Error::IntegrationFailed {
message,
time_step_scaling_factor: rdt,
});
}
Ok(Integration {
time_step_scaling_factor: rdt,
stored_energy,
dissipated_energy,
})
}
}
fn layout(list: Vec<(String, VariableType)>, dimension: usize) -> 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 variable = Variable {
name,
variable_type,
offset,
size,
};
offset += size;
variable
})
.collect();
Variables { list, size: offset }
}