use crate::aggregate::Aggregate;
use crate::containers::element_field::{ElementField, SubElementField};
use crate::containers::field::{Field, SubField};
use crate::containers::finite_element_space::{FiniteElementSpace, SubFiniteElementSpace};
use crate::containers::node_field::{NodeField, NodeFieldView};
use crate::coords::Coords;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
const COMPONENTS_1D: &[&str] = &["kappa", "gamma"];
const COMPONENTS_2D: &[&str] = &["eps", "kappa", "gamma"];
const COMPONENTS_3D: &[&str] = &["eps", "kappa_y", "kappa_z", "torsion", "gamma_y", "gamma_z"];
const DOFS_1D: &[&str] = &["w", "theta"];
const DOFS_2D: &[&str] = &["u_x", "u_y", "r_z"];
const DOFS_3D: &[&str] = &["u_x", "u_y", "u_z", "r_x", "r_y", "r_z"];
pub fn beam_deformation(
field: &NodeField,
fespace: &FiniteElementSpace,
material: &ElementField,
) -> Result<ElementField> {
let components = Field::components(field)?;
let view = field.view()?;
let mut out = ElementField::empty();
for sub in fespace {
let mat = material.sub_for_fespace(sub)?;
out.add_sub(Handle::new(subspace_beam_deformation(
sub,
&view,
&components,
&mat,
)?))?;
}
Ok(out)
}
fn subspace_beam_deformation(
fespace: &Handle<SubFiniteElementSpace>,
view: &NodeFieldView,
components: &[String],
material: &Handle<SubElementField>,
) -> Result<SubElementField> {
let s = fespace.read();
let space_dim = s.space_dim();
let (dofs, out_comps): (&[&str], &[&str]) = match space_dim {
1 => (DOFS_1D, COMPONENTS_1D),
2 => (DOFS_2D, COMPONENTS_2D),
3 => (DOFS_3D, COMPONENTS_3D),
d => {
return Err(PyrucastError::Message(format!(
"beam_deformation: a beam lives in a 1-, 2- or 3-D configuration, got {d}-D"
)))
}
};
let n_nodes = s.nodes_per_cell()?;
let n_g = s.gauss_count();
if n_nodes != 2 {
return Err(PyrucastError::Message(format!(
"beam_deformation: a beam must be SEG2 (2 nodes/cell), got {n_nodes}"
)));
}
for required in dofs {
if !components.iter().any(|c| c == required) {
return Err(PyrucastError::Message(format!(
"beam_deformation: the field must carry a '{required}' component (has: [{}])",
components.join(", ")
)));
}
}
let mat = material.read();
let submesh = s.submesh();
let mesh = submesh.read();
let conn = mesh.connectivity();
let coords_h: Handle<Coords> = mesh.coords();
let coords = coords_h.read();
let n_comp = out_comps.len();
let mut field = SubElementField::new(
fespace.clone(),
out_comps.iter().map(|s| s.to_string()).collect(),
)?;
let slots: Vec<BendingSlots> = if space_dim == 3 {
vec![
BendingSlots::resolve(&mat, "I_z", "A_sy")?,
BendingSlots::resolve(&mat, "I_y", "A_sz")?,
]
} else {
vec![BendingSlots::resolve(&mat, "I", "A_s")?]
};
let n_cells = conn.len() / n_nodes;
for cell in 0..n_cells {
let ids = &conn[cell * n_nodes..(cell + 1) * n_nodes];
let row = mat.row(cell, 0);
let xa = coords.position(ids[0])?;
let xb = coords.position(ids[1])?;
let da: Vec<f64> = dofs
.iter()
.map(|c| view.value(ids[0], c))
.collect::<Result<_>>()?;
let db: Vec<f64> = dofs
.iter()
.map(|c| view.value(ids[1], c))
.collect::<Result<_>>()?;
for g in 0..n_g {
let xi = s.gauss_xi(g)?[0];
let t = 0.5 * (xi + 1.0);
let strains = match space_dim {
1 => strains_1d(&slots, row, xa, xb, &da, &db, t)?,
2 => strains_2d(&slots, row, xa, xb, &da, &db, t)?,
_ => strains_3d(&slots, row, xa, xb, &da, &db, t)?,
};
debug_assert_eq!(strains.len(), n_comp);
for (c, &v) in strains.iter().enumerate() {
field.set(cell, g, c, v)?;
}
}
}
Ok(field)
}
#[derive(Clone, Copy)]
struct BendingSlots {
e: usize,
i: usize,
shear: Option<(usize, usize)>,
}
impl BendingSlots {
fn resolve(mat: &SubElementField, i_name: &str, a_s_name: &str) -> Result<Self> {
let need = |name: &str| -> Result<usize> {
mat.component_index(name).ok_or_else(|| {
PyrucastError::Message(format!(
"beam_deformation: the material carries no `{name}`"
))
})
};
Ok(Self {
e: need("E")?,
i: need(i_name)?,
shear: mat.component_index("G").zip(mat.component_index(a_s_name)),
})
}
fn phi(&self, row: &[f64], l: f64) -> f64 {
let ei = row[self.e] * row[self.i];
let gas = self.shear.map(|(g, a_s)| row[g] * row[a_s]);
crate::models::beam::phi(ei, gas, l)
}
}
#[allow(clippy::too_many_arguments)]
fn strains_1d(
slots: &[BendingSlots],
row: &[f64],
xa: &[f64],
xb: &[f64],
da: &[f64],
db: &[f64],
t: f64,
) -> Result<Vec<f64>> {
let l = (xb[0] - xa[0]).abs();
let ph = slots[0].phi(row, l);
let d = [da[0], da[1], db[0], db[1]];
let (kappa, gamma) = crate::models::beam::section_strains(ph, l, &d, t);
Ok(vec![kappa, gamma])
}
#[allow(clippy::too_many_arguments)]
fn strains_2d(
slots: &[BendingSlots],
row: &[f64],
xa: &[f64],
xb: &[f64],
da: &[f64],
db: &[f64],
t: f64,
) -> Result<Vec<f64>> {
let (dx, dy) = (xb[0] - xa[0], xb[1] - xa[1]);
let l = (dx * dx + dy * dy).sqrt();
let (c, s) = (dx / l, dy / l);
let ua = c * da[0] + s * da[1];
let wa = -s * da[0] + c * da[1];
let ub = c * db[0] + s * db[1];
let wb = -s * db[0] + c * db[1];
let (ta, tb) = (da[2], db[2]);
let eps = (ub - ua) / l;
let ph = slots[0].phi(row, l);
let (kappa, gamma) = crate::models::beam::section_strains(ph, l, &[wa, ta, wb, tb], t);
Ok(vec![eps, kappa, gamma])
}
#[allow(clippy::too_many_arguments)]
fn strains_3d(
slots: &[BendingSlots],
row: &[f64],
xa: &[f64],
xb: &[f64],
da: &[f64],
db: &[f64],
t: f64,
) -> Result<Vec<f64>> {
let d = [xb[0] - xa[0], xb[1] - xa[1], xb[2] - xa[2]];
let l = norm(d);
let r = local_axes(d); let ua = rotate(&r, &da[0..3]);
let ra = rotate(&r, &da[3..6]);
let ub = rotate(&r, &db[0..3]);
let rb = rotate(&r, &db[3..6]);
let eps = (ub[0] - ua[0]) / l; let torsion = (rb[0] - ra[0]) / l;
let phi_y = slots[0].phi(row, l);
let (kappa_z, gamma_y) =
crate::models::beam::section_strains(phi_y, l, &[ua[1], ra[2], ub[1], rb[2]], t);
let phi_z = slots[1].phi(row, l);
let (minus_kappa_y, gamma_z) =
crate::models::beam::section_strains(phi_z, l, &[ua[2], -ra[1], ub[2], -rb[1]], t);
Ok(vec![
eps,
-minus_kappa_y,
kappa_z,
torsion,
gamma_y,
gamma_z,
])
}
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]
}
fn rotate(r: &[[f64; 3]; 3], v: &[f64]) -> [f64; 3] {
[
r[0][0] * v[0] + r[0][1] * v[1] + r[0][2] * v[2],
r[1][0] * v[0] + r[1][1] * v[1] + r[1][2] * v[2],
r[2][0] * v[0] + r[2][1] * v[1] + r[2][2] * v[2],
]
}
#[cfg(test)]
mod tests {
use super::*;
use crate::atoms::{ElementType, Node};
use crate::containers::field::SubField;
use crate::containers::mesh::{Mesh, SubMesh};
use crate::containers::node_field::SubNodeField;
use crate::coords::Coords;
use crate::handle::Handle;
fn one_element(
space_dim: u8,
a: &[f64],
b: &[f64],
) -> (FiniteElementSpace, Node, Node, Handle<SubMesh>) {
let coords = Handle::new(Coords::new(space_dim).unwrap());
let na = Node::create_in(coords.clone(), a).unwrap();
let nb = Node::create_in(coords.clone(), b).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
mesh.add_cell(&[na.id(), nb.id()]).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
let support = Handle::new(SubMesh::poi1_from_nodes(&[na.clone(), nb.clone()]).unwrap());
(fes, na, nb, support)
}
fn material(fes: &FiniteElementSpace, pairs: &[(&str, f64)]) -> ElementField {
let names: Vec<String> = pairs.iter().map(|(c, _)| (*c).to_string()).collect();
let mut m = SubElementField::new(fes.get(0).unwrap(), names).unwrap();
for (c, v) in pairs {
m.set_uniform(c, *v).unwrap();
}
let mut out = ElementField::empty();
out.add_sub(Handle::new(m)).unwrap();
out
}
fn integrated_curvature(
s: &SubElementField,
fes: &FiniteElementSpace,
comp: &str,
l: f64,
) -> f64 {
let sub = fes.get(0).unwrap().read();
(0..sub.gauss_count())
.map(|g| s.value(0, g, comp).unwrap() * sub.gauss_weight(g).unwrap())
.sum::<f64>()
* l
/ 2.0 }
#[test]
fn horizontal_2d_strains() {
let l = 2.0;
let (fes, a, b, support) = one_element(2, &[0.0, 0.0], &[l, 0.0]);
let mut f =
SubNodeField::from_poi1(&support, vec!["u_x".into(), "u_y".into(), "r_z".into()])
.unwrap();
f.set_value(a.id(), "u_x", 0.0).unwrap();
f.set_value(b.id(), "u_x", 0.5 * l).unwrap();
f.set_value(a.id(), "r_z", 0.0).unwrap();
f.set_value(b.id(), "r_z", 0.25 * l).unwrap();
let f = NodeField::from_sub(f);
let mat = material(
&fes,
&[("E", 1.0), ("A", 1.0), ("I", 1.0), ("G", 1.0), ("A_s", 1.0)],
);
let def = beam_deformation(&f, &fes, &mat).unwrap();
let s = def.get(0).unwrap().read();
assert_eq!(s.components(), &["eps", "kappa", "gamma"]);
for g in 0..s.gauss_count() {
assert!((s.value(0, g, "eps").unwrap() - 0.5).abs() < 1e-12);
}
let total = integrated_curvature(&s, &fes, "kappa", l);
assert!((total - 0.25 * l).abs() < 1e-10, "∫κ = {total}");
let g0 = s.value(0, 0, "gamma").unwrap();
for g in 1..s.gauss_count() {
assert!((s.value(0, g, "gamma").unwrap() - g0).abs() < 1e-12);
}
}
#[test]
fn vertical_2d_strains_are_rotated() {
let l = 2.0;
let (fes, a, b, support) = one_element(2, &[0.0, 0.0], &[0.0, l]);
let mut f =
SubNodeField::from_poi1(&support, vec!["u_x".into(), "u_y".into(), "r_z".into()])
.unwrap();
f.set_value(a.id(), "u_y", 0.0).unwrap();
f.set_value(b.id(), "u_y", 0.5 * l).unwrap();
f.set_value(a.id(), "r_z", 0.0).unwrap();
f.set_value(b.id(), "r_z", 0.25 * l).unwrap();
let f = NodeField::from_sub(f);
let mat = material(
&fes,
&[("E", 1.0), ("A", 1.0), ("I", 1.0), ("G", 1.0), ("A_s", 1.0)],
);
let def = beam_deformation(&f, &fes, &mat).unwrap();
let s = def.get(0).unwrap().read();
for g in 0..s.gauss_count() {
assert!((s.value(0, g, "eps").unwrap() - 0.5).abs() < 1e-12);
}
let total = integrated_curvature(&s, &fes, "kappa", l);
assert!((total - 0.25 * l).abs() < 1e-10, "∫κ = {total}");
}
#[test]
fn horizontal_3d_strains() {
let l = 2.0;
let (fes, a, b, support) = one_element(3, &[0.0, 0.0, 0.0], &[l, 0.0, 0.0]);
let mut f = SubNodeField::from_poi1(
&support,
["u_x", "u_y", "u_z", "r_x", "r_y", "r_z"]
.iter()
.map(|s| (*s).to_string())
.collect(),
)
.unwrap();
f.set_value(b.id(), "u_x", 0.5 * l).unwrap();
f.set_value(b.id(), "r_x", 0.1 * l).unwrap();
f.set_value(b.id(), "r_z", 0.25 * l).unwrap();
let _ = a;
let f = NodeField::from_sub(f);
let mat = material(
&fes,
&[
("E", 1.0),
("A", 1.0),
("I_y", 1.0),
("I_z", 1.0),
("G", 1.0),
("A_sy", 1.0),
("A_sz", 1.0),
],
);
let def = beam_deformation(&f, &fes, &mat).unwrap();
let s = def.get(0).unwrap().read();
for g in 0..s.gauss_count() {
assert!((s.value(0, g, "eps").unwrap() - 0.5).abs() < 1e-12);
assert!((s.value(0, g, "torsion").unwrap() - 0.1).abs() < 1e-12);
}
let total = integrated_curvature(&s, &fes, "kappa_z", l);
assert!((total - 0.25 * l).abs() < 1e-10, "∫κ_z = {total}");
}
#[test]
fn rejects_missing_dof() {
let (fes, _a, _b, support) = one_element(2, &[0.0, 0.0], &[1.0, 0.0]);
let f = NodeField::from_sub(
SubNodeField::from_poi1(&support, vec!["u_x".into(), "u_y".into()]).unwrap(),
);
let mat = material(
&fes,
&[("E", 1.0), ("A", 1.0), ("I", 1.0), ("G", 1.0), ("A_s", 1.0)],
);
let err = beam_deformation(&f, &fes, &mat).unwrap_err();
assert!(format!("{err}").contains("must carry a 'r_z'"));
}
}