pyrucast 0.1.3

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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
//! Mesh — collection of homogeneous submeshes (one element type per
//! submesh).
//!
//! Hierarchy:
//!
//! - [`SubMesh`] — every cell of a single [`ElementType`]. Stores the
//!   connectivity flat (`Vec<NodeId>`, length `cell_count * nodes_per_cell`).
//!   RAII referencing: `add_cell` increments the node refcounts in the
//!   `Coords`; the `SubMesh`'s `Drop` decrements every referenced
//!   node.
//! - [`Mesh`] — aggregate of SubMeshes attached to the same `Coords`.
//!
//! The POI1 case is deliberately degenerate: a POI1 submesh is exactly a
//! list of nodes.
//!
//! # Example
//!
//! ```
//! use pyrucast::containers::mesh::Coords;
//! use pyrucast::containers::mesh::ElementType;
//! use pyrucast::containers::mesh::SubMesh;
//! use pyrucast::containers::mesh::Node;
//! use pyrucast::store::{insert, read};
//!
//! let coords = insert(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();
//! assert_eq!(sm.cell_count(), 1);
//!
//! // The SubMesh holds refs on the 3 nodes, in addition to the `Node`s.
//! assert_eq!(read(&coords).unwrap().refcount(a.id()), 2);
//! drop(sm);  // decrements the referenced nodes
//! assert_eq!(read(&coords).unwrap().refcount(a.id()), 1);
//! ```

pub mod cell;
pub mod color;
pub mod coords;
pub mod element_type;
pub mod node;
pub mod point;

// Flat re-exports: the public types of this module are reachable as
// `mesh::Cell`, `mesh::Coords`, … alongside the `SubMesh` / `Mesh`
// defined here, instead of through their defining sub-module.
pub use cell::{Cell, CellIter};
pub use color::RgbColor;
pub use coords::{Coords, NodeId};
pub use element_type::ElementType;
pub use node::Node;
pub use point::{Point2, Point3, Vector2, Vector3};

use crate::aggregate::Aggregate;
use crate::error::{PyrucastError, Result};
use crate::store::{insert, read, write, Handle};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::sync::OnceLock;

// ─── SubMesh ────────────────────────────────────────────────────────────────

/// Submesh: every cell of a single [`ElementType`].
///
/// The connectivity is stored flat; each cell occupies
/// `element_type.nodes_per_cell()` contiguous entries.
///
/// A [`RgbColor`] is attached as the **face colour** used by the
/// visualization layer (`viz` feature); it has no effect on numerics and
/// defaults to a light blue.
#[derive(Serialize, Deserialize)]
pub struct SubMesh {
    element_type: ElementType,
    coords: Handle<Coords>,
    /// Flat connectivity: cell `i` occupies `[i*npc, (i+1)*npc)`.
    connectivity: Vec<NodeId>,
    /// Face colour used by the viz layer. `serde(default)` keeps older
    /// snapshots (without the field) readable.
    #[serde(default)]
    face_color: RgbColor,
    /// Once **sealed**, the connectivity is frozen: [`SubMesh::add_cell`] and
    /// [`SubMesh::add_cell_taking`] refuse to run. A submesh is sealed the
    /// first time a non-mesh consumer (finite-element space, field, matrix, …)
    /// captures its handle, so those consumers can never be left referencing
    /// stale cells. The seal is permanent for the object's lifetime.
    /// `serde(default)` keeps older snapshots (without the field) readable.
    #[serde(default)]
    sealed: bool,
    /// Lazily-built `NodeId → index` map over the **distinct** nodes of the
    /// connectivity, in first-appearance order. Consumers that need a node
    /// lookup (node fields, …) read it in place while holding their store
    /// guard on this submesh — no copy — so the O(n) build is paid once and
    /// mutualised across every field on this support. Not serialized — it is
    /// derived from `connectivity` and rebuilt on demand after a reload. Only
    /// ever populated once the submesh is sealed (its connectivity frozen),
    /// so it can never go stale.
    #[serde(skip)]
    node_index: OnceLock<HashMap<NodeId, usize>>,
    /// Lazily-built **canonical POI1 companion**: the node cloud of this
    /// submesh's distinct nodes, materialised once and shared. Every consumer
    /// that projects this submesh to its nodes ([`SubMesh::to_poi1`]) gets the
    /// *same* store slot, so their node fields pair under
    /// [`same_support`](crate::containers::field::SubField::same_support) — a
    /// stiffness block's support, a `restrict` onto this mesh, and a
    /// `divergence`/`flux` output over it all land on one handle and combine
    /// directly. Not serialized (derived from `connectivity`, rebuilt on
    /// demand). Only ever populated once the submesh is sealed, so it can never
    /// go stale.
    #[serde(skip)]
    poi1_companion: OnceLock<Handle<SubMesh>>,
}

impl SubMesh {
    /// Create an empty submesh for the given element type, attached to `coords`.
    pub fn new(coords: Handle<Coords>, element_type: ElementType) -> Self {
        Self {
            element_type,
            coords,
            connectivity: Vec::new(),
            face_color: RgbColor::default(),
            sealed: false,
            node_index: OnceLock::new(),
            poi1_companion: OnceLock::new(),
        }
    }

    /// Whether this submesh is sealed (connectivity frozen).
    pub fn is_sealed(&self) -> bool {
        self.sealed
    }

    /// `NodeId → index` map over the **distinct** nodes of the connectivity,
    /// in first-appearance order (the order [`SubNodeField`](crate::containers::node_field::SubNodeField) snapshots its
    /// support in). Built once and cached; callers keep their read guard on
    /// this submesh while using the returned reference — no copy.
    ///
    /// Meant for sealed supports: the map is derived from `connectivity`, and
    /// a sealed submesh can no longer grow, so the cache can never go stale.
    /// (It is only ever queried through a sealed support in practice.)
    pub fn node_index(&self) -> &HashMap<NodeId, usize> {
        self.node_index.get_or_init(|| {
            let mut map = HashMap::with_capacity(self.connectivity.len());
            for &nid in &self.connectivity {
                let next = map.len();
                map.entry(nid).or_insert(next);
            }
            map
        })
    }

    /// Seal this submesh: freeze its connectivity permanently. After this,
    /// [`SubMesh::add_cell`] / [`SubMesh::add_cell_taking`] return
    /// [`PyrucastError::MeshSealed`]. Idempotent.
    ///
    /// Called by the container layer whenever a non-mesh object captures the
    /// submesh — see the free function [`seal`]. A bare [`Mesh`] holding the
    /// submesh does **not** seal it (a mesh may keep growing until consumed).
    pub fn seal(&mut self) {
        self.sealed = true;
    }

    /// Face colour used when this submesh is drawn (no numerical effect).
    pub fn face_color(&self) -> RgbColor {
        self.face_color
    }

    /// Replace the face colour used when this submesh is drawn.
    pub fn set_face_color(&mut self, color: RgbColor) {
        self.face_color = color;
    }

    /// Add a cell. The length of `nodes` must equal
    /// `element_type.nodes_per_cell()`, and each node must be alive in the
    /// `Coords`; each node is increfed. On increment failure
    /// (invalid / collected id), the increfs already performed for this
    /// cell are rolled back.
    pub fn add_cell(&mut self, nodes: &[NodeId]) -> Result<usize> {
        if self.sealed {
            return Err(PyrucastError::MeshSealed);
        }
        let npc = self.element_type.nodes_per_cell();
        if nodes.len() != npc {
            return Err(PyrucastError::Message(format!(
                "add_cell({}): expected {} nodes, got {}",
                self.element_type,
                npc,
                nodes.len()
            )));
        }
        {
            let mut c = write(&self.coords)?;
            for (acquired, &n) in nodes.iter().enumerate() {
                if let Err(e) = c.incref(n) {
                    // Roll back the increfs already done for this cell.
                    for &m in &nodes[..acquired] {
                        let _ = c.decref(m);
                    }
                    return Err(e);
                }
            }
        }
        let idx = self.connectivity.len() / npc;
        self.connectivity.extend_from_slice(nodes);
        Ok(idx)
    }

    /// Add a cell whose nodes are **already owned** by the caller (one
    /// refcount unit per node). The SubMesh adopts those units without
    /// increfing further; its `Drop` will decref as usual, which
    /// balances the donation.
    ///
    /// Typical use: a freshly created node (`Coords::add_node`
    /// returns refcount = 1) is handed directly to a POI1 SubMesh which
    /// then becomes its sole owner.
    ///
    /// The caller is responsible for the ownership claim; this method
    /// only checks that the cell length matches the element type and
    /// that the nodes are alive at the moment of the call.
    pub fn add_cell_taking(&mut self, nodes: &[NodeId]) -> Result<usize> {
        if self.sealed {
            return Err(PyrucastError::MeshSealed);
        }
        let npc = self.element_type.nodes_per_cell();
        if nodes.len() != npc {
            return Err(PyrucastError::Message(format!(
                "add_cell_taking({}): expected {} nodes, got {}",
                self.element_type,
                npc,
                nodes.len()
            )));
        }
        {
            let c = read(&self.coords)?;
            for &n in nodes {
                if !c.is_alive(n) {
                    return Err(PyrucastError::Message(format!(
                        "add_cell_taking: node {} is not alive",
                        n
                    )));
                }
            }
        }
        let idx = self.connectivity.len() / npc;
        self.connectivity.extend_from_slice(nodes);
        Ok(idx)
    }

    /// Deep-copy this submesh into a **fresh, unsealed** one: same element
    /// type, same `Coords`, same connectivity (each referenced node increfed
    /// anew) and same face colour — but never inheriting the seal.
    ///
    /// This is the escape hatch for the seal: once a consumer has frozen a
    /// submesh, `duplicate()` hands back an independent copy you can keep
    /// editing with [`SubMesh::add_cell`]. The two share the same `Coords`
    /// (nodes are not cloned, only their refcounts bumped).
    pub fn duplicate(&self) -> Result<SubMesh> {
        let mut copy = SubMesh::new(self.coords.clone(), self.element_type);
        copy.face_color = self.face_color;
        let npc = self.element_type.nodes_per_cell();
        if npc > 0 {
            for chunk in self.connectivity.chunks(npc) {
                // `copy` is unsealed, so `add_cell` runs and increfs the
                // nodes (with rollback on failure).
                copy.add_cell(chunk)?;
            }
        }
        Ok(copy)
    }

    /// Element type of the submesh.
    pub fn element_type(&self) -> ElementType {
        self.element_type
    }

    /// Number of cells in the submesh.
    pub fn cell_count(&self) -> usize {
        self.connectivity.len() / self.element_type.nodes_per_cell()
    }

    /// Flat connectivity buffer (all cells concatenated).
    pub(crate) fn connectivity(&self) -> &[NodeId] {
        &self.connectivity
    }

    /// Handle to the owning `Coords` (internal clone).
    pub fn coords(&self) -> Handle<Coords> {
        self.coords.clone()
    }

    /// Build a POI1 submesh with **one cell per [`Node`]**, in the given
    /// order. The [`Coords`] is taken from the nodes themselves
    /// (every [`Node`] carries its own — project convention). Errors if
    /// `nodes` is empty (no Coords to attach to).
    ///
    /// Lower-level form when you already hold the ids and the coords:
    /// [`SubMesh::poi1_from_node_ids`].
    pub fn poi1_from_nodes(nodes: &[Node]) -> Result<SubMesh> {
        let coords = nodes
            .first()
            .ok_or_else(|| {
                PyrucastError::Message("SubMesh::poi1_from_nodes: nodes must not be empty".into())
            })?
            .coords();
        let ids: Vec<NodeId> = nodes.iter().map(|n| n.id()).collect();
        SubMesh::poi1_from_node_ids(coords, &ids)
    }

    /// Build a POI1 submesh with **one cell per node id** in `nodes`, in the
    /// given order. Each node is increfed; on failure the partial submesh's
    /// `Drop` rolls back the increfs already done. The caller is responsible
    /// for any de-duplication (see [`SubMesh::to_poi1`] for the deduped
    /// variant) and supplies the owning `coords` explicitly. When you have
    /// [`Node`] objects, prefer [`SubMesh::poi1_from_nodes`].
    pub fn poi1_from_node_ids(coords: Handle<Coords>, nodes: &[NodeId]) -> Result<SubMesh> {
        let mut sm = SubMesh::new(coords, ElementType::POI1);
        for &nid in nodes {
            sm.add_cell(&[nid])?;
        }
        Ok(sm)
    }

    /// Canonical POI1 node cloud of this submesh — its nodes **de-duplicated in
    /// order of first appearance** (one POI1 cell per unique node), as a sealed
    /// [`SubMesh`] handle.
    ///
    /// **Cached, per submesh.** Once `self` is sealed the companion is built at
    /// most once and every later call returns the *same* store slot, so all the
    /// node fields that project this submesh to its nodes pair under
    /// [`same_support`](crate::containers::field::SubField::same_support): a
    /// stiffness block's support (built this way in every physics' `new`), a
    /// [`restrict`](fn@crate::ops::field::restrict) onto this mesh, and a
    /// `divergence`/`flux`/`internal_forces` output over it all share one handle
    /// and combine directly by the field operators. This is what lets
    /// `solve(K, f) - restrict(g, mesh)` and `&K * &restrict(f, mesh)` line up.
    ///
    /// On an **unsealed** submesh nothing is cached — a fresh cloud is returned
    /// each call (the old behaviour), since the connectivity could still change
    /// and stale the companion. Shared building block:
    /// [`crate::ops::mesher::to_poi1()`] applies it submesh-by-submesh.
    pub fn to_poi1(&self) -> Result<Handle<SubMesh>> {
        if let Some(h) = self.poi1_companion.get() {
            return Ok(h.clone());
        }
        let mut seen: Vec<NodeId> = Vec::new();
        for &nid in &self.connectivity {
            if !seen.contains(&nid) {
                seen.push(nid);
            }
        }
        // Build (write-locks `Coords`) and seal the companion. `self` is behind
        // the caller's read guard on this submesh — a different slot than the
        // POI1 companion and `Coords` — so no lock inversion (same discipline
        // the previous `insert(read(sm)?.to_poi1()?)` idiom already relied on).
        let handle = insert(SubMesh::poi1_from_node_ids(self.coords.clone(), &seen)?);
        seal(&handle)?;
        if self.sealed {
            // Frozen source ⇒ safe to memoize. On a race the loser drops its
            // build and everyone reads the winner's slot.
            let _ = self.poi1_companion.set(handle);
            Ok(self
                .poi1_companion
                .get()
                .expect("populated on this path")
                .clone())
        } else {
            Ok(handle)
        }
    }

    /// Visualize this submesh.
    ///
    /// - `view = None` ⇒ [`crate::viz::View::default`] (isometric).
    /// - `save = None` ⇒ open an interactive window (requires feature
    ///   `viz-interactive`).
    /// - `save = Some(path)` ⇒ write an image file; the format is inferred
    ///   from the extension (`.png` or `.svg`).
    ///
    /// Every supported element type is rendered: POI1 as dots, SEG2 as
    /// segments, TRI3 / QUA4 as filled polygons, and TET4 / HEX8 as their
    /// outer skin (boundary faces) under the painter's algorithm.
    #[cfg(feature = "viz")]
    pub fn plot(
        &self,
        view: Option<crate::viz::View>,
        save: Option<&std::path::Path>,
    ) -> Result<()> {
        self.plot_styled(view, save, crate::viz::MeshStyle::default())
    }

    /// Like [`SubMesh::plot`] but choosing the [`crate::viz::MeshStyle`]:
    /// `Surface` (opaque skin) or `Wireframe` (all edges, see-through).
    #[cfg(feature = "viz")]
    pub fn plot_styled(
        &self,
        view: Option<crate::viz::View>,
        save: Option<&std::path::Path>,
        style: crate::viz::MeshStyle,
    ) -> Result<()> {
        crate::viz::render_submesh_styled(self, view, save, style)
    }
}

/// Seal the submesh behind `handle`, freezing its connectivity.
///
/// This is the seam every non-mesh consumer goes through when it captures a
/// [`SubMesh`] handle (finite-element space, node field, matrix support, …):
/// from that point on the submesh can no longer grow, so the consumer's
/// cell-indexed view can never go stale. Idempotent; returns the same handle
/// (cloned) for ergonomic chaining at a constructor's capture site.
///
/// **Already-sealed fast path takes only a read lock.** This matters now that
/// [`SubMesh::to_poi1`] is cached: a `restrict` onto a mesh can land on the very
/// support a source field already sits on (the shared POI1 companion), so
/// `from_poi1` may `seal` a support while the caller still holds a *read* guard
/// on it (a field `view`). Sealing is idempotent, so when the submesh is already
/// sealed we skip the write entirely — a read lock coexists with that reader,
/// whereas a write lock would deadlock against it. Taking a write lock while a
/// **write** guard on the same slot is held is still a deadlock (the slot lock is
/// not reentrant — see [`crate::store`]); only the sealed-read case is relaxed.
pub fn seal(handle: &Handle<SubMesh>) -> Result<Handle<SubMesh>> {
    if read(handle)?.is_sealed() {
        return Ok(handle.clone());
    }
    write(handle)?.seal();
    Ok(handle.clone())
}

impl Drop for SubMesh {
    fn drop(&mut self) {
        // One lock acquisition for all decrefs.
        if let Ok(mut c) = write(&self.coords) {
            for &n in &self.connectivity {
                let _ = c.decref(n);
            }
        }
    }
}

impl fmt::Debug for SubMesh {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Bounded structure only — the per-cell connectivity lives in `dump()`.
        f.debug_struct("SubMesh")
            .field("element_type", &self.element_type)
            .field("coords", &self.coords)
            .field("cell_count", &self.cell_count())
            .field("face_color", &self.face_color)
            .field("sealed", &self.sealed)
            .finish()
    }
}

impl fmt::Display for SubMesh {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "SubMesh<{}>: {} cell(s)",
            self.element_type,
            self.cell_count()
        )
    }
}

impl crate::dump::Dump for SubMesh {
    fn render(&self, opts: &crate::dump::DumpOptions) -> String {
        use crate::dump::table;
        let npc = self.element_type.nodes_per_cell();
        let mut headers = vec!["cell".to_string()];
        headers.extend((0..npc).map(|i| format!("n{i}")));
        let rows: Vec<Vec<String>> = if npc > 0 {
            self.connectivity
                .chunks(npc)
                .enumerate()
                .map(|(i, chunk)| {
                    let mut row = vec![i.to_string()];
                    row.extend(chunk.iter().map(|nid| nid.to_string()));
                    row
                })
                .collect()
        } else {
            Vec::new()
        };
        format!("{self}\n{}", table(&headers, &rows, opts))
    }
}

// ─── Mesh ───────────────────────────────────────────────────────────────────

/// Mesh: aggregate of submeshes. Each submesh carries its own
/// `Handle<Coords>`; the mesh itself imposes no constraint on
/// `Coords` homogeneity.
#[derive(Serialize, Deserialize, Default)]
pub struct Mesh {
    subs: Vec<Handle<SubMesh>>,
}

crate::impl_aggregate!(Mesh, SubMesh, submesh, "submesh(es)", {
    fn display_extra(&self) -> Option<String> {
        Some(format!(
            ", {} cell(s) total",
            self.cell_count().unwrap_or(0)
        ))
    }
    fn check_push(&self, h: &Handle<SubMesh>) -> Result<()> {
        if self.is_empty() {
            return Ok(());
        }
        let a = self.coords()?;
        let b = read(h)?.coords();
        if a.index() != b.index() || a.generation() != b.generation() {
            Err(PyrucastError::Message("mismatched Coords".into()))
        } else {
            Ok(())
        }
    }
});

crate::impl_aggregate_dump!(Mesh);

// ─── Building POI1 point meshes by union ─────────────────────────────────────
//
// `node.union(node)` and (unitary POI1) `mesh.union_node(node)` both yield a
// fresh unitary POI1 `Mesh` — a points mesh grown one node at a time. Exposed
// to Python as `node | node` and `mesh | node` (the same `|` as the
// aggregates' union). See also [`SubMesh::poi1_from_nodes`].

impl Node {
    /// `node.union(other)` → a unitary POI1 [`Mesh`] over both nodes.
    /// Python: `node | node`.
    pub fn union(&self, other: &Node) -> Result<Mesh> {
        let sm = SubMesh::poi1_from_nodes(&[self.clone(), other.clone()])?;
        Ok(Mesh::from_submesh(sm))
    }
}

impl Mesh {
    /// `mesh.union_node(node)` → a unitary POI1 [`Mesh`] holding this mesh's
    /// points plus `node`. Errors unless `self` is **unitary and POI1**
    /// (exactly one POI1 submesh). Python: `mesh | node`.
    pub fn union_node(&self, node: &Node) -> Result<Mesh> {
        let sub = self.unit()?;
        let (et, coords, mut ids) = {
            let s = read(&sub)?;
            (s.element_type(), s.coords(), s.connectivity().to_vec())
        };
        if et != ElementType::POI1 {
            return Err(PyrucastError::Message(
                "Mesh | Node: expected a unitary POI1 mesh".into(),
            ));
        }
        ids.push(node.id());
        Ok(Mesh::from_submesh(SubMesh::poi1_from_node_ids(
            coords, &ids,
        )?))
    }
}

impl Mesh {
    /// Total cells in the mesh (sum across submeshes).
    pub fn cell_count(&self) -> Result<usize> {
        let mut total = 0usize;
        for sm in self {
            total += read(sm)?.cell_count();
        }
        Ok(total)
    }

    /// Handle to the `Coords` of the first submesh.
    ///
    /// Returns an error if the mesh has no submeshes.
    pub fn coords(&self) -> Result<Handle<Coords>> {
        let sm = self
            .items()
            .first()
            .ok_or_else(|| PyrucastError::Message("coords: mesh has no submeshes".into()))?;
        Ok(read(sm)?.coords())
    }

    /// Create a mesh wrapping a single `SubMesh`. Config-free at the Mesh
    /// level: the submesh already carries its `Coords` (a Mesh is a
    /// pure aggregate of submeshes). The submesh is moved into the store.
    pub fn from_submesh(sub: SubMesh) -> Self {
        let mut mesh = Self::default();
        mesh.subs.push(insert(sub));
        mesh
    }

    /// Deep-copy the whole mesh: every submesh is [`SubMesh::duplicate`]d
    /// into a fresh, unsealed submesh under a new handle. The copy is fully
    /// editable even when the source's submeshes have been sealed by their
    /// consumers; nodes are shared (same `Coords`), only their refcounts grow.
    pub fn duplicate(&self) -> Result<Mesh> {
        let mut copy = Self::default();
        for sm in self {
            let dup = read(sm)?.duplicate()?;
            copy.subs.push(insert(dup));
        }
        Ok(copy)
    }

    /// Add a cell directly when the mesh has exactly one submesh.
    pub fn add_cell(&mut self, nodes: &[NodeId]) -> Result<usize> {
        if self.len() != 1 {
            return Err(PyrucastError::Message(
                "add_cell: mesh must have exactly one submesh".into(),
            ));
        }
        write(&self.subs[0])?.add_cell(nodes)
    }

    /// Element type of each submesh, in order.
    pub fn element_types(&self) -> Result<Vec<ElementType>> {
        self.iter().map(|sm| Ok(read(sm)?.element_type())).collect()
    }

    /// Cell count of each submesh, in order.
    pub fn cell_counts(&self) -> Result<Vec<usize>> {
        self.iter().map(|sm| Ok(read(sm)?.cell_count())).collect()
    }

    /// Node at position `node_idx` in cell `cell_idx` of submesh `submesh_idx`.
    pub fn node(&self, submesh_idx: usize, cell_idx: usize, node_idx: usize) -> Result<Node> {
        let sm = self.get(submesh_idx)?;
        let (nid, coords) = {
            let s = read(&sm)?;
            let npc = s.element_type.nodes_per_cell();
            let n = s.cell_count();
            if cell_idx >= n {
                return Err(PyrucastError::Message(format!(
                    "node: cell index {} ≥ cell_count {}",
                    cell_idx, n
                )));
            }
            let nid = s
                .connectivity()
                .get(cell_idx * npc + node_idx)
                .copied()
                .ok_or_else(|| {
                    PyrucastError::Message(format!(
                        "node: node index {} ≥ nodes_per_cell {}",
                        node_idx, npc
                    ))
                })?;
            (nid, s.coords())
        };
        Node::acquire(coords, nid)
    }

    /// Return a `Cell` view on cell `cell_idx` of submesh `submesh_idx`.
    pub fn cell(&self, submesh_idx: usize, cell_idx: usize) -> Result<Cell> {
        let sm = self.get(submesh_idx)?;
        Cell::new(sm, cell_idx)
    }

    /// Iterator over every cell of submesh `submesh_idx`.
    pub fn cells(&self, submesh_idx: usize) -> Result<CellIter> {
        let sm = self.get(submesh_idx)?;
        let end = read(&sm)?.cell_count();
        Ok(CellIter::new(sm, end))
    }

    /// Visualize this mesh — every submesh is drawn, each in its own
    /// [`SubMesh::face_color`]. See [`SubMesh::plot`] for the meaning of
    /// `view` and `save` and the supported element types.
    #[cfg(feature = "viz")]
    pub fn plot(
        &self,
        view: Option<crate::viz::View>,
        save: Option<&std::path::Path>,
    ) -> Result<()> {
        self.plot_styled(view, save, crate::viz::MeshStyle::default())
    }

    /// Like [`Mesh::plot`] but choosing the [`crate::viz::MeshStyle`]:
    /// `Surface` (opaque skin) or `Wireframe` (all edges, see-through).
    /// Each submesh is drawn in its own `face_color`.
    #[cfg(feature = "viz")]
    pub fn plot_styled(
        &self,
        view: Option<crate::viz::View>,
        save: Option<&std::path::Path>,
        style: crate::viz::MeshStyle,
    ) -> Result<()> {
        crate::viz::render_mesh_styled(self, view, save, style)
    }

    /// Visualize this mesh coloured by a field component — a
    /// [`crate::containers::node_field::NodeField`] **or** an
    /// [`crate::containers::element_field::ElementField`], uniformly via
    /// [`crate::viz::FieldArg`].
    ///
    /// Per-cell colour comes from the cell's nodal values (read directly
    /// for a node field; fitted per element from the Gauss values for an
    /// element field — inter-element discontinuities stay visible).
    /// `component = None` selects the field's first component.
    ///
    /// The interactive window draws a clickable button at the top
    /// showing the current component and value range; clicking it (or
    /// pressing `Tab`) cycles through the field's components. A colorbar
    /// is drawn on the right edge; `scale` pins its bounds (default:
    /// the data's own min/max).
    ///
    /// For a single submesh, use
    /// [`crate::viz::render_submesh_with_field`] with the submesh handle.
    #[cfg(feature = "viz")]
    pub fn plot_with_field(
        &self,
        view: Option<crate::viz::View>,
        save: Option<&std::path::Path>,
        field: crate::viz::FieldArg<'_>,
        component: Option<&str>,
        scale: crate::viz::ColorScale,
        smooth: usize,
    ) -> Result<()> {
        crate::viz::render_mesh_with_field(self, field, component, scale, smooth, view, save)
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::store::insert;

    #[test]
    fn submesh_poi1_is_node_list() {
        let coords = insert(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 mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
        sm.add_cell(&[a.id()]).unwrap();
        sm.add_cell(&[b.id()]).unwrap();
        assert_eq!(sm.cell_count(), 2);
        assert_eq!(sm.connectivity()[0], a.id());
        assert_eq!(sm.connectivity()[1], b.id());
    }

    #[test]
    fn poi1_from_nodes_derives_config_and_builds() {
        let coords = insert(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();

        // Node-based form: Coords is taken from the nodes themselves.
        let sm = SubMesh::poi1_from_nodes(&[a.clone(), b.clone()]).unwrap();
        assert_eq!(sm.element_type(), ElementType::POI1);
        assert_eq!(sm.cell_count(), 2);
        assert_eq!(sm.connectivity(), &[a.id(), b.id()]);
        // Matches the id-based form on the same nodes.
        let sm2 = SubMesh::poi1_from_node_ids(coords.clone(), &[a.id(), b.id()]).unwrap();
        assert_eq!(sm.connectivity(), sm2.connectivity());
    }

    #[test]
    fn poi1_from_nodes_empty_is_error() {
        assert!(SubMesh::poi1_from_nodes(&[]).is_err());
    }

    #[test]
    fn submesh_tri3_increfs_and_drop_decrefs() {
        let coords = insert(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();
        // SubMesh increfed each of the 3 nodes, in addition to the Nodes.
        {
            let cf = read(&coords).unwrap();
            assert_eq!(cf.refcount(a.id()), 2);
            assert_eq!(cf.refcount(b.id()), 2);
            assert_eq!(cf.refcount(c.id()), 2);
        }
        drop(sm);
        {
            let cf = read(&coords).unwrap();
            assert_eq!(cf.refcount(a.id()), 1);
            assert_eq!(cf.refcount(b.id()), 1);
            assert_eq!(cf.refcount(c.id()), 1);
        }
    }

    #[test]
    fn node_index_maps_distinct_nodes_in_first_appearance_order() {
        let coords = insert(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();

        // Two QUA4 cells sharing the edge (b, c): b and c appear twice.
        let mut sm = SubMesh::new(coords.clone(), ElementType::QUA4);
        sm.add_cell(&[a.id(), b.id(), c.id(), d.id()]).unwrap();
        let e = Node::create_in(coords.clone(), &[2.0, 0.0]).unwrap();
        let f = Node::create_in(coords.clone(), &[2.0, 1.0]).unwrap();
        sm.add_cell(&[b.id(), e.id(), f.id(), c.id()]).unwrap();

        let map = sm.node_index();
        // Distinct nodes, indexed by first appearance in the connectivity.
        assert_eq!(map.len(), 6);
        assert_eq!(map[&a.id()], 0);
        assert_eq!(map[&b.id()], 1);
        assert_eq!(map[&c.id()], 2);
        assert_eq!(map[&d.id()], 3);
        assert_eq!(map[&e.id()], 4);
        assert_eq!(map[&f.id()], 5);
        // Cached: a second call returns the same populated map.
        assert_eq!(sm.node_index().len(), 6);
    }

    #[test]
    fn sealed_submesh_refuses_add_cell() {
        let coords = insert(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 mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
        sm.add_cell(&[a.id()]).unwrap();
        assert!(!sm.is_sealed());
        sm.seal();
        assert!(sm.is_sealed());
        // Both mutating paths are now blocked with MeshSealed.
        assert!(matches!(
            sm.add_cell(&[b.id()]).unwrap_err(),
            PyrucastError::MeshSealed
        ));
        assert!(matches!(
            sm.add_cell_taking(&[b.id()]).unwrap_err(),
            PyrucastError::MeshSealed
        ));
        assert_eq!(sm.cell_count(), 1);
        // The refused cell left no lingering incref on b.
        assert_eq!(read(&coords).unwrap().refcount(b.id()), 1);
    }

    #[test]
    fn seal_via_handle_and_is_idempotent() {
        let coords = insert(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();
        let h = insert({
            let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
            sm.add_cell(&[a.id()]).unwrap();
            sm
        });
        seal(&h).unwrap();
        seal(&h).unwrap(); // idempotent
        assert!(read(&h).unwrap().is_sealed());
        assert!(matches!(
            write(&h).unwrap().add_cell(&[a.id()]).unwrap_err(),
            PyrucastError::MeshSealed
        ));
    }

    #[test]
    fn duplicate_is_unsealed_and_reincrefs() {
        let coords = insert(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();
        sm.seal();

        let mut copy = sm.duplicate().unwrap();
        // Copy carries the same connectivity but is not sealed.
        assert!(!copy.is_sealed());
        assert_eq!(copy.connectivity(), sm.connectivity());
        // Each node is now referenced by the original AND the copy (+ Node).
        {
            let cf = read(&coords).unwrap();
            assert_eq!(cf.refcount(a.id()), 3);
        }
        // The copy is editable even though the source is frozen.
        let d = Node::create_in(coords.clone(), &[1.0, 1.0]).unwrap();
        copy.add_cell(&[a.id(), b.id(), d.id()]).unwrap();
        assert_eq!(copy.cell_count(), 2);
        assert_eq!(sm.cell_count(), 1);
    }

    #[test]
    fn mesh_duplicate_yields_editable_copy() {
        let coords = insert(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 mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
        sm.add_cell(&[a.id()]).unwrap();
        sm.seal();
        let mesh = Mesh::from_submesh(sm);

        let mut copy = mesh.duplicate().unwrap();
        assert_eq!(copy.cell_count().unwrap(), 1);
        // A fresh submesh handle: editable.
        copy.add_cell(&[b.id()]).unwrap();
        assert_eq!(copy.cell_count().unwrap(), 2);
    }

    #[test]
    fn submesh_add_cell_invalid_arity() {
        let coords = insert(Coords::new(2).unwrap());
        let a = Node::create_in(coords.clone(), &[0.0, 0.0]).unwrap();

        let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        let err = sm.add_cell(&[a.id()]).unwrap_err();
        assert!(matches!(err, PyrucastError::Message(_)));
        // No increment should have survived the failure.
        assert_eq!(read(&coords).unwrap().refcount(a.id()), 1);
    }

    #[test]
    fn submesh_add_cell_collected_node_rollback() {
        let coords = insert(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 dead_id = write(&coords).unwrap().add_node(&[2.0]).unwrap();
        // dead_id starts at refcount=1; decrement then collect.
        {
            let mut c = write(&coords).unwrap();
            c.decref(dead_id).unwrap();
            assert_eq!(c.gc(), 1);
        }

        let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        // a (live), b (live), dead_id (collected) → add_cell fails after
        // increfing a and b. The rollback must undo those increfs.
        let err = sm.add_cell(&[a.id(), b.id(), dead_id]).unwrap_err();
        assert!(matches!(err, PyrucastError::Message(_)));
        {
            let cf = read(&coords).unwrap();
            assert_eq!(cf.refcount(a.id()), 1, "a must be rolled back");
            assert_eq!(cf.refcount(b.id()), 1, "b must be rolled back");
        }
        assert_eq!(sm.cell_count(), 0);
    }

    #[test]
    fn mesh_aggregates_submeshes_same_config() {
        let coords = insert(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 cc = Node::create_in(coords.clone(), &[0.5, 1.0]).unwrap();

        let sm_pts = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::POI1);
            sm.add_cell(&[a.id()]).unwrap();
            sm.add_cell(&[b.id()]).unwrap();
            insert(sm)
        };
        let sm_tri = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
            sm.add_cell(&[a.id(), b.id(), cc.id()]).unwrap();
            insert(sm)
        };

        let mut mesh = Mesh::empty();
        mesh.add_sub(sm_pts).unwrap();
        mesh.add_sub(sm_tri).unwrap();
        assert_eq!(mesh.len(), 2);
        assert_eq!(mesh.cell_count().unwrap(), 3); // 2 points + 1 triangle
    }

    #[test]
    fn mesh_element_types_and_cell_counts() {
        let coords = insert(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 m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
        m.add_cell(&[a.id()]).unwrap();
        m.add_cell(&[b.id()]).unwrap();
        let sm_tri = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
            sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
            insert(sm)
        };
        m.add_sub(sm_tri).unwrap();

        assert_eq!(
            m.element_types().unwrap(),
            vec![ElementType::POI1, ElementType::TRI3]
        );
        assert_eq!(m.cell_counts().unwrap(), vec![2, 1]);
    }

    #[test]
    fn mesh_index_and_iter_sugar() {
        let coords = insert(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 m = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
        m.add_cell(&[a.id()]).unwrap();
        let sm_tri = {
            let mut sm = SubMesh::new(coords.clone(), ElementType::TRI3);
            sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
            insert(sm)
        };
        m.add_sub(sm_tri).unwrap();

        let et0 = read(&m[0]).unwrap().element_type();
        let et1 = read(&m[1]).unwrap().element_type();
        assert_eq!(et0, ElementType::POI1);
        assert_eq!(et1, ElementType::TRI3);

        let types: Vec<ElementType> = (&m)
            .into_iter()
            .map(|h| read(h).unwrap().element_type())
            .collect();
        assert_eq!(types, vec![ElementType::POI1, ElementType::TRI3]);
    }

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

        let n = m.node(0, 0, 0).unwrap();
        assert_eq!(n.id(), a.id()); // node 0 of element 0 = a
        assert!(m.node(1, 0, 0).is_err()); // submesh out of bounds
        assert!(m.node(0, 1, 0).is_err()); // cell out of bounds
        assert!(m.node(0, 0, 3).is_err()); // node out of bounds (TRI3: indices 0..2)
    }

    #[test]
    fn mesh_merge_combines_submeshes() {
        let coords = insert(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 m1 = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::POI1));
        m1.add_cell(&[a.id()]).unwrap();
        m1.add_cell(&[b.id()]).unwrap();

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

        let merged = m1.union(&m2).unwrap();
        assert_eq!(merged.len(), 2);
        assert_eq!(merged.cell_count().unwrap(), 3); // 2 POI1 + 1 TRI3
    }

    #[test]
    fn debug_and_display_submesh_and_mesh() {
        let coords = insert(Coords::new(1).unwrap());
        let sm = SubMesh::new(coords.clone(), ElementType::SEG2);
        let d = format!("{:?}", sm);
        let s = format!("{}", sm);
        assert!(d.contains("SubMesh"));
        assert!(s.contains("SEG2"));

        let mesh = Mesh::empty();
        assert!(format!("{:?}", mesh).contains("Mesh"));
        assert!(format!("{}", mesh).contains("submesh"));
    }

    #[test]
    fn aggregate_union_sub_and_sub_union_sub() {
        let coords = insert(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 s1 = insert(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
        let s2 = insert(SubMesh::poi1_from_nodes(std::slice::from_ref(&b)).unwrap());

        // sub | sub → Mesh
        let m = Mesh::union_subs(&s1, &s2).unwrap();
        assert_eq!(m.len(), 2);

        // aggregate | sub → Mesh
        let s3 = insert(SubMesh::poi1_from_nodes(std::slice::from_ref(&a)).unwrap());
        let m2 = m.union_sub(&s3).unwrap();
        assert_eq!(m2.len(), 3);
    }

    #[test]
    fn node_union_node_and_mesh_union_node() {
        let coords = insert(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(), &[2.0, 0.0]).unwrap();

        let m = a.union(&b).unwrap();
        assert_eq!(m.len(), 1);
        assert_eq!(read(&m.unit().unwrap()).unwrap().cell_count(), 2);

        let m2 = m.union_node(&c).unwrap();
        assert_eq!(read(&m2.unit().unwrap()).unwrap().cell_count(), 3);
    }

    #[test]
    fn mesh_union_node_rejects_non_unitary_poi1() {
        let coords = insert(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 tri = Mesh::from_submesh(SubMesh::new(coords.clone(), ElementType::TRI3));
        tri.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
        // Non-POI1 → error.
        assert!(tri.union_node(&a).is_err());
    }

    #[test]
    fn to_poi1_caches_companion_on_a_sealed_submesh() {
        let coords = insert(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 sm = SubMesh::new(coords.clone(), ElementType::TRI3);
        sm.add_cell(&[a.id(), b.id(), c.id()]).unwrap();
        let h = insert(sm);

        // Unsealed: nothing memoized — a fresh cloud each call.
        let u1 = read(&h).unwrap().to_poi1().unwrap();
        let u2 = read(&h).unwrap().to_poi1().unwrap();
        assert!(!u1.same_slot(&u2), "unsealed submesh is not memoized");

        // Sealed: the companion is built once and every call shares its slot.
        seal(&h).unwrap();
        let p1 = read(&h).unwrap().to_poi1().unwrap();
        let p2 = read(&h).unwrap().to_poi1().unwrap();
        assert!(
            p1.same_slot(&p2),
            "sealed submesh memoizes its POI1 companion"
        );
        assert_eq!(read(&p1).unwrap().element_type(), ElementType::POI1);
        assert_eq!(read(&p1).unwrap().cell_count(), 3); // three distinct nodes
    }
}