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::Result;
use crate::models::{CellGeom, Domain, MatrixLayout, Physics, SubModelKind};
use crate::store::{read, Handle};
use serde::{Deserialize, Serialize};
pub const PRIMAL_VAR: &str = "T";
pub const DUAL_VAR: &str = "q";
pub const MATERIAL_COMPONENT: &str = "k";
const MATERIAL_COMPONENTS: &[&str] = &[MATERIAL_COMPONENT];
const CAPACITY_COMPONENTS: &[&str] = &["rho", "cp"];
const AXES: [&str; 3] = ["x", "y", "z"];
fn deformation_components(space_dim: usize) -> Vec<String> {
(0..space_dim)
.map(|a| format!("grad_{PRIMAL_VAR}_{}", AXES[a]))
.collect()
}
fn flux_components(space_dim: usize) -> Vec<String> {
(0..space_dim)
.map(|a| format!("flux_{}", AXES[a]))
.collect()
}
#[derive(Clone, Serialize, Deserialize)]
pub struct HeatConduction {
pub(crate) fespace: Handle<SubFiniteElementSpace>,
pub(crate) support: Handle<SubMesh>,
}
impl HeatConduction {
pub fn new(fespace: Handle<SubFiniteElementSpace>) -> Result<Self> {
let submesh = read(&fespace)?.submesh();
let support = read(&submesh)?.to_poi1()?;
Ok(Self { fespace, support })
}
}
impl SubModelKind for HeatConduction {
fn primal_vars(&self) -> Vec<String> {
vec![PRIMAL_VAR.to_string()]
}
fn dual_vars(&self) -> Vec<String> {
vec![DUAL_VAR.to_string()]
}
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 element_matrix(
&self,
geoms: &[CellGeom],
material: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
element_stiffness(
geom,
material.expect("HeatConduction requires a material field"),
ke,
)
}
fn element_mass(
&self,
geoms: &[CellGeom],
material: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
element_capacity(
geom,
material.expect("HeatConduction requires a material field"),
ke,
)
}
fn internal_force_element(
&self,
geoms: &[CellGeom],
stress: &SubElementField,
fe: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
let d = geom.space_dim;
let flux_names = flux_components(d);
for g in 0..geom.n_gauss {
let dn = geom.dn_dx(g)?; let w = geom.det_j_w(g)?;
for i in 0..geom.n_nodes {
let mut s = 0.0;
for a in 0..d {
s += dn[i * d + a] * stress.value(geom.cell, g, &flux_names[a])?;
}
fe[i] += s * w;
}
}
Ok(())
}
fn physics(&self) -> &'static [Physics] {
&[Physics::Thermal]
}
fn label(&self) -> &'static str {
"HeatConduction"
}
fn render(&self, _opts: &DumpOptions) -> String {
let primal = self.primal_vars().join(", ");
let dual = self.dual_vars().join(", ");
let n = read(&self.support).map(|s| s.cell_count()).unwrap_or(0);
format!(
"SubModel<HeatConduction>\n primal var(s): {primal}\n \
dual var(s): {dual}\n support: {n} node(s)"
)
}
}
impl Domain for HeatConduction {
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] {
CAPACITY_COMPONENTS
}
fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn behavior_output_components(&self) -> Result<Vec<String>> {
Ok(flux_components(read(&self.fespace)?.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("HeatConduction declares a material_fespace ⇒ material is supplied");
let (cell, space_dim) = (geom.cell, geom.space_dim);
let k = mat.value(cell, g, MATERIAL_COMPONENT)?;
let grad_names = deformation_components(space_dim);
for a in 0..space_dim {
out[a] = k * input.value(cell, g, &grad_names[a])?;
}
Ok(())
}
}
pub fn element_stiffness(
geom: &CellGeom,
material: &SubElementField,
ke: &mut [f64],
) -> Result<()> {
let n_nodes = geom.n_nodes;
let space_dim = geom.space_dim;
for g in 0..geom.n_gauss {
let dn = geom.dn_dx(g)?;
let det_j_w = geom.det_j_w(g)?;
let k = material.value(geom.cell, g, MATERIAL_COMPONENT)?;
for i in 0..n_nodes {
for j in 0..n_nodes {
let mut grad_dot = 0.0;
for a in 0..space_dim {
grad_dot += dn[i * space_dim + a] * dn[j * space_dim + a];
}
ke[i * n_nodes + j] += k * grad_dot * det_j_w;
}
}
}
Ok(())
}
pub fn element_capacity(geom: &CellGeom, material: &SubElementField, ke: &mut [f64]) -> Result<()> {
let n_nodes = geom.n_nodes;
let rho = material.value(geom.cell, 0, "rho").map_err(|_| {
crate::error::PyrucastError::Message(
"HeatConduction capacity matrix: material component `rho` (density) is required".into(),
)
})?;
let cp = material.value(geom.cell, 0, "cp").map_err(|_| {
crate::error::PyrucastError::Message(
"HeatConduction capacity matrix: material component `cp` (specific heat) is required"
.into(),
)
})?;
let rho_cp = rho * cp;
for g in 0..geom.n_gauss {
let n = geom.n_at_g(g)?;
let w = geom.det_j_w(g)? * rho_cp;
for i in 0..n_nodes {
for j in 0..n_nodes {
ke[i * n_nodes + j] += n[i] * n[j] * w;
}
}
}
Ok(())
}
#[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, ElementType, Mesh, Node};
use crate::store::insert;
fn seg2_hc(length: f64) -> HeatConduction {
let coords = insert(Coords::new(1).unwrap());
let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[length]).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();
HeatConduction::new(fes.get(0).unwrap()).unwrap()
}
#[test]
fn behavior_fespace_is_the_physics_fespace() {
let hc = seg2_hc(1.0);
let fe = hc.behavior_fespace();
assert_eq!(fe.index(), hc.fespace.index());
assert_eq!(fe.generation(), hc.fespace.generation());
}
#[test]
fn integrate_behavior_returns_weak_form_flux() {
let hc = seg2_hc(2.0);
let grad = 1.5; let k = 1.5;
let mut def = SubElementField::new(hc.fespace.clone(), deformation_components(1)).unwrap();
def.set_uniform("grad_T_x", grad).unwrap();
let def = insert(def);
let mut mat =
SubElementField::new(hc.fespace.clone(), vec![MATERIAL_COMPONENT.to_string()]).unwrap();
mat.set_uniform(MATERIAL_COMPONENT, k).unwrap();
let mat = insert(mat);
let flux = hc.integrate_behavior(&def, None, Some(&mat), None).unwrap();
assert_eq!(flux.components(), &["flux_x".to_string()]);
let expected = k * grad;
for g in 0..flux.gauss_count() {
assert!((flux.value(0, g, "flux_x").unwrap() - expected).abs() < 1e-12);
}
}
}