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 crate::parallel::*;
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, welded) = build_representatives(mesh, &coords_handle, tol)?;
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: &[u32],
) -> Result<(Mesh, usize)> {
let mut result = Mesh::empty();
let mut dropped = 0;
for sm_handle in mesh {
let (et, color, mapped, degenerate) = {
let s = sm_handle.read();
let et = s.element_type();
let npc = et.nodes_per_cell();
let conn = s.connectivity();
let mapped: Vec<NodeId> = conn
.par_iter()
.with_min_len(MIN_PARALLEL_LEN)
.map(|&n| image(representative, n))
.collect();
let degenerate: Vec<bool> = mapped
.par_chunks(npc)
.with_min_len(MIN_PARALLEL_LEN)
.map(is_degenerate)
.collect();
(et, s.face_color(), mapped, degenerate)
};
let npc = et.nodes_per_cell();
let dropped_here = degenerate.iter().filter(|d| **d).count();
dropped += dropped_here;
let conn = if dropped_here == 0 {
mapped
} else {
let mut kept = Vec::with_capacity(mapped.len() - dropped_here * npc);
for (cell, °) in mapped.chunks(npc).zip(°enerate) {
if !deg {
kept.extend_from_slice(cell);
}
}
kept
};
let mut new_sm = SubMesh::from_connectivity(coords_handle.clone(), et, conn)?;
new_sm.set_face_color(color);
result.add_sub(Handle::new(new_sm))?;
}
Ok((result, dropped))
}
fn weld_in_place(mesh: &Mesh, representative: &[u32]) -> 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, a matrix, or a node field supported on this POI1 zone \
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;
}
let collapsing = s
.connectivity()
.par_chunks(npc)
.with_min_len(MIN_PARALLEL_LEN)
.position_first(|cell| collapses(representative, cell));
if let Some(ci) = collapsing {
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_dense(representative)?;
}
mesh.subset(0..mesh.len())
}
fn build_representatives(
mesh: &Mesh,
coords_handle: &crate::handle::Handle<Coords>,
tol: f64,
) -> Result<(Vec<u32>, usize)> {
let n_nodes = coords_handle.read().node_count();
let mut referenced = vec![false; n_nodes];
for sm_handle in mesh {
for &n in sm_handle.read().connectivity() {
match referenced.get_mut(n.0 as usize) {
Some(slot) => *slot = true,
None => {
return Err(PyrucastError::Message(format!(
"merge_nodes: node {} does not belong to this Coords",
n.0
)));
}
}
}
}
let ids: Vec<NodeId> = (0..n_nodes as u32)
.filter(|&i| referenced[i as usize])
.map(NodeId)
.collect();
let mut parent: Vec<u32> = (0..n_nodes as u32).collect();
if ids.is_empty() {
return Ok((parent, 0));
}
let guard = coords_handle.read();
let coords: &Coords = &guard;
coords.ensure_all_alive(&ids)?;
let grid = NodeGrid::build(&ids, coords, tol);
let tol2 = tol * tol;
let edges: Vec<(u32, u32)> = ids
.par_iter()
.with_min_len(MIN_PARALLEL_LEN)
.flat_map_iter(|&id| {
let p = coords.position_alive(id);
let mut local: Vec<(u32, u32)> = Vec::new();
grid.for_each_candidate(p, tol, &mut |other: NodeId| {
if other.0 < id.0 && dist2(p, coords.position_alive(other)) <= tol2 {
local.push((id.0, other.0));
}
});
local
})
.collect();
drop(guard);
for &(a, b) in &edges {
let (ra, rb) = (find(&mut parent, a), find(&mut parent, b));
if ra != rb {
let (root, child) = if ra < rb { (ra, rb) } else { (rb, ra) };
parent[child as usize] = root;
}
}
let mut welded = 0;
for &id in &ids {
let root = find(&mut parent, id.0);
parent[id.0 as usize] = root;
if root != id.0 {
welded += 1;
}
}
Ok((parent, welded))
}
fn find(parent: &mut [u32], mut x: u32) -> u32 {
while parent[x as usize] != x {
let grand = parent[parent[x as usize] as usize];
parent[x as usize] = grand;
x = grand;
}
x
}
struct NodeGrid {
dim: usize,
lo: Vec<f64>,
inv: Vec<f64>,
res: Vec<usize>,
stride: Vec<usize>,
starts: Vec<u32>,
items: Vec<NodeId>,
}
impl NodeGrid {
fn build(ids: &[NodeId], coords: &Coords, tol: f64) -> NodeGrid {
let dim = coords.dim() as usize;
let n = ids.len();
let mut lo = vec![f64::INFINITY; dim];
let mut hi = vec![f64::NEG_INFINITY; dim];
for &id in ids {
for (a, &x) in coords.position_alive(id).iter().enumerate() {
lo[a] = lo[a].min(x);
hi[a] = hi[a].max(x);
}
}
let live = lo
.iter()
.zip(&hi)
.filter(|(l, h)| *h - *l > 0.0)
.count()
.max(1);
let target = (n as f64).powf(1.0 / live as f64).round().max(1.0);
let mut res = vec![1usize; dim];
let mut inv = vec![0.0f64; dim];
for a in 0..dim {
let extent = hi[a] - lo[a];
if extent <= 0.0 {
continue;
}
let mut r = target;
if tol > 0.0 {
r = r.min((extent / tol).floor().max(1.0));
}
res[a] = r as usize;
inv[a] = res[a] as f64 / extent;
}
let mut stride = vec![1usize; dim];
for a in 1..dim {
stride[a] = stride[a - 1] * res[a - 1];
}
let total = stride[dim - 1] * res[dim - 1];
let mut grid = NodeGrid {
dim,
lo,
inv,
res,
stride,
starts: vec![0; total + 1],
items: vec![NodeId(0); n],
};
for &id in ids {
let b = grid.bucket(coords.position_alive(id));
grid.starts[b + 1] += 1;
}
for b in 0..total {
grid.starts[b + 1] += grid.starts[b];
}
let mut cursor = grid.starts.clone();
for &id in ids {
let b = grid.bucket(coords.position_alive(id));
grid.items[cursor[b] as usize] = id;
cursor[b] += 1;
}
grid
}
fn axis_index(&self, axis: usize, x: f64) -> usize {
let i = ((x - self.lo[axis]) * self.inv[axis]).floor();
i.clamp(0.0, (self.res[axis] - 1) as f64) as usize
}
fn bucket(&self, p: &[f64]) -> usize {
(0..self.dim)
.map(|a| self.axis_index(a, p[a]) * self.stride[a])
.sum()
}
fn for_each_candidate(&self, p: &[f64], tol: f64, f: &mut impl FnMut(NodeId)) {
self.visit(0, 0, p, tol, f);
}
fn visit(&self, axis: usize, acc: usize, p: &[f64], tol: f64, f: &mut impl FnMut(NodeId)) {
if axis == self.dim {
for &id in &self.items[self.starts[acc] as usize..self.starts[acc + 1] as usize] {
f(id);
}
return;
}
let first = self.axis_index(axis, p[axis] - tol);
let last = self.axis_index(axis, p[axis] + tol);
for i in first..=last {
self.visit(axis + 1, acc + i * self.stride[axis], p, tol, f);
}
}
}
fn dist2(a: &[f64], b: &[f64]) -> f64 {
a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum()
}
fn image(table: &[u32], n: NodeId) -> NodeId {
NodeId(table[n.0 as usize])
}
fn is_degenerate(nodes: &[NodeId]) -> bool {
nodes
.iter()
.enumerate()
.any(|(i, n)| nodes[i + 1..].contains(n))
}
fn collapses(table: &[u32], cell: &[NodeId]) -> bool {
cell.iter().enumerate().any(|(i, &n)| {
let rep = image(table, n);
cell[i + 1..].iter().any(|&m| image(table, m) == rep)
})
}
#[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(), 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(), 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 a_chain_of_close_nodes_closes_into_one_cluster() {
let coords = coords2();
let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
let b = Node::create_in(coords.clone(), &[0.9, 0.0]).unwrap();
let c = Node::create_in(coords.clone(), &[1.8, 0.0]).unwrap();
let far = Node::create_in(coords.clone(), &[10.0, 0.0]).unwrap();
let mut mesh = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::SEG2));
mesh.add_cell(&[a.id(), far.id()]).unwrap();
mesh.add_cell(&[b.id(), far.id()]).unwrap();
mesh.add_cell(&[c.id(), far.id()]).unwrap();
let merged = merge_nodes(&mesh, 1.0, false).unwrap();
for cell in 0..3 {
assert_eq!(merged.node(0, cell, 0).unwrap().id(), a.id());
}
assert_eq!(merged.node(0, 0, 1).unwrap().id(), far.id());
}
#[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(), 1);
assert_eq!(right.cell_count(), 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(), 2);
assert_eq!(mesh.node(0, 1, 1).unwrap().id(), c.id());
assert_eq!(merge_nodes(&mesh, 1e-6, false).unwrap().cell_count(), 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();
SubMesh::seal(&sealed.get(0).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);
}
}