pyrucast 0.12.0

Finite-element library in Rust, inspired by cast3m, exposed to Python
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! Boundary-extraction operator: the border loop(s) of a surface mesh.
//!
//! [`border`] is the inverse companion of
//! [`crate::ops::mesh::triangulate_surface()`]
//! (whose input is one or more closed SEG2 loops): it takes a surface mesh
//! (TRI3 / QUA4 cells, or their quadratic TRI6 / QUA8 / QUA9) and returns its
//! boundary as one or more closed SEG2 (or SEG3) loops, one per submesh.
//!
//! A *boundary* edge is an element edge used by exactly one cell; interior
//! edges are shared by two cells (with opposite orientations) and cancel.
//! The boundary edges are then chained into closed loops: a simply-connected
//! domain yields a single loop, a domain with holes or several disjoint
//! pieces yields several — hence several submeshes.
//!
//! With an `angle_deg` given, each closed loop is further split into open
//! *arêtes* (edges) at its **corner** nodes — where the boundary changes
//! direction by more than `angle_deg` degrees — the 1-D analogue of the
//! dihedral-angle face splitting done by [`crate::ops::mesh::skin()`].

use crate::aggregate::Aggregate;
use crate::atoms::{ElementType, NodeId};
use crate::containers::mesh::{Mesh, SubMesh};
use crate::coords::Coords;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
use std::collections::HashMap;

/// Undirected edge key: the two node ids sorted, so an edge and its reverse
/// share the same key (and interior edges collide).
fn edge_key(u: NodeId, v: NodeId) -> (NodeId, NodeId) {
    if u.0 <= v.0 {
        (u, v)
    } else {
        (v, u)
    }
}

/// Extract the boundary of a **surface** mesh (TRI3 / QUA4 cells) as one or
/// more closed SEG2 loops — or, for a quadratic surface (TRI6 / QUA8 /
/// QUA9), as SEG3 loops that keep the mid-node of every boundary edge.
///
/// Every element edge is taken with the cell's CCW orientation; an edge used
/// by exactly one cell is a *boundary* edge (interior edges appear twice,
/// with opposite orientations, and cancel). Boundary edges from all surface
/// submeshes are pooled together — so the QUA4 + TRI3 output of
/// [`triangulate_surface()`](fn@crate::ops::mesh::triangulate_surface) yields a
/// single shared boundary — then chained into closed loops.
///
/// The result is a [`Mesh`] with **one SEG2 submesh per loop**: one submesh
/// for a simply-connected domain, several when the domain has holes or
/// disjoint components. Each loop keeps the CCW boundary orientation, so the
/// outer loop runs counter-clockwise and hole loops clockwise — the
/// orientation [`triangulate_surface()`](fn@crate::ops::mesh::triangulate_surface)
/// expects of its input contour. The original nodes are reused (and re-referenced).
///
/// With `angle_deg = Some(a)`, every closed loop is split into open **arêtes**
/// at its corner nodes: a node is a corner when the boundary turns by more
/// than `a` degrees there (the angle between the incoming and outgoing edge
/// directions). Each arête — a maximal run of near-collinear segments between
/// two corners — becomes its own `SEG2` submesh (a straight side of a square
/// yields one arête, so a square boundary yields four). A loop with no corner
/// (a smoothly curved boundary whose every turn stays under `a`) is kept as a
/// single closed loop. `angle_deg = None` keeps every boundary as one closed
/// loop (no splitting) — the default.
///
/// The edges are read on the cells' corners; a quadratic cell's mid-node of
/// edge `i` (local `corners + i`) becomes the mid-node of the SEG3. Linear
/// and quadratic surface zones cannot be mixed.
///
/// POI1 submeshes are ignored (a point has no edge). Errors if the mesh has
/// no surface cells, if it lists one zone twice (every edge would sit under
/// two cells, the border would be empty), if it carries cells that are
/// neither POI1 nor a surface type listed above (1-D and 3-D borders are not
/// handled here — see [`skin()`](fn@crate::ops::mesh::skin) for the boundary
/// of a volume), if it mixes linear and quadratic surfaces, or if the
/// boundary is not a clean set of closed loops (an open or non-manifold
/// edge).
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # use pyrucast::ops::mesh;
/// # let coords = Handle::new(Coords::new(3).unwrap());
/// # let p = |x: &[f64]| Node::create_in(coords.clone(), x).unwrap();
/// // A surface's border: the edges carried by **one** cell only,
/// // chaînées en boucles fermées.
/// # let q = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]];
/// # let n: Vec<Node> = q.iter().map(|x| p(x)).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::QUA4);
/// # sm.add_cell(&[n[0].id(), n[1].id(), n[2].id(), n[3].id()])?;
/// let carre = Mesh::from_submesh(sm);
/// assert_eq!(mesh::border(&carre, None)?.cell_count(), 4);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn border(mesh: &Mesh, angle_deg: Option<f64>) -> Result<Mesh> {
    let coords = mesh.coords()?;
    mesh.check_zones_once("border")?;

    // 1. Count every element edge across all surface submeshes. A boundary
    //    edge is one whose undirected key occurs exactly once.
    let mut counts: HashMap<(NodeId, NodeId), u32> = HashMap::new();
    let mut quadratic: Option<bool> = None;
    for sm in mesh {
        // Guard held for this zone's pass: the loop below only reads.
        let s = sm.read();
        let (et, conn) = (s.element_type(), s.connectivity());
        let is_quadratic = match et {
            ElementType::POI1 => continue, // no edges — tolerated
            ElementType::TRI3 | ElementType::QUA4 => false,
            ElementType::TRI6 | ElementType::QUA8 | ElementType::QUA9 => true,
            other => {
                return Err(PyrucastError::Message(format!(
                    "border: only surface meshes (TRI3/QUA4, TRI6/QUA8/QUA9) are supported, got {}",
                    other
                )));
            }
        };
        if quadratic.is_some_and(|q| q != is_quadratic) {
            return Err(PyrucastError::Message(
                "border: linear and quadratic surface zones cannot be bordered together".into(),
            ));
        }
        quadratic = Some(is_quadratic);
        let (npc, corners) = (et.nodes_per_cell(), et.as_kind().corner_count());
        for cell in conn.chunks(npc) {
            for i in 0..corners {
                let key = edge_key(cell[i], cell[(i + 1) % corners]);
                *counts.entry(key).or_insert(0) += 1;
            }
        }
    }
    let Some(quadratic) = quadratic else {
        return Err(PyrucastError::Message(
            "border: mesh has no surface cells (TRI3/QUA4, TRI6/QUA8/QUA9)".into(),
        ));
    };

    // 2. Re-walk the cells in order, collecting boundary edges with their
    //    cell orientation. `adj` maps a from-node to the to-nodes still to be
    //    consumed; `order` keeps the from-nodes in a deterministic order so
    //    the loops (and their starts) are reproducible.
    //    A quadratic cell also hands over the mid-node of each boundary edge,
    //    keyed by the directed edge.
    let mut adj: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
    let mut order: Vec<NodeId> = Vec::new();
    let mut mids: HashMap<(NodeId, NodeId), NodeId> = HashMap::new();
    for sm in mesh {
        // Guard held for this zone's pass: the loop below only reads.
        let s = sm.read();
        let (et, conn) = (s.element_type(), s.connectivity());
        if et == ElementType::POI1 {
            continue;
        }
        let (npc, corners) = (et.nodes_per_cell(), et.as_kind().corner_count());
        for cell in conn.chunks(npc) {
            for i in 0..corners {
                let (u, v) = (cell[i], cell[(i + 1) % corners]);
                if counts.get(&edge_key(u, v)) == Some(&1) {
                    adj.entry(u).or_default().push(v);
                    order.push(u);
                    if quadratic {
                        mids.insert((u, v), cell[corners + i]);
                    }
                }
            }
        }
    }
    let mids = quadratic.then_some(&mids);

    // 3. Chain the boundary edges into closed loops (node-id sequences).
    let mut loops: Vec<Vec<NodeId>> = Vec::new();
    for &start in &order {
        // Skip a from-node whose boundary edge was already consumed.
        if adj.get(&start).is_none_or(|outs| outs.is_empty()) {
            continue;
        }
        let mut chain = Vec::new();
        let mut current = start;
        loop {
            let outs = adj
                .get_mut(&current)
                .filter(|o| !o.is_empty())
                .ok_or_else(|| {
                    PyrucastError::Message(format!(
                        "border: boundary is not a closed loop (open or non-manifold at node {})",
                        current
                    ))
                })?;
            let next = outs.remove(0);
            chain.push(current);
            if next == start {
                break;
            }
            current = next;
        }
        loops.push(chain);
    }

    // 4. Emit one SEG2 submesh per loop, or — when an angle is given — per
    //    open arête once each loop is split at its corner nodes.
    let mut result = Mesh::empty();
    match angle_deg {
        None => {
            for chain in &loops {
                emit_closed(&mut result, &coords, chain, mids)?;
            }
        }
        Some(a) => {
            let cos_tol = a.to_radians().cos();
            // Decide the split under the coords read guard (positions only);
            // build the submeshes afterwards, since `add_cell` write-locks
            // `Coords` and must not run while the read guard is held.
            let mut pieces: Vec<(Vec<NodeId>, bool)> = Vec::new(); // (nodes, closed)
            {
                let c = coords.read();
                for chain in &loops {
                    let corners = corner_indices(&c, chain, cos_tol)?;
                    if corners.is_empty() {
                        pieces.push((chain.clone(), true)); // smooth loop: keep closed
                    } else {
                        for arc in split_at_corners(chain, &corners) {
                            pieces.push((arc, false));
                        }
                    }
                }
            }
            for (nodes, closed) in &pieces {
                if *closed {
                    emit_closed(&mut result, &coords, nodes, mids)?;
                } else {
                    emit_open(&mut result, &coords, nodes, mids)?;
                }
            }
        }
    }
    Ok(result)
}

/// Append the segments `(u, v)` as one submesh of `result`: SEG2, or SEG3
/// `[u, v, mid]` when the boundary's mid-nodes are given.
fn emit(
    result: &mut Mesh,
    coords: &Handle<Coords>,
    segments: impl Iterator<Item = (NodeId, NodeId)>,
    mids: Option<&HashMap<(NodeId, NodeId), NodeId>>,
) -> Result<()> {
    let (et, conn): (ElementType, Vec<NodeId>) = match mids {
        None => (
            ElementType::SEG2,
            segments.flat_map(|(u, v)| [u, v]).collect(),
        ),
        Some(mids) => (
            ElementType::SEG3,
            segments.flat_map(|(u, v)| [u, v, mids[&(u, v)]]).collect(),
        ),
    };
    let sub = SubMesh::from_connectivity(coords.clone(), et, conn)?;
    result.add_sub(Handle::new(sub))
}

/// Append a **closed** loop (segments wrap from the last node back to the
/// first) as one submesh of `result`.
fn emit_closed(
    result: &mut Mesh,
    coords: &Handle<Coords>,
    chain: &[NodeId],
    mids: Option<&HashMap<(NodeId, NodeId), NodeId>>,
) -> Result<()> {
    let n = chain.len();
    emit(
        result,
        coords,
        (0..n).map(|i| (chain[i], chain[(i + 1) % n])),
        mids,
    )
}

/// Append an **open** polyline (an arête: no wrap-around) as one submesh.
fn emit_open(
    result: &mut Mesh,
    coords: &Handle<Coords>,
    arc: &[NodeId],
    mids: Option<&HashMap<(NodeId, NodeId), NodeId>>,
) -> Result<()> {
    emit(result, coords, arc.windows(2).map(|w| (w[0], w[1])), mids)
}

/// Indices, into the cyclic `chain`, of the **corner** nodes: those where the
/// boundary turns by more than the tolerance (dot of the unit incoming and
/// outgoing edge directions below `cos_tol`). Degenerate (zero-length) edges
/// never make a corner.
fn corner_indices(c: &Coords, chain: &[NodeId], cos_tol: f64) -> Result<Vec<usize>> {
    let k = chain.len();
    let mut corners = Vec::new();
    for i in 0..k {
        let prev = c.position(chain[(i + k - 1) % k])?;
        let cur = c.position(chain[i])?;
        let next = c.position(chain[(i + 1) % k])?;
        if let Some(cos_turn) = turn_cosine(prev, cur, next)
            && cos_turn < cos_tol
        {
            corners.push(i);
        }
    }
    Ok(corners)
}

/// Cosine of the turning angle at `cur` between the incoming edge
/// (`prev`→`cur`) and the outgoing edge (`cur`→`next`), or `None` if either
/// edge has zero length. Works in any dimension (2-D or planar 3-D).
fn turn_cosine(prev: &[f64], cur: &[f64], next: &[f64]) -> Option<f64> {
    let din: Vec<f64> = cur.iter().zip(prev).map(|(a, b)| a - b).collect();
    let dout: Vec<f64> = next.iter().zip(cur).map(|(a, b)| a - b).collect();
    let dot: f64 = din.iter().zip(&dout).map(|(a, b)| a * b).sum();
    let nin = din.iter().map(|x| x * x).sum::<f64>().sqrt();
    let nout = dout.iter().map(|x| x * x).sum::<f64>().sqrt();
    if nin == 0.0 || nout == 0.0 {
        return None;
    }
    Some((dot / (nin * nout)).clamp(-1.0, 1.0))
}

/// Split a cyclic `chain` at the given `corners` (indices, non-empty) into
/// open arêtes. Each arête runs from one corner to the next (inclusive of both
/// endpoints), following the loop's order; with a single corner the whole loop
/// becomes one open polyline starting and ending at that corner.
fn split_at_corners(chain: &[NodeId], corners: &[usize]) -> Vec<Vec<NodeId>> {
    let k = chain.len();
    let m = corners.len();
    let mut arcs = Vec::with_capacity(m);
    for t in 0..m {
        let a = corners[t];
        let b = corners[(t + 1) % m];
        let mut arc = vec![chain[a]];
        let mut idx = a;
        loop {
            idx = (idx + 1) % k;
            arc.push(chain[idx]);
            if idx == b {
                break;
            }
        }
        arcs.push(arc);
    }
    arcs
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::atoms::Node;
    use crate::coords::Coords;
    use crate::handle::Handle;

    /// signed area of a node-id loop, read from `coords` (2-D).
    fn signed_area(coords: &crate::handle::Handle<Coords>, loop_ids: &[NodeId]) -> f64 {
        let c = coords.read();
        let n = loop_ids.len();
        let mut a = 0.0;
        for i in 0..n {
            let p = c.position(loop_ids[i]).unwrap();
            let q = c.position(loop_ids[(i + 1) % n]).unwrap();
            a += p[0] * q[1] - q[0] * p[1];
        }
        a / 2.0
    }

    /// Ordered node-id loop of submesh `s` (chains its SEG2 connectivity).
    fn loop_of(mesh: &Mesh, s: usize) -> Vec<NodeId> {
        let sm = mesh.get(s).unwrap();
        let conn = sm.read().connectivity().to_vec();
        // The submesh is stored as consecutive segments (a,b)(b,c)…; the
        // first node of each segment, in order, is the loop.
        conn.chunks(2).map(|seg| seg[0]).collect()
    }

    #[test]
    fn single_triangle_gives_one_triloop() {
        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.0, 1.0]).unwrap();
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
        m.add_cell(&[a.id(), b.id(), c.id()]).unwrap();

        let ct = border(&m, None).unwrap();
        assert_eq!(ct.len(), 1);
        assert_eq!(ct.element_types().unwrap(), vec![ElementType::SEG2]);
        assert_eq!(ct.cell_counts().unwrap(), vec![3]);
        // CCW input → CCW boundary (positive signed area).
        assert!(signed_area(&coords, &loop_of(&ct, 0)) > 0.0);
    }

    #[test]
    fn two_triangles_sharing_diagonal_give_one_quadloop() {
        // Unit square split into two triangles along the (b,d) diagonal; the
        // shared diagonal is interior and must not appear in the contour.
        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(), &[1.0, 1.0]).unwrap();
        let d = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
        m.add_cell(&[a.id(), b.id(), d.id()]).unwrap();
        m.add_cell(&[b.id(), c.id(), d.id()]).unwrap();

        let ct = border(&m, None).unwrap();
        assert_eq!(ct.len(), 1);
        assert_eq!(ct.cell_counts().unwrap(), vec![4]);
    }

    #[test]
    fn square_split_by_angle_gives_four_open_aretes() {
        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(), &[1.0, 1.0]).unwrap();
        let d = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::QUA4));
        m.add_cell(&[a.id(), b.id(), c.id(), d.id()]).unwrap();

        // Four right-angle corners → four open arêtes, one segment each
        // (a closed loop would be a single 4-segment submesh).
        let ar = border(&m, Some(45.0)).unwrap();
        assert_eq!(ar.len(), 4);
        assert_eq!(ar.cell_counts().unwrap(), vec![1, 1, 1, 1]);
    }

    #[test]
    fn collinear_boundary_segments_stay_in_one_arete() {
        // Two unit squares side by side (2×1): the mid nodes on the top and
        // bottom edges are collinear, so those edges are not split at them.
        let coords = Handle::new(Coords::new(2).unwrap());
        let bl = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let bm = Node::create_in(coords.clone(), &[1.0, 0.0]).unwrap();
        let br = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
        let tr = Node::create_in(coords.clone(), &[2.0, 1.0]).unwrap();
        let tm = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
        let tl = Node::create_in(coords.clone(), &[0.0, 1.0]).unwrap();
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::QUA4));
        m.add_cell(&[bl.id(), bm.id(), tm.id(), tl.id()]).unwrap();
        m.add_cell(&[bm.id(), br.id(), tr.id(), tm.id()]).unwrap();

        // Four rectangle corners → four arêtes; the bottom and top runs each
        // carry two collinear segments, the sides one.
        let ar = border(&m, Some(45.0)).unwrap();
        assert_eq!(ar.len(), 4);
        let mut sizes = ar.cell_counts().unwrap();
        sizes.sort_unstable();
        assert_eq!(sizes, vec![1, 1, 2, 2]);
    }

    #[test]
    fn large_angle_keeps_a_triangle_boundary_closed() {
        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.0, 1.0]).unwrap();
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
        m.add_cell(&[a.id(), b.id(), c.id()]).unwrap();

        // Every vertex turns by ≤135°, below a 170° threshold → no corner,
        // so the boundary stays a single closed loop (3 segments).
        let closed = border(&m, Some(170.0)).unwrap();
        assert_eq!(closed.len(), 1);
        assert_eq!(closed.cell_counts().unwrap(), vec![3]);

        // A small threshold does split it, into three open arêtes.
        let split = border(&m, Some(30.0)).unwrap();
        assert_eq!(split.len(), 3);
        assert_eq!(split.cell_counts().unwrap(), vec![1, 1, 1]);
    }

    #[test]
    fn grid_with_hole_gives_two_loops() {
        // 3×3 grid of QUA4 with the centre cell removed: outer loop (12
        // segments) + inner hole loop (4 segments).
        let coords = Handle::new(Coords::new(2).unwrap());
        let mut ids = Vec::new();
        for j in 0..4 {
            for i in 0..4 {
                ids.push(
                    Node::create_in(coords.clone(), &[i as f64, j as f64])
                        .unwrap()
                        .id(),
                );
            }
        }
        let at = |i: usize, j: usize| ids[j * 4 + i];
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::QUA4));
        for j in 0..3 {
            for i in 0..3 {
                if i == 1 && j == 1 {
                    continue; // drill the hole
                }
                // CCW: (i,j)(i+1,j)(i+1,j+1)(i,j+1)
                m.add_cell(&[at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)])
                    .unwrap();
            }
        }

        let ct = border(&m, None).unwrap();
        assert_eq!(ct.len(), 2, "outer loop + hole loop");
        let mut sizes = ct.cell_counts().unwrap();
        sizes.sort_unstable();
        assert_eq!(sizes, vec![4, 12]);

        // Outer loop CCW (area > 0), hole loop CW (area < 0).
        let areas: Vec<f64> = (0..2)
            .map(|s| signed_area(&coords, &loop_of(&ct, s)))
            .collect();
        assert!(areas.iter().any(|&a| a > 0.0), "an outer (CCW) loop");
        assert!(areas.iter().any(|&a| a < 0.0), "a hole (CW) loop");
    }

    #[test]
    fn reuses_nodes_and_increfs() {
        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.0, 1.0]).unwrap();
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
        m.add_cell(&[a.id(), b.id(), c.id()]).unwrap();

        // a: TRI3 + Node = 2 before contour.
        assert_eq!(coords.read().refcount(a.id()), 2);
        let ct = border(&m, None).unwrap();
        // Boundary SEG2 references a in two segments (incoming + outgoing).
        assert_eq!(coords.read().refcount(a.id()), 4);
        drop(ct);
        assert_eq!(coords.read().refcount(a.id()), 2);
    }

    #[test]
    fn a_zone_listed_twice_is_refused() {
        // Twice the same zone puts every edge under two cells: the border
        // would come out empty. The entry check refuses it instead.
        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.0, 1.0]).unwrap();
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
        m.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
        let mut twice = Mesh::empty();
        twice.add_sub(m.get(0).unwrap()).unwrap();
        twice.add_sub(m.get(0).unwrap()).unwrap();

        let err = border(&twice, None).unwrap_err().to_string();
        assert!(err.contains("border") && err.contains("same zone"), "{err}");
        // Each zone once, it is a triangle again.
        assert_eq!(
            border(&twice.union(&twice).unwrap(), None)
                .unwrap()
                .cell_count(),
            3
        );
    }

    #[test]
    fn no_surface_cells_is_error() {
        let coords = Handle::new(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
        m.add_cell(&[a.id()]).unwrap();
        assert!(border(&m, None).is_err());
    }

    #[test]
    fn volume_cells_are_rejected() {
        let coords = Handle::new(Coords::new(3).unwrap());
        let ns: Vec<NodeId> = (0..4)
            .map(|k| {
                Node::create_in(coords.clone(), &[k as f64, 0.0, 0.0])
                    .unwrap()
                    .id()
            })
            .collect();
        let mut m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TET4));
        m.add_cell(&ns).unwrap();
        assert!(border(&m, None).is_err());
    }

    /// A 2 × 2 grid of QUA4 on [0, 2]², 9 nodes.
    fn grid_2x2(coords: &Handle<Coords>) -> Mesh {
        let n: Vec<NodeId> = (0..9)
            .map(|k| {
                Node::create_in(coords.clone(), &[(k % 3) as f64, (k / 3) as f64])
                    .unwrap()
                    .id()
            })
            .collect();
        let mut sm = SubMesh::new(coords.clone(), ElementType::QUA4);
        for (i, j) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
            let k = 3 * j + i;
            sm.add_cell(&[n[k], n[k + 1], n[k + 4], n[k + 3]]).unwrap();
        }
        Mesh::from_submesh(sm)
    }

    #[test]
    fn quadratic_surface_border_is_seg3_on_its_own_mid_nodes() {
        // The border of the promoted grid and the promoted border of the
        // grid: same segments, mid-nodes at the same places — and the SEG3
        // re-use the surface's own mid-nodes, they create none.
        use crate::ops::mesh::to_quadratic;
        let coords = Handle::new(Coords::new(2).unwrap());
        let grid = grid_2x2(&coords);
        let quad = to_quadratic(&grid).unwrap();
        let from_quad = border(&quad, None).unwrap();
        let promoted = to_quadratic(&border(&grid, None).unwrap()).unwrap();
        assert_eq!(from_quad.element_types().unwrap(), vec![ElementType::SEG3]);
        assert_eq!(from_quad.cell_count(), 8);
        let surface_nodes: std::collections::HashSet<NodeId> = quad
            .get(0)
            .unwrap()
            .read()
            .connectivity()
            .iter()
            .copied()
            .collect();
        for c in 0..8 {
            for k in 0..3 {
                let a = from_quad.node(0, c, k).unwrap();
                let b = promoted.node(0, c, k).unwrap();
                assert_eq!(
                    a.position().unwrap(),
                    b.position().unwrap(),
                    "cell {c}, node {k}"
                );
                assert!(surface_nodes.contains(&a.id()));
            }
        }
        // Split at the corners, the arêtes stay SEG3.
        let sides = border(&quad, Some(45.0)).unwrap();
        assert_eq!(sides.len(), 4);
        assert_eq!(sides.element_types().unwrap(), vec![ElementType::SEG3; 4]);
    }

    #[test]
    fn linear_and_quadratic_surfaces_are_not_bordered_together() {
        use crate::ops::mesh::to_quadratic;
        let coords = Handle::new(Coords::new(2).unwrap());
        let grid = grid_2x2(&coords);
        let other = to_quadratic(&grid_2x2(&coords)).unwrap();
        let mixed = grid.union(&other).unwrap();
        let err = border(&mixed, None).unwrap_err();
        assert!(err.to_string().contains("linear and quadratic"));
    }
}