use crate::containers::element_field::SubElementField;
use crate::containers::field::ABSENT_COMPONENT;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::matrix::DofOrdering;
use crate::containers::matrix::Symmetry;
use crate::containers::mesh::SubMesh;
use crate::containers::model::SubModel;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::models::owned_components;
use crate::models::tensor::{dual_name, primal_name};
use crate::models::ZoneLayout;
use crate::models::{Behavior, CellGeom, Domain, MatrixLayout, Physics, SubModelKind};
use crate::models::{ElementLayout, MatrixKind};
use serde::{Deserialize, Serialize};
pub(crate) const AXES: [&str; 3] = ["x", "y", "z"];
const MATERIAL_COMPONENTS: &[&str] = &["E", "A"];
fn strain_names(space_dim: usize) -> Vec<String> {
let mut names = Vec::new();
for i in 0..space_dim {
for j in i..space_dim {
names.push(format!("eps_{}{}", AXES[i], AXES[j]));
}
}
names
}
#[derive(Clone, Serialize, Deserialize)]
pub struct Truss {
pub(crate) fespace: Handle<SubFiniteElementSpace>,
pub(crate) support: Handle<SubMesh>,
pub(crate) space_dim: usize,
}
impl Truss {
pub fn new(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
let (submesh, space_dim, axisymmetric) = {
let s = fespace.read();
(s.submesh(), s.space_dim(), s.is_axisymmetric())
};
if axisymmetric {
return Err(PyrucastError::Message(
"Truss: axisymmetric geometries are not supported — a segment in a \
meridian plane is a shell of revolution, not a bar"
.into(),
));
}
let support = submesh.read().to_poi1()?;
Ok(Self {
fespace,
support,
space_dim,
})
}
}
impl SubModelKind for Truss {
fn primal_vars(&self) -> Vec<String> {
(0..self.space_dim).map(primal_name).collect()
}
fn dual_vars(&self) -> Vec<String> {
(0..self.space_dim).map(dual_name).collect()
}
fn as_domain(&self) -> Option<&dyn Domain> {
Some(self)
}
fn as_behavior(&self) -> Option<&dyn Behavior> {
Some(self)
}
fn stiffness_layout(&self) -> Option<MatrixLayout> {
Some(MatrixLayout {
fespaces: vec![self.fespace.clone()],
support: self.support.clone(),
dual_vars: self.dual_vars(),
primal_vars: self.primal_vars(),
ordering: DofOrdering::NodesThenVars,
symmetry: Symmetry::Full,
})
}
fn mass_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
fn geometric_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
fn internal_force_reads(&self) -> Vec<String> {
vec!["n".to_string()]
}
fn internal_force_element(
&self,
geoms: &[CellGeom],
stress: &SubElementField,
lay: &[u32],
_material: &SubElementField,
_mat: &[u32],
fe: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let d = self.space_dim;
let mut c = [0.0_f64; 3];
cell_cosine(geom, d, &mut c)?;
let n = stress.row(geom.cell, 0)[lay[0] as usize];
for a in 0..d {
fe[a] = -n * c[a]; fe[d + a] = n * c[a]; }
Ok(())
}
fn physics(&self) -> &'static [Physics] {
&[Physics::Mechanical]
}
fn label(&self) -> &'static str {
"Truss"
}
fn render(&self, _opts: &DumpOptions) -> String {
let primal = self.primal_vars().join(", ");
let dual = self.dual_vars().join(", ");
let n = self.support.read().cell_count();
format!(
"SubModel<Truss>\n primal var(s): {primal}\n dual var(s): {dual}\n \
support: {n} node(s)"
)
}
}
impl Domain for Truss {
fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn material_components(&self) -> Vec<String> {
owned_components(MATERIAL_COMPONENTS)
}
fn optional_material_components(&self) -> &'static [&'static str] {
&["rho"]
}
fn element_state_reads(&self, kind: MatrixKind) -> Vec<String> {
match kind {
MatrixKind::Geometric => vec!["n".to_string()],
_ => Vec::new(),
}
}
fn element_matrix(
&self,
geoms: &[CellGeom],
material: &SubElementField,
lay: &ElementLayout,
ke: &mut [f64],
) -> Result<()> {
element_stiffness(&geoms[0], material, lay, ke)
}
fn element_mass(
&self,
geoms: &[CellGeom],
material: &SubElementField,
lay: &ElementLayout,
ke: &mut [f64],
) -> Result<()> {
element_mass(&geoms[0], material, lay, ke)
}
fn element_geometric(
&self,
geoms: &[CellGeom],
_material: &SubElementField,
lay: &ElementLayout,
state: &SubElementField,
ke: &mut [f64],
) -> Result<()> {
element_geometric(&geoms[0], state, lay, ke)
}
}
impl Behavior for Truss {
fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn behavior_output_components(&self) -> Vec<String> {
vec!["n".to_string()]
}
fn deformation_reads(&self) -> Vec<String> {
strain_names(self.space_dim)
}
fn integrate_point(
&self,
geom: &CellGeom,
_g: usize,
lay: &ZoneLayout,
deformation: &[f64],
_prev: &[f64],
material: &[f64],
_dt: f64,
out: &mut [f64],
) -> Result<()> {
let d = self.space_dim;
let mut c = [0.0_f64; 3];
cell_cosine(geom, d, &mut c)?;
let comp_index = |i: usize, j: usize| -> usize {
let (i, j) = if i <= j { (i, j) } else { (j, i) };
(0..i).map(|r| d - r).sum::<usize>() + (j - i)
};
let (e, a) = (
material[lay.material[0] as usize],
material[lay.material[1] as usize],
);
let mut eps_axial = 0.0;
for i in 0..d {
for j in 0..d {
let eps_ij = deformation[lay.deformation[comp_index(i, j)] as usize];
eps_axial += c[i] * eps_ij * c[j];
}
}
out[0] = e * a * eps_axial;
Ok(())
}
}
fn cell_cosine(geom: &CellGeom, space_dim: usize, out: &mut [f64; 3]) -> Result<f64> {
let xa = geom.node_coord(0);
let xb = geom.node_coord(1);
for a in 0..space_dim {
out[a] = xb[a] - xa[a];
}
let len = out[..space_dim].iter().map(|v| v * v).sum::<f64>().sqrt();
if len <= f64::EPSILON {
return Err(crate::error::PyrucastError::Message(format!(
"Truss: cell {} has zero length",
geom.cell
)));
}
for v in &mut out[..space_dim] {
*v /= len;
}
Ok(len)
}
pub fn element_stiffness(
geom: &CellGeom,
material: &SubElementField,
lay: &ElementLayout,
ke: &mut [f64],
) -> Result<()> {
let sd = geom.space_dim;
let side = 2 * sd;
let mut c = [0.0_f64; 3];
let len = cell_cosine(geom, sd, &mut c)?;
let row = material.row(geom.cell, 0);
let k_ax = row[lay.material[0] as usize] * row[lay.material[1] as usize] / len;
for ii in 0..2 {
for jj in 0..2 {
let sign = if ii == jj { 1.0 } else { -1.0 };
for a in 0..sd {
for b in 0..sd {
ke[(ii * sd + a) * side + (jj * sd + b)] = sign * k_ax * c[a] * c[b];
}
}
}
}
Ok(())
}
pub fn element_mass(
geom: &CellGeom,
material: &SubElementField,
lay: &ElementLayout,
ke: &mut [f64],
) -> Result<()> {
let sd = geom.space_dim;
let side = 2 * sd;
let mut c = [0.0_f64; 3];
let len = cell_cosine(geom, sd, &mut c)?;
let row = material.row(geom.cell, 0);
let rho = match lay.optional_material[0] {
ABSENT_COMPONENT => {
return Err(crate::error::PyrucastError::Message(
"Truss mass matrix: material component `rho` (density) is required".into(),
))
}
i => row[i as usize],
};
let a = row[lay.material[1] as usize];
let m = rho * a * len / 6.0;
for ii in 0..2 {
for jj in 0..2 {
let coef = m * if ii == jj { 2.0 } else { 1.0 };
for aa in 0..sd {
ke[(ii * sd + aa) * side + (jj * sd + aa)] += coef;
}
}
}
Ok(())
}
pub fn element_geometric(
geom: &CellGeom,
state: &SubElementField,
lay: &ElementLayout,
ke: &mut [f64],
) -> Result<()> {
let sd = geom.space_dim;
let side = 2 * sd;
let mut c = [0.0_f64; 3];
let len = cell_cosine(geom, sd, &mut c)?;
let k = state.row(geom.cell, 0)[lay.state[0] as usize] / len;
for ii in 0..2 {
for jj in 0..2 {
let sign = if ii == jj { 1.0 } else { -1.0 };
for a in 0..sd {
for b in 0..sd {
let p = (if a == b { 1.0 } else { 0.0 }) - c[a] * c[b];
ke[(ii * sd + a) * side + (jj * sd + b)] += sign * k * p;
}
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn rest<B: Behavior>(b: &B, mat: &Handle<SubElementField>) -> Handle<SubElementField> {
Handle::new(b.initial_state(&mat.read()).unwrap())
}
use crate::aggregate::Aggregate;
use crate::atoms::{ElementType, Node, NodeId};
use crate::containers::field::SubField;
use crate::containers::finite_element_space::FiniteElementSpace;
use crate::containers::mesh::Mesh;
use crate::coords::Coords;
use crate::handle::Handle;
fn inclined_bar(e: f64, area: f64, dx: f64, dy: f64) -> (Truss, NodeId, NodeId, f64, [f64; 2]) {
let coords = Handle::new(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[dx, dy]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
let truss = Truss::new(fes.get(0).unwrap()).unwrap();
let len = (dx * dx + dy * dy).sqrt();
let _ = (e, area);
(truss, a.id(), b.id(), len, [dx / len, dy / len])
}
fn material(truss: &Truss, e: f64, area: f64) -> Handle<SubElementField> {
let mut m =
SubElementField::new(truss.fespace.clone(), vec!["E".into(), "A".into()]).unwrap();
m.set_uniform("E", e).unwrap();
m.set_uniform("A", area).unwrap();
Handle::new(m)
}
#[test]
fn vars_follow_space_dim() {
let (truss, ..) = inclined_bar(1.0, 1.0, 3.0, 4.0);
assert_eq!(truss.primal_vars(), vec!["u_x", "u_y"]);
assert_eq!(truss.dual_vars(), vec!["f_x", "f_y"]);
}
#[test]
fn inclined_bar_stiffness_matches_direction_cosines() {
let (e, area) = (210.0, 2.0);
let (truss, a, b, len, c) = inclined_bar(e, area, 3.0, 4.0);
let mat = material(&truss, e, area);
let blocks = truss.build_stiffness_blocks(&mat).unwrap();
let k = &blocks[0];
let k_ax = e * area / len;
let tol = 1e-9;
assert!((k.get(a, "f_x", a, "u_x") - k_ax * c[0] * c[0]).abs() < tol);
assert!((k.get(a, "f_x", a, "u_y") - k_ax * c[0] * c[1]).abs() < tol);
assert!((k.get(a, "f_y", a, "u_y") - k_ax * c[1] * c[1]).abs() < tol);
assert!((k.get(a, "f_x", b, "u_x") + k_ax * c[0] * c[0]).abs() < tol);
assert!((k.get(b, "f_y", a, "u_x") + k_ax * c[1] * c[0]).abs() < tol);
assert!((k.get(b, "f_y", b, "u_y") - k_ax * c[1] * c[1]).abs() < tol);
}
#[test]
fn integrate_behavior_returns_axial_force() {
let (e, area) = (100.0, 3.0);
let (truss, _a, _b, _len, c) = inclined_bar(e, area, 3.0, 4.0);
let mat = material(&truss, e, area);
let eps0 = 0.01;
let mut strain = SubElementField::new(truss.fespace.clone(), strain_names(2)).unwrap();
strain.set_uniform("eps_xx", eps0 * c[0] * c[0]).unwrap();
strain.set_uniform("eps_xy", eps0 * c[0] * c[1]).unwrap();
strain.set_uniform("eps_yy", eps0 * c[1] * c[1]).unwrap();
let strain = Handle::new(strain);
let out = truss
.integrate_behavior(&strain, &rest(&truss, &mat), &mat, 0.0)
.unwrap();
assert_eq!(out.components(), &["n".to_string()]);
let expected = e * area * eps0;
for g in 0..out.gauss_count() {
assert!((out.value(0, g, "n").unwrap() - expected).abs() < 1e-9);
}
}
}
crate::physics_operator! {
pub fn truss(fes) via SubModel::truss;
python: "`model.truss(fespace)` — truss / bar (axial-force) model spanning\n**every** subspace of `fespace` (SEG2 elements). DOFs are the vector\ndisplacement `u_x, u_y(, u_z)`; the orientation is taken from the node\ncoordinates. Material (`E`, `A`) is supplied at assembly time."
}