use core::ffi::{c_int, CStr};
use std::path::Path;
use libloading::Library;
use crate::symbols::Symbols;
use crate::{ffi, Error, Hypothesis};
#[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)]
pub struct Behaviour {
description: Description,
integrate: ffi::IntegrateFn,
finite_strain: Option<[f64; 2]>,
_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 {
let kinematic = symbols.u16("BehaviourKinematic")?;
if kinematic != 3 {
return Err(Error::UnsupportedKinematic {
name: name.to_owned(),
kinematic,
});
}
} else if 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 thermodynamic_forces = match settings.stress_measure {
StressMeasure::SecondPiolaKirchhoff if finite_strain => {
vec![(
"SecondPiolaKirchhoffStress".to_owned(),
VariableType::Stensor,
)]
}
StressMeasure::FirstPiolaKirchhoff if finite_strain => {
vec![("FirstPiolaKirchhoffStress".to_owned(), VariableType::Tensor)]
}
_ => 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 (of, of_type, with_respect_to, with_respect_to_type) =
match settings.finite_strain_tangent_operator {
FiniteStrainTangentOperator::CauchyByDeformationGradient => (
"Stress",
VariableType::Stensor,
"DeformationGradient",
VariableType::Tensor,
),
FiniteStrainTangentOperator::SecondPiolaKirchhoffByGreenLagrange => (
"SecondPiolaKirchhoffStress",
VariableType::Stensor,
"GreenLagrangeStrain",
VariableType::Stensor,
),
FiniteStrainTangentOperator::FirstPiolaKirchhoffByDeformationGradient => (
"FirstPiolaKirchhoffStress",
VariableType::Tensor,
"DeformationGradient",
VariableType::Tensor,
),
FiniteStrainTangentOperator::KirchhoffBySpatialIncrement => (
"KirchhoffStress",
VariableType::Stensor,
"SpatialIncrementOfTheDeformationGradient",
VariableType::Tensor,
),
};
let block = layout(
vec![
(of.to_owned(), of_type),
(with_respect_to.to_owned(), with_respect_to_type),
],
dimension,
);
let size = block.list[0].size * block.list[1].size;
(vec![(of.to_owned(), with_respect_to.to_owned())], 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)
.ok_or_else(|| Error::InvalidTangentOperatorBlock {
variable: variable.clone(),
})?
.size;
}
size += block;
blocks.push((of.clone(), with_respect_to.clone()));
}
(blocks, size)
};
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([
match settings.stress_measure {
StressMeasure::Cauchy => 0.0,
StressMeasure::SecondPiolaKirchhoff => 1.0,
StressMeasure::FirstPiolaKirchhoff => 2.0,
},
match settings.finite_strain_tangent_operator {
FiniteStrainTangentOperator::CauchyByDeformationGradient => 0.0,
FiniteStrainTangentOperator::SecondPiolaKirchhoffByGreenLagrange => 1.0,
FiniteStrainTangentOperator::FirstPiolaKirchhoffByDeformationGradient => 2.0,
FiniteStrainTangentOperator::KirchhoffBySpatialIncrement => 3.0,
},
]),
_library: library,
})
}
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 }
}