use crate::atoms::NodeId;
use crate::containers::element_field::SubElementField;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::matrix::{DofOrdering, SubMatrix};
use crate::containers::mesh::{Mesh, SubMesh};
use crate::containers::node_field::SubNodeField;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::store::{read, Handle};
use serde::{Deserialize, Serialize};
pub mod contact;
pub mod convection;
pub mod dirichlet;
pub mod elasticity;
pub mod embedded;
pub mod frame;
pub mod frame3d;
pub mod heat_conduction;
pub mod kernel;
pub mod mazars;
pub mod mpc;
pub mod plasticity;
pub mod timoshenko;
pub mod truss;
pub use kernel::CellGeom;
const VOIGT_AXES: [&str; 3] = ["x", "y", "z"];
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MatrixKind {
#[default]
Stiffness,
Mass,
Geometric,
Tangent,
}
impl MatrixKind {
pub const COUNT: usize = 4;
pub const fn index(self) -> usize {
self as usize
}
}
pub struct MatrixLayout {
pub fespaces: Vec<Handle<SubFiniteElementSpace>>,
pub support: Handle<SubMesh>,
pub dual_vars: Vec<String>,
pub primal_vars: Vec<String>,
pub ordering: DofOrdering,
pub symmetric: bool,
}
pub enum Contribution {
Computed(MatrixLayout),
Literal(Vec<SubMatrix>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Physics {
Mechanical,
Thermal,
Constraint,
Other,
}
impl Physics {
pub fn from_tag(tag: &str) -> Option<Self> {
match tag {
"mechanical" => Some(Self::Mechanical),
"thermal" => Some(Self::Thermal),
"constraint" => Some(Self::Constraint),
"other" => Some(Self::Other),
_ => None,
}
}
pub fn to_tag(self) -> &'static str {
match self {
Self::Mechanical => "mechanical",
Self::Thermal => "thermal",
Self::Constraint => "constraint",
Self::Other => "other",
}
}
}
impl std::fmt::Display for Physics {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.to_tag())
}
}
pub trait SubModelKind: Sync {
fn primal_vars(&self) -> Vec<String>;
fn dual_vars(&self) -> Vec<String>;
fn physics(&self) -> &'static [Physics];
fn as_domain(&self) -> Option<&dyn Domain> {
None
}
fn as_constraint(&self) -> Option<&dyn Constraint> {
None
}
fn element_matrix(
&self,
_geoms: &[CellGeom],
_material: Option<&SubElementField>,
_ke: &mut [f64],
) -> Result<()> {
Err(PyrucastError::Message(format!(
"{}: no element kernel — element_matrix is undefined",
self.label()
)))
}
fn element_mass(
&self,
_geoms: &[CellGeom],
_material: Option<&SubElementField>,
_ke: &mut [f64],
) -> Result<()> {
Err(PyrucastError::Message(format!(
"{}: no mass kernel — element_mass is undefined",
self.label()
)))
}
fn element_geometric(
&self,
_geoms: &[CellGeom],
_material: Option<&SubElementField>,
_state: Option<&SubElementField>,
_ke: &mut [f64],
) -> Result<()> {
Err(PyrucastError::Message(format!(
"{}: no geometric-stiffness kernel — element_geometric is undefined",
self.label()
)))
}
fn element_tangent(
&self,
_geoms: &[CellGeom],
_material: Option<&SubElementField>,
_state: Option<&SubElementField>,
_ke: &mut [f64],
) -> Result<()> {
Err(PyrucastError::Message(format!(
"{}: no tangent kernel — element_tangent is undefined",
self.label()
)))
}
fn matrix_element(
&self,
kind: MatrixKind,
geoms: &[CellGeom],
material: Option<&SubElementField>,
state: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
match kind {
MatrixKind::Stiffness => self.element_matrix(geoms, material, ke),
MatrixKind::Mass => self.element_mass(geoms, material, ke),
MatrixKind::Geometric => self.element_geometric(geoms, material, state, ke),
MatrixKind::Tangent => self.element_tangent(geoms, material, state, ke),
}
}
fn contributions(
&self,
kind: MatrixKind,
material: Option<&Handle<SubElementField>>,
) -> Result<Vec<Contribution>> {
Ok(match self.matrix_layout(kind) {
Some(layout) => vec![Contribution::Computed(layout)],
None if kind == MatrixKind::Stiffness => {
vec![Contribution::Literal(
self.build_stiffness_blocks(material)?,
)]
}
None => Vec::new(),
})
}
fn build_stiffness_blocks(
&self,
material: Option<&Handle<SubElementField>>,
) -> Result<Vec<SubMatrix>> {
let Some(layout) = self.stiffness_layout() else {
return Err(PyrucastError::Message(format!(
"{}: build_stiffness_blocks has no default without a \
stiffness_layout — override it (e.g. a constraint such as \
Dirichlet, or a multi-block physics)",
self.label()
)));
};
let block = kernel::assemble_block(
&layout.fespaces,
&layout.support,
&layout.support,
layout.dual_vars,
layout.primal_vars,
layout.ordering,
layout.symmetric,
material,
None,
|geoms, m, _state, ke| self.element_matrix(geoms, m, ke),
)?;
Ok(vec![block])
}
fn stiffness_layout(&self) -> Option<MatrixLayout> {
None
}
fn mass_layout(&self) -> Option<MatrixLayout> {
None
}
fn geometric_layout(&self) -> Option<MatrixLayout> {
None
}
fn tangent_layout(&self) -> Option<MatrixLayout> {
None
}
fn matrix_layout(&self, kind: MatrixKind) -> Option<MatrixLayout> {
match kind {
MatrixKind::Stiffness => self.stiffness_layout(),
MatrixKind::Mass => self.mass_layout(),
MatrixKind::Geometric => self.geometric_layout(),
MatrixKind::Tangent => self.tangent_layout(),
}
}
fn internal_force_element(
&self,
geoms: &[CellGeom],
stress: &SubElementField,
fe: &mut [f64],
) -> Result<()> {
continuum_internal_force_element(geoms, stress, fe)
}
fn build_internal_forces(&self, stress: &Handle<SubElementField>) -> Result<SubNodeField> {
let Some(layout) = self.stiffness_layout() else {
return Err(PyrucastError::Message(format!(
"{}: build_internal_forces has no default without a stiffness_layout \
(e.g. a constraint such as Dirichlet)",
self.label()
)));
};
let stress_guard = read(stress)?;
kernel::scatter_to_nodes(
&layout.fespaces,
&layout.support,
layout.dual_vars,
|geoms, fe| self.internal_force_element(geoms, &stress_guard, fe),
)
}
fn label(&self) -> &'static str;
fn display(&self) -> String {
format!("SubModel<{}>", self.label())
}
fn render(&self, opts: &DumpOptions) -> String;
}
pub trait Constraint {
fn multiplier_mesh(&self) -> &Mesh;
fn relations(&self) -> Result<Vec<Relation>>;
}
#[derive(Clone, Debug)]
pub struct ConstraintTerm {
pub node: NodeId,
pub variable: String,
pub target_dual: String,
pub coefficient: f64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum RelationSense {
#[default]
Equality,
GreaterEqual,
LessEqual,
}
impl RelationSense {
pub fn parse(sense: Option<&str>) -> Result<Self> {
match sense {
None | Some("=") | Some("==") => Ok(Self::Equality),
Some(">=") | Some("≥") => Ok(Self::GreaterEqual),
Some("<=") | Some("≤") => Ok(Self::LessEqual),
Some(other) => Err(PyrucastError::Message(format!(
"unknown relation sense '{other}' (expected '=', '>=' or '<=')"
))),
}
}
}
impl std::fmt::Display for RelationSense {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Equality => "=",
Self::GreaterEqual => ">=",
Self::LessEqual => "<=",
})
}
}
#[derive(Clone, Debug)]
pub struct Relation {
pub multiplier_node: NodeId,
pub imposed_value: String,
pub terms: Vec<ConstraintTerm>,
pub sense: RelationSense,
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn constraint_block_pair(
multiplier_sm: &Handle<SubMesh>,
constrained_sm: &Handle<SubMesh>,
variable: &str,
target_dual: &str,
multiplier: &str,
imposed_value: &str,
coefficient: f64,
) -> Result<(SubMatrix, SubMatrix)> {
let mult_nodes: Vec<NodeId> = read(multiplier_sm)?.connectivity().to_vec();
let cons_nodes: Vec<NodeId> = read(constrained_sm)?.connectivity().to_vec();
let mut c = SubMatrix::new(
multiplier_sm.clone(),
constrained_sm.clone(),
vec![imposed_value.to_string()],
vec![variable.to_string()],
DofOrdering::NodesThenVars,
false,
)?;
let mut ct = SubMatrix::new(
constrained_sm.clone(),
multiplier_sm.clone(),
vec![target_dual.to_string()],
vec![multiplier.to_string()],
DofOrdering::NodesThenVars,
false,
)?;
for (cons, mult) in cons_nodes.iter().zip(mult_nodes.iter()) {
c.add_entry(*mult, imposed_value, *cons, variable, coefficient)?;
ct.add_entry(*cons, target_dual, *mult, multiplier, coefficient)?;
}
Ok((c, ct))
}
pub trait Domain: Sync {
fn material_fespace(&self) -> Handle<SubFiniteElementSpace>;
fn material_components(&self) -> Option<&'static [&'static str]> {
None
}
fn optional_material_components(&self) -> &'static [&'static str] {
&[]
}
fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace>;
fn behavior_output_components(&self) -> Result<Vec<String>>;
#[allow(clippy::too_many_arguments)]
fn integrate_point(
&self,
geom: &CellGeom,
deformation: &SubElementField,
prev: Option<&SubElementField>,
material: Option<&SubElementField>,
g: usize,
dt: Option<f64>,
out: &mut [f64],
) -> Result<()>;
fn integrate_behavior(
&self,
deformation: &Handle<SubElementField>,
prev: Option<&Handle<SubElementField>>,
material: Option<&Handle<SubElementField>>,
dt: Option<f64>,
) -> Result<SubElementField> {
let fespace = self.behavior_fespace();
let out_components = self.behavior_output_components()?;
let prev_guard = prev.map(read).transpose()?;
let prev_ref = prev_guard.as_deref();
kernel::element_pointwise(
&fespace,
deformation,
material,
out_components,
|geom, def, mat, g, out| self.integrate_point(geom, def, prev_ref, mat, g, dt, out),
)
}
}
pub(crate) fn continuum_internal_force_element(
geoms: &[CellGeom],
stress: &SubElementField,
fe: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let d = geom.space_dim;
let n_nodes = geom.n_nodes;
for g in 0..geom.n_gauss {
let dn = geom.dn_dx(g)?; let w = geom.det_j_w(g)?;
let sig = voigt_stress_matrix(stress, geom.cell, g, d)?; let hoop = if geom.axisymmetric {
Some((
geom.n_at_g(g)?,
stress.value(geom.cell, g, "sigma_zz")? / geom.radius(g)?,
))
} else {
None
};
for i in 0..n_nodes {
for a in 0..d {
let mut s = 0.0;
for b in 0..d {
s += dn[i * d + b] * sig[a * d + b];
}
fe[i * d + a] += s * w;
}
if let Some((n, s_hoop)) = hoop {
fe[i * d] += n[i] * s_hoop * w;
}
}
}
Ok(())
}
pub(crate) fn voigt_stress_matrix(
stress: &SubElementField,
cell: usize,
g: usize,
d: usize,
) -> Result<Vec<f64>> {
let mut sig = vec![0.0_f64; d * d];
for i in 0..d {
for j in i..d {
let name = format!("sigma_{}{}", VOIGT_AXES[i], VOIGT_AXES[j]);
let v = stress.value(cell, g, &name)?;
sig[i * d + j] = v;
sig[j * d + i] = v; }
}
Ok(sig)
}