use crate::containers::element_field::SubElementField;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::matrix::DofOrdering;
use crate::containers::mesh::{ElementType, SubMesh};
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::models::{CellGeom, Domain, MatrixLayout, Physics, SubModelKind};
use crate::store::{read, Handle};
use serde::{Deserialize, Serialize};
const MATERIAL_COMPONENTS: &[&str] = &["E", "A", "I_y", "I_z", "J", "G", "A_sy", "A_sz"];
const PRIMAL: [&str; 6] = ["u_x", "u_y", "u_z", "r_x", "r_y", "r_z"];
const DUAL: [&str; 6] = ["f_x", "f_y", "f_z", "m_x", "m_y", "m_z"];
#[derive(Clone, Serialize, Deserialize)]
pub struct Frame3d {
pub(crate) fespace: Handle<SubFiniteElementSpace>,
pub(crate) support: Handle<SubMesh>,
}
impl Frame3d {
pub fn new(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
let (submesh, space_dim, et) = {
let s = read(&fespace)?;
(s.submesh(), s.space_dim(), s.element_type()?)
};
if et != ElementType::SEG2 {
return Err(PyrucastError::Message(format!(
"Frame3d: expected SEG2 elements, got {et}"
)));
}
if space_dim != 3 {
return Err(PyrucastError::Message(format!(
"Frame3d: space frame requires a 3-D configuration, got {space_dim}-D"
)));
}
let support = read(&submesh)?.to_poi1()?;
Ok(Self { fespace, support })
}
}
impl SubModelKind for Frame3d {
fn primal_vars(&self) -> Vec<String> {
PRIMAL.iter().map(|s| s.to_string()).collect()
}
fn dual_vars(&self) -> Vec<String> {
DUAL.iter().map(|s| s.to_string()).collect()
}
fn as_domain(&self) -> Option<&dyn Domain> {
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,
symmetric: true,
})
}
fn mass_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
fn geometric_layout(&self) -> Option<MatrixLayout> {
self.stiffness_layout()
}
fn element_matrix(
&self,
geoms: &[CellGeom],
material: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
element_stiffness(
geom,
material.expect("Frame3d requires a material field"),
ke,
)
}
fn element_mass(
&self,
geoms: &[CellGeom],
material: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
element_mass(
geom,
material.expect("Frame3d requires a material field"),
ke,
)
}
fn element_geometric(
&self,
geoms: &[CellGeom],
_material: Option<&SubElementField>,
state: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let stress = state.expect("frame3d geometric stiffness requires the axial force `N`");
element_geometric(geom, stress, ke)
}
fn physics(&self) -> &'static [Physics] {
&[Physics::Mechanical]
}
fn label(&self) -> &'static str {
"Frame3d"
}
fn render(&self, _opts: &DumpOptions) -> String {
let n = read(&self.support).map(|s| s.cell_count()).unwrap_or(0);
format!(
"SubModel<Frame3d>\n primal var(s): u_x, u_y, u_z, r_x, r_y, r_z\n \
dual var(s): f_x, f_y, f_z, m_x, m_y, m_z\n support: {n} node(s)"
)
}
}
impl Domain for Frame3d {
fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn material_components(&self) -> Option<&'static [&'static str]> {
Some(MATERIAL_COMPONENTS)
}
fn optional_material_components(&self) -> &'static [&'static str] {
&["rho"]
}
fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn behavior_output_components(&self) -> Result<Vec<String>> {
Ok(vec![
"N".into(),
"M_y".into(),
"M_z".into(),
"T".into(),
"V_y".into(),
"V_z".into(),
])
}
fn integrate_point(
&self,
geom: &CellGeom,
input: &SubElementField,
_prev: Option<&SubElementField>,
material: Option<&SubElementField>,
g: usize,
_dt: Option<f64>,
out: &mut [f64],
) -> Result<()> {
let mat = material.expect("Frame3d declares a material_fespace ⇒ material is supplied");
let cell = geom.cell;
let v = |c| mat.value(cell, 0, c);
let e = v("E")?;
let gg = v("G")?;
out[0] = e * v("A")? * input.value(cell, g, "eps")?;
out[1] = e * v("I_y")? * input.value(cell, g, "kappa_y")?;
out[2] = e * v("I_z")? * input.value(cell, g, "kappa_z")?;
out[3] = gg * v("J")? * input.value(cell, g, "torsion")?;
out[4] = gg * v("A_sy")? * input.value(cell, g, "gamma_y")?;
out[5] = gg * v("A_sz")? * input.value(cell, g, "gamma_z")?;
Ok(())
}
}
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
[
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
}
fn norm(a: [f64; 3]) -> f64 {
(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]).sqrt()
}
fn normalize(a: [f64; 3]) -> [f64; 3] {
let n = norm(a);
[a[0] / n, a[1] / n, a[2] / n]
}
fn local_axes(d: [f64; 3]) -> [[f64; 3]; 3] {
let x = normalize(d);
let z_ref = if x[2].abs() > 0.999 {
[0.0, 1.0, 0.0]
} else {
[0.0, 0.0, 1.0]
};
let y = normalize(cross(z_ref, x)); let z = cross(x, y); [x, y, z]
}
#[allow(clippy::too_many_arguments)]
fn local_stiffness(
ea: f64,
gj: f64,
e: f64,
iy: f64,
iz: f64,
g: f64,
asy: f64,
asz: f64,
l: f64,
) -> [[f64; 12]; 12] {
let mut k = [[0.0_f64; 12]; 12];
let a = ea / l; let t = gj / l; let phi_y = 12.0 * e * iz / (g * asy * l * l); let phi_z = 12.0 * e * iy / (g * asz * l * l);
let kv1 = 12.0 * e * iz / (l * l * l * (1.0 + phi_y));
let kv2 = 6.0 * e * iz / (l * l * (1.0 + phi_y));
let kv3 = (4.0 + phi_y) * e * iz / (l * (1.0 + phi_y));
let kv4 = (2.0 - phi_y) * e * iz / (l * (1.0 + phi_y));
let kw1 = 12.0 * e * iy / (l * l * l * (1.0 + phi_z));
let kw2 = 6.0 * e * iy / (l * l * (1.0 + phi_z));
let kw3 = (4.0 + phi_z) * e * iy / (l * (1.0 + phi_z));
let kw4 = (2.0 - phi_z) * e * iy / (l * (1.0 + phi_z));
k[0][0] = a;
k[0][6] = -a;
k[6][6] = a;
k[3][3] = t;
k[3][9] = -t;
k[9][9] = t;
k[1][1] = kv1;
k[1][5] = kv2;
k[1][7] = -kv1;
k[1][11] = kv2;
k[5][5] = kv3;
k[5][7] = -kv2;
k[5][11] = kv4;
k[7][7] = kv1;
k[7][11] = -kv2;
k[11][11] = kv3;
k[2][2] = kw1;
k[2][4] = -kw2;
k[2][8] = -kw1;
k[2][10] = -kw2;
k[4][4] = kw3;
k[4][8] = kw2;
k[4][10] = kw4;
k[8][8] = kw1;
k[8][10] = kw2;
k[10][10] = kw3;
for i in 0..12 {
for j in (i + 1)..12 {
k[j][i] = k[i][j];
}
}
k
}
fn rotation(r: &[[f64; 3]; 3]) -> [[f64; 12]; 12] {
let mut t = [[0.0_f64; 12]; 12];
for blk in 0..4 {
let o = blk * 3;
for i in 0..3 {
for j in 0..3 {
t[o + i][o + j] = r[i][j];
}
}
}
t
}
fn matmul(a: &[[f64; 12]; 12], b: &[[f64; 12]; 12]) -> [[f64; 12]; 12] {
let mut out = [[0.0_f64; 12]; 12];
for i in 0..12 {
for j in 0..12 {
let mut acc = 0.0;
for k in 0..12 {
acc += a[i][k] * b[k][j];
}
out[i][j] = acc;
}
}
out
}
fn transpose(a: &[[f64; 12]; 12]) -> [[f64; 12]; 12] {
let mut out = [[0.0_f64; 12]; 12];
for i in 0..12 {
for j in 0..12 {
out[i][j] = a[j][i];
}
}
out
}
pub fn element_stiffness(
geom: &CellGeom,
material: &SubElementField,
ke: &mut [f64],
) -> Result<()> {
let cell = geom.cell;
let xa = geom.node_coord(0)?;
let xb = geom.node_coord(1)?;
let d = [xb[0] - xa[0], xb[1] - xa[1], xb[2] - xa[2]];
let l = norm(d);
let v = |c| material.value(cell, 0, c);
let kl = local_stiffness(
v("E")? * v("A")?,
v("G")? * v("J")?,
v("E")?,
v("I_y")?,
v("I_z")?,
v("G")?,
v("A_sy")?,
v("A_sz")?,
l,
);
let t = rotation(&local_axes(d));
let kg = matmul(&transpose(&t), &matmul(&kl, &t));
for r in 0..12 {
for c in 0..12 {
ke[r * 12 + c] = kg[r][c];
}
}
Ok(())
}
fn local_mass(rho: f64, area: f64, iy: f64, iz: f64, l: f64) -> [[f64; 12]; 12] {
let mut m = [[0.0_f64; 12]; 12];
let inertia = [area, area, area, iy + iz, iy, iz];
for (var, &sec) in inertia.iter().enumerate() {
let ms = rho * sec * l / 6.0;
let (i, j) = (var, var + 6); m[i][i] += 2.0 * ms;
m[j][j] += 2.0 * ms;
m[i][j] += ms;
m[j][i] += ms;
}
m
}
fn local_geometric(n: f64, l: f64) -> [[f64; 12]; 12] {
let mut k = [[0.0_f64; 12]; 12];
let g = n / l;
for &(i, j) in &[(1usize, 7usize), (2, 8)] {
k[i][i] += g;
k[j][j] += g;
k[i][j] -= g;
k[j][i] -= g;
}
k
}
pub fn element_mass(geom: &CellGeom, material: &SubElementField, ke: &mut [f64]) -> Result<()> {
let cell = geom.cell;
let xa = geom.node_coord(0)?;
let xb = geom.node_coord(1)?;
let d = [xb[0] - xa[0], xb[1] - xa[1], xb[2] - xa[2]];
let l = norm(d);
let rho = material.value(cell, 0, "rho").map_err(|_| {
PyrucastError::Message(
"Frame3d mass matrix: material component `rho` (density) is required".into(),
)
})?;
let ml = local_mass(
rho,
material.value(cell, 0, "A")?,
material.value(cell, 0, "I_y")?,
material.value(cell, 0, "I_z")?,
l,
);
let t = rotation(&local_axes(d));
write_12x12(ke, &matmul(&transpose(&t), &matmul(&ml, &t)));
Ok(())
}
pub fn element_geometric(geom: &CellGeom, state: &SubElementField, ke: &mut [f64]) -> Result<()> {
let cell = geom.cell;
let xa = geom.node_coord(0)?;
let xb = geom.node_coord(1)?;
let d = [xb[0] - xa[0], xb[1] - xa[1], xb[2] - xa[2]];
let l = norm(d);
let n = state.value(cell, 0, "N")?;
let kl = local_geometric(n, l);
let t = rotation(&local_axes(d));
write_12x12(ke, &matmul(&transpose(&t), &matmul(&kl, &t)));
Ok(())
}
fn write_12x12(ke: &mut [f64], m: &[[f64; 12]; 12]) {
for (r, row) in m.iter().enumerate() {
for (col, v) in row.iter().enumerate() {
ke[r * 12 + col] += v;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aggregate::Aggregate;
use crate::containers::field::SubField;
use crate::containers::finite_element_space::FiniteElementSpace;
use crate::containers::mesh::{Coords, Mesh, Node, NodeId};
use crate::store::insert;
fn one_beam(bx: f64, by: f64, bz: f64) -> (Frame3d, NodeId, NodeId) {
let coords = insert(Coords::new(3).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[bx, by, bz]).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 frame = Frame3d::new(fes.get(0).unwrap()).unwrap();
(frame, a.id(), b.id())
}
fn material(frame: &Frame3d) -> Handle<SubElementField> {
let mut m = SubElementField::new(
frame.fespace.clone(),
MATERIAL_COMPONENTS.iter().map(|s| s.to_string()).collect(),
)
.unwrap();
for (c, v) in [
("E", 2.0),
("A", 3.0),
("I_y", 1.5),
("I_z", 2.5),
("J", 1.2),
("G", 0.8),
("A_sy", 4.0),
("A_sz", 5.0),
] {
m.set_uniform(c, v).unwrap();
}
insert(m)
}
#[test]
fn horizontal_beam_axial_torsion_decoupled() {
let l = 2.0;
let (frame, a, b) = one_beam(l, 0.0, 0.0);
let mat = material(&frame);
let blocks = frame.build_stiffness_blocks(Some(&mat)).unwrap();
let k = &blocks[0];
let tol = 1e-9;
assert!((k.get(a, "f_x", a, "u_x") - 6.0 / l).abs() < tol); assert!((k.get(a, "f_x", b, "u_x") + 6.0 / l).abs() < tol);
assert!((k.get(a, "m_x", a, "r_x") - 0.96 / l).abs() < tol); assert!(k.get(a, "f_x", a, "u_y").abs() < tol);
assert!(k.get(a, "f_x", a, "r_x").abs() < tol);
assert!(k.get(a, "f_y", a, "u_z").abs() < tol);
assert!(k.get(a, "f_y", a, "r_y").abs() < tol);
}
#[test]
fn vertical_beam_axial_is_along_y() {
let l = 2.0;
let (frame, a, _b) = one_beam(0.0, l, 0.0);
let mat = material(&frame);
let blocks = frame.build_stiffness_blocks(Some(&mat)).unwrap();
let k = &blocks[0];
assert!((k.get(a, "f_y", a, "u_y") - 6.0 / l).abs() < 1e-9); assert!(k.get(a, "f_y", a, "u_x").abs() < 1e-9);
}
}