use std::fmt;
use crate::atoms::Cell;
use crate::atoms::NodeId;
use crate::containers::finite_element_space::SubFiniteElementSpace;
use crate::error::{PyrucastError, Result};
use crate::store::{read, Handle};
#[derive(Clone)]
pub struct Element {
pub(crate) fespace: Handle<SubFiniteElementSpace>,
idx: usize,
}
impl Element {
pub fn new(fespace: Handle<SubFiniteElementSpace>, idx: usize) -> Result<Self> {
let n = read(&fespace)?.cell_count()?;
if idx >= n {
return Err(PyrucastError::Message(format!(
"element index {idx} out of range (cell_count={n})"
)));
}
Ok(Self { fespace, idx })
}
pub fn index(&self) -> usize {
self.idx
}
pub fn fespace(&self) -> Handle<SubFiniteElementSpace> {
self.fespace.clone()
}
pub fn cell(&self) -> Result<Cell> {
let sm = read(&self.fespace)?.submesh();
Cell::new(sm, self.idx)
}
pub fn nodes_per_cell(&self) -> Result<usize> {
read(&self.fespace)?.nodes_per_cell()
}
pub fn space_dim(&self) -> Result<usize> {
Ok(read(&self.fespace)?.space_dim())
}
pub fn ref_dim(&self) -> Result<usize> {
read(&self.fespace)?.ref_dim()
}
pub fn gauss_count(&self) -> usize {
read(&self.fespace).map(|s| s.gauss_count()).unwrap_or(0)
}
pub fn node_ids(&self) -> Result<Vec<NodeId>> {
self.cell()?.node_ids()
}
pub fn gauss_xi(&self, g: usize) -> Result<Vec<f64>> {
Ok(read(&self.fespace)?.gauss_xi(g)?.to_vec())
}
pub fn gauss_weight(&self, g: usize) -> Result<f64> {
read(&self.fespace)?.gauss_weight(g)
}
pub fn n_at_g(&self, g: usize) -> Result<Vec<f64>> {
Ok(read(&self.fespace)?.n_at_g(g)?.to_vec())
}
pub fn dn_at_g(&self, g: usize) -> Result<Vec<f64>> {
Ok(read(&self.fespace)?.dn_at_g(g)?.to_vec())
}
pub fn jacobian(&self, g: usize) -> Result<Vec<f64>> {
read(&self.fespace)?.jacobian(self.idx, g)
}
pub fn det_jacobian(&self, g: usize) -> Result<f64> {
read(&self.fespace)?.det_jacobian(self.idx, g)
}
pub fn dn_dx(&self, g: usize) -> Result<Vec<f64>> {
read(&self.fespace)?.dn_dx(self.idx, g)
}
}
impl fmt::Debug for Element {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Element").field("idx", &self.idx).finish()
}
}
impl fmt::Display for Element {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.cell() {
Ok(cell) => {
let et = cell.element_type().map(|e| e.name()).unwrap_or("?");
write!(f, "Element<{}> #{}", et, self.idx)
}
Err(_) => write!(f, "Element #{}", self.idx),
}
}
}
impl crate::dump::Dump for Element {
fn render(&self, opts: &crate::dump::DumpOptions) -> String {
match self.cell() {
Ok(cell) => format!(
"Element #{} ({} Gauss point(s))\n{}",
self.idx,
self.gauss_count(),
crate::dump::Dump::render(&cell, opts)
),
Err(e) => format!("Element #{} <{e}>", self.idx),
}
}
}
#[derive(Clone)]
pub struct ElementIter {
fespace: Handle<SubFiniteElementSpace>,
next: usize,
end: usize,
}
impl ElementIter {
pub(crate) fn new(fespace: Handle<SubFiniteElementSpace>, end: usize) -> Self {
Self {
fespace,
next: 0,
end,
}
}
}
impl Iterator for ElementIter {
type Item = Element;
fn next(&mut self) -> Option<Element> {
if self.next < self.end {
let el = Element {
fespace: self.fespace.clone(),
idx: self.next,
};
self.next += 1;
Some(el)
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.end - self.next;
(remaining, Some(remaining))
}
}
impl ExactSizeIterator for ElementIter {}
#[cfg(test)]
mod tests {
use super::*;
use crate::aggregate::Aggregate;
use crate::atoms::ElementType;
use crate::atoms::Node;
use crate::containers::finite_element_space::FiniteElementSpace;
use crate::containers::mesh::{Mesh, SubMesh};
use crate::coords::Coords;
use crate::store::insert;
fn seg2_fes() -> (Handle<Coords>, Vec<Node>, FiniteElementSpace) {
let coords = insert(Coords::new(1).unwrap());
let n0 = Node::create_in(coords.clone(), &[0.0]).unwrap();
let n1 = Node::create_in(coords.clone(), &[1.0]).unwrap();
let n2 = Node::create_in(coords.clone(), &[2.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[n0.id(), n1.id()]).unwrap();
mesh.add_cell(&[n1.id(), n2.id()]).unwrap();
let fes = FiniteElementSpace::lagrange1(&mesh).unwrap();
(coords, vec![n0, n1, n2], fes)
}
#[test]
fn element_exposes_cell_and_physical_quantities() {
let (_cfg, nodes, fes) = seg2_fes();
let el = fes.element(0, 0).unwrap();
assert_eq!(el.index(), 0);
assert_eq!(el.nodes_per_cell().unwrap(), 2);
assert_eq!(el.node_ids().unwrap(), vec![nodes[0].id(), nodes[1].id()]);
let cell = el.cell().unwrap();
assert_eq!(cell.element_type().unwrap(), ElementType::SEG2);
for g in 0..el.gauss_count() {
assert!((el.det_jacobian(g).unwrap() - 0.5).abs() < 1e-12);
}
}
#[test]
fn elements_iterator_yields_all_elements_in_order() {
let (_cfg, _nodes, fes) = seg2_fes();
let elements: Vec<Element> = fes.elements(0).unwrap().collect();
assert_eq!(elements.len(), 2);
assert_eq!(elements[0].index(), 0);
assert_eq!(elements[1].index(), 1);
}
#[test]
fn element_new_out_of_range_errors() {
let (_cfg, _nodes, fes) = seg2_fes();
let sub = fes.get(0).unwrap();
assert!(Element::new(sub, 5).is_err());
}
#[test]
fn fespace_element_by_indices() {
let (_cfg, _nodes, fes) = seg2_fes();
let el = fes.element(0, 1).unwrap();
assert_eq!(el.index(), 1);
assert!(fes.element(1, 0).is_err());
assert!(fes.element(0, 7).is_err());
}
}