use crate::containers::element_field::SubElementField;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::containers::matrix::DofOrdering;
use crate::containers::mesh::SubMesh;
use crate::dump::DumpOptions;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use crate::models::owned_components;
use crate::models::{
CellGeom, Contribution, Domain, MatrixKind, MatrixLayout, Physics, SubModelKind,
};
use serde::{Deserialize, Serialize};
const AXES: [&str; 3] = ["x", "y", "z"];
pub const MATERIAL_COMPONENT: &str = "p";
const MATERIAL_COMPONENTS: &[&str] = &[MATERIAL_COMPONENT];
fn primal_name(a: usize) -> String {
format!("u_{}", AXES[a])
}
fn dual_name(a: usize) -> String {
format!("f_{}", AXES[a])
}
fn traction_names(space_dim: usize) -> Vec<String> {
(0..space_dim).map(|a| format!("t_{}", AXES[a])).collect()
}
#[derive(Clone, Serialize, Deserialize)]
pub struct FollowerPressure {
pub(crate) fespace: Handle<SubFiniteElementSpace>,
pub(crate) support: Handle<SubMesh>,
pub(crate) space_dim: usize,
}
impl FollowerPressure {
pub fn new(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
let (submesh, space_dim, ref_dim) = {
let s = fespace.read();
(s.submesh(), s.space_dim(), s.ref_dim()?)
};
if ref_dim + 1 != space_dim {
return Err(PyrucastError::Message(format!(
"FollowerPressure: a {ref_dim}-D element in a {space_dim}-D space is not a \
boundary — a pressure acts on a surface (SEG2 in 2-D, TRI3/QUA4 in 3-D), \
and needs a normal to follow"
)));
}
let support = submesh.read().to_poi1()?;
Ok(Self {
fespace,
support,
space_dim,
})
}
}
impl SubModelKind for FollowerPressure {
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 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: false,
})
}
fn contributions(
&self,
_kind: MatrixKind,
_material: Option<&Handle<SubElementField>>,
) -> Result<Vec<Contribution>> {
Ok(Vec::new())
}
fn internal_force_element(
&self,
geoms: &[CellGeom],
stress: &SubElementField,
fe: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let d = self.space_dim;
let names = traction_names(d);
for g in 0..geom.n_gauss {
let shape = geom.n_at_g(g)?;
let w = geom.det_j_w(g)?;
for i in 0..geom.n_nodes {
for (a, name) in names.iter().enumerate() {
fe[i * d + a] += shape[i] * stress.value(geom.cell, g, name)? * w;
}
}
}
Ok(())
}
fn physics(&self) -> &'static [Physics] {
&[Physics::Mechanical]
}
fn label(&self) -> &'static str {
"FollowerPressure"
}
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<FollowerPressure>\n primal var(s): {primal}\n \
dual var(s): {dual}\n support: {n} node(s)"
)
}
}
impl Domain for FollowerPressure {
fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn material_components(&self) -> Option<Vec<String>> {
Some(owned_components(MATERIAL_COMPONENTS))
}
fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn behavior_output_components(&self) -> Result<Vec<String>> {
Ok(traction_names(self.space_dim))
}
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("FollowerPressure declares a material_fespace");
let (cell, d) = (geom.cell, self.space_dim);
let p = mat.value(cell, g, MATERIAL_COMPONENT)?;
let mut grad = vec![0.0; d * d];
for a in 0..d {
for b in 0..d {
let name = format!("grad_u_{}_{}", AXES[a], AXES[b]);
grad[a * d + b] = input.value(cell, g, &name)?;
}
}
let reference = geom.tangents(g)?;
let deformed: Vec<Vec<f64>> = reference
.iter()
.map(|a| {
(0..d)
.map(|i| a[i] + (0..d).map(|j| grad[i * d + j] * a[j]).sum::<f64>())
.collect()
})
.collect();
let n_ref = CellGeom::normal_from_tangents(&reference)?;
let area_ref = n_ref.iter().map(|v| v * v).sum::<f64>().sqrt();
if area_ref <= f64::EPSILON {
return Err(PyrucastError::Message(format!(
"FollowerPressure: cell {cell} is degenerate at Gauss point {g} (null area)"
)));
}
let n_def = CellGeom::normal_from_tangents(&deformed)?;
for (a, o) in out.iter_mut().enumerate().take(d) {
*o = -p * n_def[a] / area_ref;
}
Ok(())
}
}