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::symmetry::{self, MaterialSymmetry};
use crate::models::{CellGeom, Domain, MatrixLayout, Physics, SubModelKind};
use serde::{Deserialize, Serialize};
pub fn primal_var(species: &str) -> String {
format!("c_{species}")
}
pub fn dual_var(species: &str) -> String {
format!("j_{species}")
}
const STORAGE_COMPONENTS: &[&str] = &["poro"];
const MATERIAL_COMPONENTS: &[&str] = &["D"];
const ORTHOTROPIC_2D: &[&str] = &["D_1", "D_2", "D_3", "V1X", "V1Y"];
const ORTHOTROPIC_3D: &[&str] = &[
"D_1", "D_2", "D_3", "V1X", "V1Y", "V1Z", "V2X", "V2Y", "V2Z",
];
const ANISOTROPIC_2D: &[&str] = &["D_11", "D_12", "D_13", "D_22", "D_23", "D_33", "V1X", "V1Y"];
const ANISOTROPIC_3D: &[&str] = &[
"D_11", "D_12", "D_13", "D_22", "D_23", "D_33", "V1X", "V1Y", "V1Z", "V2X", "V2Y", "V2Z",
];
fn material_contract(symmetry: MaterialSymmetry, space_dim: usize, species: &str) -> Vec<String> {
static_contract(symmetry, space_dim)
.iter()
.map(|name| {
if name.starts_with('D') {
format!("{name}_{species}")
} else {
(*name).to_string()
}
})
.collect()
}
fn static_contract(symmetry: MaterialSymmetry, space_dim: usize) -> &'static [&'static str] {
match (symmetry, space_dim) {
(MaterialSymmetry::Isotropic, _) => MATERIAL_COMPONENTS,
(MaterialSymmetry::Orthotropic, 2) => ORTHOTROPIC_2D,
(MaterialSymmetry::Orthotropic, _) => ORTHOTROPIC_3D,
(MaterialSymmetry::Anisotropic, 2) => ANISOTROPIC_2D,
(MaterialSymmetry::Anisotropic, _) => ANISOTROPIC_3D,
}
}
const AXES: [&str; 3] = ["x", "y", "z"];
fn gradient_components(space_dim: usize, species: &str) -> Vec<String> {
let primal = primal_var(species);
(0..space_dim)
.map(|a| format!("grad_{primal}_{}", AXES[a]))
.collect()
}
fn flux_components(space_dim: usize, species: &str) -> Vec<String> {
let dual = dual_var(species);
(0..space_dim)
.map(|a| format!("{dual}_{}", AXES[a]))
.collect()
}
#[derive(Clone, Serialize, Deserialize)]
pub struct Fick {
pub(crate) fespace: Handle<SubFiniteElementSpace>,
pub(crate) support: Handle<SubMesh>,
pub(crate) space_dim: usize,
pub(crate) symmetry: MaterialSymmetry,
pub(crate) species: String,
}
impl Fick {
pub fn new(fespace: Handle<SubFiniteElementSpace>, species: &str) -> Result<Self> {
Self::with_symmetry(fespace, MaterialSymmetry::Isotropic, species)
}
pub fn with_symmetry(
fespace: Handle<SubFiniteElementSpace>,
symmetry: MaterialSymmetry,
species: &str,
) -> Result<Self> {
if species.is_empty() {
return Err(PyrucastError::Message(
"Fick: a diffusing species must be named — its concentration, flux and \
diffusivity all carry the name (`c_H2`, `j_H2`, `D_H2`), which is what lets \
two species share a mesh"
.into(),
));
}
let (submesh, space_dim) = {
let s = fespace.read();
(s.submesh(), s.space_dim())
};
let support = submesh.read().to_poi1()?;
Ok(Self {
fespace,
support,
space_dim,
symmetry,
species: species.to_string(),
})
}
}
impl SubModelKind for Fick {
fn primal_vars(&self) -> Vec<String> {
vec![primal_var(&self.species)]
}
fn dual_vars(&self) -> Vec<String> {
vec![dual_var(&self.species)]
}
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<()> {
element_stiffness(
&geoms[0],
material.expect("Fick requires a material field"),
self.symmetry,
&self.species,
ke,
)
}
fn element_mass(
&self,
geoms: &[CellGeom],
material: Option<&SubElementField>,
ke: &mut [f64],
) -> Result<()> {
element_storage(
&geoms[0],
material.expect("Fick 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 names = flux_components(d, &self.species);
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, &names[a])?;
}
fe[i] += s * w;
}
}
Ok(())
}
fn physics(&self) -> &'static [Physics] {
&[Physics::Diffusion]
}
fn label(&self) -> &'static str {
"Fick"
}
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<Fick({})>\n primal var(s): {primal}\n \
dual var(s): {dual}\n support: {n} node(s)",
self.symmetry
)
}
}
impl Domain for Fick {
fn material_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn material_components(&self) -> Option<Vec<String>> {
Some(material_contract(
self.symmetry,
self.space_dim,
&self.species,
))
}
fn optional_material_components(&self) -> &'static [&'static str] {
STORAGE_COMPONENTS
}
fn behavior_fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
fn behavior_output_components(&self) -> Result<Vec<String>> {
Ok(flux_components(self.space_dim, &self.species))
}
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("Fick declares a material_fespace ⇒ material is supplied");
let (cell, space_dim) = (geom.cell, geom.space_dim);
let names = gradient_components(space_dim, &self.species);
let prefix = format!("D_{}", self.species);
let d3 = symmetry::transport_tensor(mat, cell, g, self.symmetry, space_dim, &prefix)?;
for a in 0..space_dim {
let mut acc = 0.0;
for b in 0..space_dim {
acc += d3[(a, b)] * input.value(cell, g, &names[b])?;
}
out[a] = acc;
}
Ok(())
}
}
pub fn element_stiffness(
geom: &CellGeom,
material: &SubElementField,
symmetry: MaterialSymmetry,
species: &str,
ke: &mut [f64],
) -> Result<()> {
let n_nodes = geom.n_nodes;
let space_dim = geom.space_dim;
let tensor = if symmetry.has_frame() {
Some(symmetry::transport_tensor(
material,
geom.cell,
0,
symmetry,
space_dim,
&format!("D_{species}"),
)?)
} else {
None
};
for g in 0..geom.n_gauss {
let dn = geom.dn_dx(g)?;
let det_j_w = geom.det_j_w(g)?;
match &tensor {
None => {
let d = material.value(geom.cell, g, &format!("D_{species}"))?;
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] += d * grad_dot * det_j_w;
}
}
}
Some(d3) => {
for i in 0..n_nodes {
for j in 0..n_nodes {
let mut acc = 0.0;
for a in 0..space_dim {
for b in 0..space_dim {
acc += dn[i * space_dim + a] * d3[(a, b)] * dn[j * space_dim + b];
}
}
ke[i * n_nodes + j] += acc * det_j_w;
}
}
}
}
}
Ok(())
}
pub fn element_storage(geom: &CellGeom, material: &SubElementField, ke: &mut [f64]) -> Result<()> {
let n_nodes = geom.n_nodes;
let poro = material.value(geom.cell, 0, "poro").map_err(|_| {
PyrucastError::Message(
"Fick storage matrix: material component `poro` (storage coefficient) is required"
.into(),
)
})?;
for g in 0..geom.n_gauss {
let n = geom.n_at_g(g)?;
let det_j_w = geom.det_j_w(g)?;
for i in 0..n_nodes {
for j in 0..n_nodes {
ke[i * n_nodes + j] += poro * n[i] * n[j] * det_j_w;
}
}
}
Ok(())
}