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 = "h";
const MATERIAL_COMPONENTS: &[&str] = &[MATERIAL_COMPONENT];
const INPUT_COMPONENT: &str = PRIMAL_VAR;
const OUTPUT_COMPONENT: &str = "flux";
#[derive(Clone, Serialize, Deserialize)]
pub struct Convection {
pub(crate) fespace: Handle<SubFiniteElementSpace>,
pub(crate) support: Handle<SubMesh>,
}
impl Convection {
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 Convection {
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 element_matrix(
&self,
geoms: &[CellGeom],
material: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
element_film_matrix(
geom,
material.expect("Convection requires a material field"),
ke,
)
}
fn internal_force_element(
&self,
geoms: &[CellGeom],
stress: &SubElementField,
fe: &mut [f64],
) -> Result<()> {
let geom = &geoms[0];
for g in 0..geom.n_gauss {
let shape = geom.n_at_g(g)?;
let w = geom.det_j_w(g)?;
let flux = stress.value(geom.cell, g, OUTPUT_COMPONENT)?;
for i in 0..geom.n_nodes {
fe[i] += shape[i] * flux * w;
}
}
Ok(())
}
fn physics(&self) -> &'static [Physics] {
&[Physics::Thermal]
}
fn label(&self) -> &'static str {
"Convection"
}
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<Convection>\n primal var(s): {primal}\n \
dual var(s): {dual}\n support: {n} node(s)"
)
}
}
impl Domain for Convection {
fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn material_components(&self) -> Option<&'static [&'static str]> {
Some(MATERIAL_COMPONENTS)
}
fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn behavior_output_components(&self) -> Result<Vec<String>> {
Ok(vec![OUTPUT_COMPONENT.to_string()])
}
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("Convection declares a material_fespace ⇒ material is supplied");
let cell = geom.cell;
let h = mat.value(cell, g, MATERIAL_COMPONENT)?;
let t = input.value(cell, g, INPUT_COMPONENT)?;
out[0] = h * t;
Ok(())
}
}
pub fn element_film_matrix(
geom: &CellGeom,
material: &SubElementField,
ke: &mut [f64],
) -> Result<()> {
let n_nodes = geom.n_nodes;
for g in 0..geom.n_gauss {
let shape = geom.n_at_g(g)?;
let det_j_w = geom.det_j_w(g)?;
let h = material.value(geom.cell, g, MATERIAL_COMPONENT)?;
for i in 0..n_nodes {
for j in 0..n_nodes {
ke[i * n_nodes + j] += h * shape[i] * shape[j] * det_j_w;
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::aggregate::Aggregate;
use crate::atoms::{ElementType, Node};
use crate::containers::field::SubField;
use crate::containers::finite_element_space::FiniteElementSpace;
use crate::containers::mesh::Mesh;
use crate::coords::Coords;
use crate::store::insert;
fn seg2_edge(length: f64) -> Convection {
let coords = insert(Coords::new(2).unwrap());
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[length, 0.0]).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();
Convection::new(fes.get(0).unwrap()).unwrap()
}
fn material(conv: &Convection, h: f64) -> Handle<SubElementField> {
let mut m =
SubElementField::new(conv.fespace.clone(), vec![MATERIAL_COMPONENT.to_string()])
.unwrap();
m.set_uniform(MATERIAL_COMPONENT, h).unwrap();
insert(m)
}
#[test]
fn vars_match_heat_conduction() {
let conv = seg2_edge(1.0);
assert_eq!(conv.primal_vars(), vec!["T"]);
assert_eq!(conv.dual_vars(), vec!["q"]);
}
#[test]
fn film_matrix_is_h_times_line_mass() {
let (h, len) = (5.0, 2.0);
let conv = seg2_edge(len);
let mat = material(&conv, h);
let blocks = conv.build_stiffness_blocks(Some(&mat)).unwrap();
let k = &blocks[0];
let nodes: Vec<_> = read(&conv.support).unwrap().connectivity().to_vec();
let (a, b) = (nodes[0], nodes[1]);
let tol = 1e-12;
assert!((k.get(a, "q", a, "T") - h * len / 3.0).abs() < tol);
assert!((k.get(b, "q", b, "T") - h * len / 3.0).abs() < tol);
assert!((k.get(a, "q", b, "T") - h * len / 6.0).abs() < tol);
assert!((k.get(a, "q", b, "T") - k.get(b, "q", a, "T")).abs() < tol);
let sum = k.get(a, "q", a, "T")
+ k.get(a, "q", b, "T")
+ k.get(b, "q", a, "T")
+ k.get(b, "q", b, "T");
assert!((sum - h * len).abs() < tol);
}
#[test]
fn integrate_behavior_returns_weak_form_flux() {
let (h, temp) = (3.0, 4.0);
let conv = seg2_edge(1.0);
let mat = material(&conv, h);
let mut input =
SubElementField::new(conv.fespace.clone(), vec![INPUT_COMPONENT.to_string()]).unwrap();
input.set_uniform(INPUT_COMPONENT, temp).unwrap();
let input = insert(input);
let out = conv
.integrate_behavior(&input, None, Some(&mat), None)
.unwrap();
assert_eq!(out.components(), &[OUTPUT_COMPONENT.to_string()]);
for g in 0..out.gauss_count() {
assert!((out.value(0, g, OUTPUT_COMPONENT).unwrap() - h * temp).abs() < 1e-12);
}
}
}