pyrucast 0.13.2

Finite-element library in Rust, inspired by cast3m, exposed to Python
Documentation
//! A `Cell` is a lightweight view on a single cell of a [`SubMesh`].
//!
//! It carries a cloned `Handle<SubMesh>` plus the cell's index — cloning
//! a `Cell` is just an `Arc` clone, so it is cheap to pass around and to
//! create on the fly inside an iterator. The actual node coordinates live
//! in the `Coords` and are fetched on demand through
//! [`Cell::nodes`] / [`Cell::node_ids`].
//!
//! # Example
//!
//! ```
//! use pyrucast::coords::Coords;
//! use pyrucast::atoms::ElementType;
//! use pyrucast::containers::mesh::{Mesh, SubMesh};
//! use pyrucast::atoms::Node;
//! use pyrucast::handle::Handle;
//!
//! let coords = Handle::new(Coords::new(2).unwrap());
//! let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
//! let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
//! let c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();
//!
//! let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::TRI3));
//! mesh.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
//!
//! let cell = mesh.cell(0, 0).unwrap();
//! assert_eq!(cell.nodes().unwrap().len(), 3);
//! for node in cell.nodes().unwrap() {
//!     let _ = node.position().unwrap();
//! }
//! ```

use std::fmt;

use crate::atoms::ElementType;
use crate::atoms::Node;
use crate::atoms::NodeId;
use crate::containers::mesh::SubMesh;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;

/// Lightweight view on a single cell of a `SubMesh`.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// // A light view on **one** cell: its connectivity, without the shape
/// // functions — `Element` is what carries those.
/// let c = maillage.cell(0, 0)?;
/// assert_eq!(c.node_ids().len(), 3);
/// assert_eq!(c.element_type(), ElementType::TRI3);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone)]
pub struct Cell {
    pub(crate) sm: Handle<SubMesh>,
    idx: usize,
}

impl Cell {
    /// Build a cell view. Errors if `idx` is past the submesh's
    /// `cell_count`.
    ///
    /// ```
    /// # use pyrucast::atoms::Cell;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords, ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let sm = Handle::new(sm);
    /// let cellule = Cell::new(sm, 0).unwrap();
    /// assert_eq!(cellule.index(), 0);
    /// ```
    pub fn new(sm: Handle<SubMesh>, idx: usize) -> Result<Self> {
        let n = sm.read().cell_count();
        if idx >= n {
            return Err(PyrucastError::Message(format!(
                "cell index {idx} out of range (cell_count={n})"
            )));
        }
        Ok(Self { sm, idx })
    }

    /// Index of this cell inside its parent submesh.
    ///
    /// ```
    /// # use pyrucast::atoms::Cell;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords, ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let sm = Handle::new(sm);
    /// assert_eq!(Cell::new(sm, 0).unwrap().index(), 0);
    /// ```
    pub fn index(&self) -> usize {
        self.idx
    }

    /// Element type of this cell (same as the parent submesh).
    ///
    /// ```
    /// # use pyrucast::atoms::Cell;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords, ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let sm = Handle::new(sm);
    /// assert_eq!(Cell::new(sm, 0).unwrap().element_type(), ElementType::TRI3);
    /// ```
    pub fn element_type(&self) -> ElementType {
        self.sm.read().element_type()
    }

    /// Number of nodes that make up this cell (= `element_type().nodes_per_cell()`).
    ///
    /// ```
    /// # use pyrucast::atoms::Cell;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords, ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let sm = Handle::new(sm);
    /// assert_eq!(Cell::new(sm, 0).unwrap().nodes_per_cell(), 3); // TRI3
    /// ```
    pub fn nodes_per_cell(&self) -> usize {
        self.sm.read().element_type().nodes_per_cell()
    }

    /// Raw connectivity (node ids) of this cell, in submesh order.
    ///
    /// ```
    /// # use pyrucast::atoms::Cell;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords, ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let sm = Handle::new(sm);
    /// let ids = Cell::new(sm, 0).unwrap().node_ids();
    /// assert_eq!(ids, vec![n[0].id(), n[1].id(), n[2].id()]); // dans l'ordre d'ajout
    /// ```
    pub fn node_ids(&self) -> Vec<NodeId> {
        let s = self.sm.read();
        let npc = s.element_type().nodes_per_cell();
        s.connectivity()[self.idx * npc..(self.idx + 1) * npc].to_vec()
    }

    /// Materialise the cell's nodes as a `Vec<Node>`. Each `Node`
    /// increments the node's refcount in the owning `Coords`,
    /// matching the behaviour of `Coords::add_node`.
    ///
    /// ```
    /// # use pyrucast::atoms::Cell;
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords, ElementType::TRI3);
    /// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
    /// # let sm = Handle::new(sm);
    /// // Every `Node` returned adds one to its node's count in the `Coords`.
    /// let noeuds = Cell::new(sm, 0).unwrap().nodes().unwrap();
    /// assert_eq!(noeuds.len(), 3);
    /// assert_eq!(noeuds[0].position().unwrap(), vec![0.0, 0.0]);
    /// ```
    pub fn nodes(&self) -> Result<Vec<Node>> {
        let coords = self.sm.read().coords();
        let ids = self.node_ids();
        ids.into_iter()
            .map(|id| Node::acquire(coords.clone(), id))
            .collect()
    }
}

/// Structure, **without a lock**: the carrying submesh and the index.
///
/// The element type and the nodes would require reading the submesh, hence
/// taking a guard — which a diagnostic display must not do: `{:?}` is written
/// in an error message or a trace, sometimes while holding precisely the lock
/// at fault. That information lives in `dump`, called
/// en connaissance de cause.
impl fmt::Debug for Cell {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Cell")
            .field("submesh", &self.sm)
            .field("idx", &self.idx)
            .finish()
    }
}

/// Summary, **without a lock**: `Cell #0 @ <SubMesh #ea6020>`.
///
/// The connectivity and the element type would have to be read from the
/// submesh. A `Cell` is only a view — a handle and an index — and its short
/// display must not be able to block: the handle prints without touching the
/// object, by deliberate choice (see `Handle`), and that caution holds for its
/// views too.
impl fmt::Display for Cell {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Cell #{} @ {}", self.idx, self.sm)
    }
}

impl crate::dump::Dump for Cell {
    fn render(&self, opts: &crate::dump::DumpOptions) -> String {
        use crate::dump::{fmt_float, table};
        let header = format!("Cell<{}> #{}", self.element_type(), self.idx);
        // Per-node coordinate table (one lock on the Coords).
        let body = (|| -> Result<String> {
            let coords = self.sm.read().coords();
            let ids = self.node_ids();
            let c = coords.read();
            let mut rows: Vec<Vec<String>> = Vec::with_capacity(ids.len());
            let mut dim = 0usize;
            for &id in &ids {
                let coord = c.position(id)?;
                dim = dim.max(coord.len());
                let mut row = vec![id.to_string()];
                row.extend(coord.iter().map(|v| fmt_float(*v, opts.precision)));
                rows.push(row);
            }
            for row in &mut rows {
                row.resize(1 + dim, String::new());
            }
            const AXES: [&str; 3] = ["x", "y", "z"];
            let mut headers = vec!["node".to_string()];
            headers.extend((0..dim).map(|i| AXES.get(i).copied().unwrap_or("?").to_string()));
            Ok(table(&headers, &rows, opts))
        })();
        match body {
            Ok(t) => format!("{header}\n{t}"),
            Err(e) => format!("{header}\n<{e}>"),
        }
    }
}

/// Iterator over the cells of a single submesh.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id()]).unwrap();
/// # let maillage = Mesh::from_submesh(sm);
/// // The walk over a zone's cells, without a per-cell allocation.
/// assert_eq!(maillage.cells(0)?.count(), 1);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Clone)]
pub struct CellIter {
    sm: Handle<SubMesh>,
    next: usize,
    end: usize,
}

impl CellIter {
    pub(crate) fn new(sm: Handle<SubMesh>, end: usize) -> Self {
        Self { sm, next: 0, end }
    }
}

impl Iterator for CellIter {
    type Item = Cell;
    fn next(&mut self) -> Option<Cell> {
        if self.next < self.end {
            let c = Cell {
                sm: self.sm.clone(),
                idx: self.next,
            };
            self.next += 1;
            Some(c)
        } else {
            None
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.end - self.next;
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for CellIter {}

// ─── Unit tests ─────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::atoms::Node;
    use crate::containers::mesh::{Mesh, SubMesh};
    use crate::coords::Coords;
    use crate::handle::Handle;

    #[test]
    fn cell_exposes_ids_and_nodes() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();

        let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
        let h = Handle::new(sm);

        let cell = Cell::new(h, 0).unwrap();
        assert_eq!(cell.element_type(), ElementType::TRI3);
        assert_eq!(cell.nodes_per_cell(), 3);
        assert_eq!(cell.node_ids(), vec![a.id(), b.id(), c.id()]);
        let nodes = cell.nodes().unwrap();
        assert_eq!(nodes.len(), 3);
        assert_eq!(nodes[0].id(), a.id());
    }

    #[test]
    fn cell_new_rejects_out_of_range() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let sm = Handle::new(SubMesh::new(coords, ElementType::TRI3));
        assert!(Cell::new(sm, 0).is_err());
    }

    #[test]
    fn cell_dump_renders_coordinate_table() {
        use crate::dump::{Dump, DumpOptions};
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let c = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();
        let mut sm = SubMesh::new(coords, ElementType::TRI3);
        sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
        let cell = Cell::new(Handle::new(sm), 0).unwrap();

        let s = cell.render(&DumpOptions::default());
        assert!(s.starts_with("Cell<TRI3> #0"), "header:\n{s}");
        assert!(s.contains("node"), "table header:\n{s}");
        assert!(s.contains('x') && s.contains('y'), "axis labels:\n{s}");
        // One row per node + coordinates at default precision (3).
        assert!(s.contains("0.000"), "coords:\n{s}");
        assert_eq!(s.lines().count(), 5, "header + table header + 3 rows:\n{s}");
    }

    #[test]
    fn cells_iterator_yields_all_cells() {
        let coords = Handle::new(Coords::new(1).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0]).unwrap();
        let b = Node::create_in(coords.clone(), &[1.0]).unwrap();
        let c = Node::create_in(coords.clone(), &[2.0]).unwrap();

        let mut mesh = Mesh::from_submesh(SubMesh::new(coords, ElementType::SEG2));
        mesh.add_cell(&[a.id(), b.id()]).unwrap();
        mesh.add_cell(&[b.id(), c.id()]).unwrap();

        let cells: Vec<_> = mesh.cells(0).unwrap().collect();
        assert_eq!(cells.len(), 2);
        assert_eq!(cells[0].index(), 0);
        assert_eq!(cells[1].index(), 1);
        assert_eq!(cells[0].node_ids(), vec![a.id(), b.id()]);
        assert_eq!(cells[1].node_ids(), vec![b.id(), c.id()]);
    }
}