use crate::aggregate::Aggregate;
use crate::atoms::NodeId;
use crate::containers::mesh::{Mesh, SubMesh};
use crate::coords::Coords;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use std::collections::HashMap;
pub fn merge_nodes(mesh: &Mesh, tol: f64, in_place: bool) -> Result<Mesh> {
if tol < 0.0 {
return Err(PyrucastError::Message(format!(
"merge_nodes: tol must be ≥ 0, got {tol}"
)));
}
let coords_handle = mesh.coords()?;
let representative = build_representatives(mesh, &coords_handle, tol)?;
let welded = representative
.iter()
.filter(|(id, rep)| *id != *rep)
.count();
let (result, dropped) = if in_place {
(weld_in_place(mesh, &representative)?, 0)
} else {
weld_into_copy(mesh, &coords_handle, &representative)?
};
println!("{}", summary(welded, dropped, tol, in_place));
Ok(result)
}
fn summary(welded: usize, dropped: usize, tol: f64, in_place: bool) -> String {
let how = if in_place { " (in place)" } else { "" };
let cells = if in_place {
String::from("cells untouched")
} else {
format!("{dropped} cell(s) dropped")
};
format!("merge_nodes{how}: {welded} node(s) welded, {cells}, tol = {tol}")
}
fn weld_into_copy(
mesh: &Mesh,
coords_handle: &crate::handle::Handle<Coords>,
representative: &HashMap<NodeId, NodeId>,
) -> Result<(Mesh, usize)> {
let mut result = Mesh::empty();
let mut dropped = 0;
for sm_handle in mesh {
let (et, color, conn) = {
let s = sm_handle.read();
(s.element_type(), s.face_color(), s.connectivity().to_vec())
};
let npc = et.nodes_per_cell();
let mut new_sm = SubMesh::new(coords_handle.clone(), et);
new_sm.set_face_color(color);
for chunk in conn.chunks(npc) {
let mapped: Vec<NodeId> = chunk
.iter()
.map(|n| representative.get(n).copied().unwrap_or(*n))
.collect();
if is_degenerate(&mapped) {
dropped += 1;
continue;
}
new_sm.add_cell(&mapped)?;
}
result.add_sub(Handle::new(new_sm))?;
}
Ok((result, dropped))
}
fn weld_in_place(mesh: &Mesh, representative: &HashMap<NodeId, NodeId>) -> Result<Mesh> {
for (si, sm_handle) in mesh.into_iter().enumerate() {
let s = sm_handle.read();
if s.is_sealed() {
return Err(PyrucastError::Message(format!(
"merge_nodes(in_place): submesh {si} is sealed — a finite-element \
space, field or matrix already reads its nodes; weld before \
building them, or weld by copy (in_place = false)"
)));
}
let npc = s.element_type().nodes_per_cell();
if npc == 0 {
continue;
}
for (ci, chunk) in s.connectivity().chunks(npc).enumerate() {
let mapped: Vec<NodeId> = chunk
.iter()
.map(|n| representative.get(n).copied().unwrap_or(*n))
.collect();
if is_degenerate(&mapped) {
return Err(PyrucastError::Message(format!(
"merge_nodes(in_place): cell {ci} of submesh {si} ({}) would \
collapse — welding it away would change the cell count, which \
an in-place weld preserves; lower tol, or weld by copy \
(in_place = false), which drops degenerate cells",
s.element_type()
)));
}
}
}
for sm_handle in mesh {
sm_handle.write().remap_nodes(representative)?;
}
mesh.subset(0..mesh.len())
}
fn build_representatives(
mesh: &Mesh,
coords_handle: &crate::handle::Handle<Coords>,
tol: f64,
) -> Result<HashMap<NodeId, NodeId>> {
let mut ids: Vec<NodeId> = Vec::new();
{
let mut seen = std::collections::HashSet::new();
for sm_handle in mesh {
for &n in sm_handle.read().connectivity() {
if seen.insert(n) {
ids.push(n);
}
}
}
}
ids.sort_by_key(|n| n.0);
let coords = coords_handle.read();
let dim = coords.dim() as usize;
let cell = if tol > 0.0 { tol } else { 1.0 };
let tol2 = tol * tol;
let offsets = neighbour_offsets(dim);
let mut grid: HashMap<Vec<i64>, Vec<NodeId>> = HashMap::new();
let mut representative: HashMap<NodeId, NodeId> = HashMap::new();
for &id in &ids {
let p = coords.position(id)?;
let base: Vec<i64> = p.iter().map(|&x| (x / cell).floor() as i64).collect();
let mut rep = None;
'search: for off in &offsets {
let key: Vec<i64> = base.iter().zip(off).map(|(b, o)| b + o).collect();
if let Some(candidates) = grid.get(&key) {
for &c in candidates {
if dist2(p, coords.position(c)?) <= tol2 {
rep = Some(c);
break 'search;
}
}
}
}
match rep {
Some(r) => {
representative.insert(id, r);
}
None => {
representative.insert(id, id);
grid.entry(base).or_default().push(id);
}
}
}
Ok(representative)
}
fn dist2(a: &[f64], b: &[f64]) -> f64 {
a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum()
}
fn is_degenerate(nodes: &[NodeId]) -> bool {
nodes
.iter()
.enumerate()
.any(|(i, n)| nodes[i + 1..].contains(n))
}
fn neighbour_offsets(dim: usize) -> Vec<Vec<i64>> {
let mut offsets = vec![Vec::new()];
for _ in 0..dim {
let mut next = Vec::with_capacity(offsets.len() * 3);
for prefix in &offsets {
for d in [-1i64, 0, 1] {
let mut v = prefix.clone();
v.push(d);
next.push(v);
}
}
offsets = next;
}
offsets
}
#[cfg(test)]
mod tests {
use super::*;
use crate::atoms::ElementType;
use crate::atoms::Node;
fn coords2() -> crate::handle::Handle<Coords> {
Handle::new(Coords::new(2).unwrap())
}
#[test]
fn welds_two_coincident_corners() {
let coords = coords2();
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 b2 = Node::create_in(coords.clone(), &[1.0 + 1e-9, 0.0]).unwrap();
let c2 = Node::create_in(coords.clone(), &[0.5, 1.0 - 1e-9]).unwrap();
let d = Node::create_in(coords.clone(), &[1.5, 1.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
mesh.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
mesh.add_cell(&[b2.id(), d.id(), c2.id()]).unwrap();
let merged = merge_nodes(&mesh, 1e-6, false).unwrap();
assert_eq!(merged.cell_count().unwrap(), 2, "both triangles survive");
let tri1: Vec<_> = (0..3).map(|i| merged.node(0, 1, i).unwrap().id()).collect();
assert_eq!(tri1, vec![b.id(), d.id(), c.id()]);
}
#[test]
fn drops_degenerate_cell() {
let coords = coords2();
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(), &[1.0, 0.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
mesh.add_cell(&[b.id(), c.id()]).unwrap();
let merged = merge_nodes(&mesh, 1e-6, false).unwrap();
assert_eq!(
merged.cell_count().unwrap(),
1,
"the (b,c) segment is dropped"
);
}
#[test]
fn representative_is_smallest_id_and_keeps_its_coords() {
let coords = coords2();
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[5.0, 5.0]).unwrap();
let c = Node::create_in(coords.clone(), &[5.0 + 1e-9, 5.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
mesh.add_cell(&[a.id(), c.id()]).unwrap();
let merged = merge_nodes(&mesh, 1e-6, false).unwrap();
let welded = merged.node(0, 1, 1).unwrap();
assert_eq!(welded.id(), b.id());
assert_eq!(coords.read().position(b.id()).unwrap(), &[5.0, 5.0]);
}
#[test]
fn tol_zero_welds_only_exact_duplicates() {
let coords = coords2();
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 exact = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let near = Node::create_in(coords.clone(), &[1.0 + 1e-9, 0.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[a.id(), near.id()]).unwrap();
mesh.add_cell(&[b.id(), exact.id()]).unwrap();
let merged = merge_nodes(&mesh, 0.0, false).unwrap();
assert_eq!(merged.node(0, 0, 1).unwrap().id(), near.id());
assert_eq!(merged.node(0, 1, 1).unwrap().id(), a.id());
assert_ne!(near.id(), b.id());
}
#[test]
fn in_place_welds_through_a_union_and_reaches_both_meshes() {
let coords = coords2();
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 b2 = Node::create_in(coords.clone(), &[1.0 + 1e-9, 0.0]).unwrap();
let d = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
let mut left = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
left.add_cell(&[a.id(), b.id()]).unwrap();
let mut right = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
right.add_cell(&[b2.id(), d.id()]).unwrap();
let both = left.union(&right).unwrap();
let welded = merge_nodes(&both, 1e-6, true).unwrap();
assert_eq!(welded.len(), both.len());
assert!(welded.get(0).unwrap().same_object(&both.get(0).unwrap()));
assert_eq!(right.node(0, 0, 0).unwrap().id(), b.id());
assert_eq!(left.node(0, 0, 1).unwrap().id(), b.id());
assert_eq!(left.cell_count().unwrap(), 1);
assert_eq!(right.cell_count().unwrap(), 1);
}
#[test]
fn in_place_moves_refcounts_and_leaves_positions_alone() {
let coords = coords2();
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[5.0, 5.0]).unwrap();
let b2 = Node::create_in(coords.clone(), &[5.0 + 1e-9, 5.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
mesh.add_cell(&[a.id(), b2.id()]).unwrap();
assert_eq!(coords.read().refcount(b.id()), 2);
merge_nodes(&mesh, 1e-6, true).unwrap();
assert_eq!(coords.read().refcount(b.id()), 3);
assert_eq!(coords.read().refcount(b2.id()), 1);
assert_eq!(coords.read().position(b.id()).unwrap(), &[5.0, 5.0]);
}
#[test]
fn in_place_refuses_a_collapsing_cell_without_touching_anything() {
let coords = coords2();
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(), &[1.0, 0.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
mesh.add_cell(&[b.id(), c.id()]).unwrap();
assert!(merge_nodes(&mesh, 1e-6, true).is_err());
assert_eq!(mesh.cell_count().unwrap(), 2);
assert_eq!(mesh.node(0, 1, 1).unwrap().id(), c.id());
assert_eq!(
merge_nodes(&mesh, 1e-6, false)
.unwrap()
.cell_count()
.unwrap(),
1
);
}
#[test]
fn in_place_refuses_a_sealed_submesh_without_touching_anything() {
let coords = coords2();
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 b2 = Node::create_in(coords.clone(), &[1.0 + 1e-9, 0.0]).unwrap();
let d = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
let mut sealed = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
sealed.add_cell(&[b2.id(), d.id()]).unwrap();
crate::containers::mesh::seal(&sealed.get(0).unwrap()).unwrap();
let mut open = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
open.add_cell(&[a.id(), b.id()]).unwrap();
let both = open.union(&sealed).unwrap();
assert!(merge_nodes(&both, 1e-6, true).is_err());
assert_eq!(sealed.node(0, 0, 0).unwrap().id(), b2.id());
assert_eq!(open.node(0, 0, 1).unwrap().id(), b.id());
}
#[test]
fn tally_line_reports_both_welds() {
assert_eq!(
summary(3, 1, 1e-6, false),
"merge_nodes: 3 node(s) welded, 1 cell(s) dropped, tol = 0.000001"
);
assert_eq!(
summary(3, 0, 1e-6, true),
"merge_nodes (in place): 3 node(s) welded, cells untouched, tol = 0.000001"
);
}
#[test]
fn negative_tol_is_error() {
let coords = coords2();
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 mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
assert!(merge_nodes(&mesh, -1.0, false).is_err());
}
#[test]
fn leaves_input_untouched_and_increfs_result() {
let coords = coords2();
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 mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[a.id(), b.id()]).unwrap();
assert_eq!(coords.read().refcount(a.id()), 2);
let merged = merge_nodes(&mesh, 1e-6, false).unwrap();
assert_eq!(coords.read().refcount(a.id()), 3);
drop(merged);
assert_eq!(coords.read().refcount(a.id()), 2);
}
}