pyrucast 0.14.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
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
//! Saving and reloading a graph of objects.
//!
//! Writing an object writes everything it needs, and reading gives them back
//! **sharing what they shared**: two fields carried by one support come back as
//! two fields carried by one support, not by two copies of it.
//!
//! ```no_run
//! use pyrucast::archive;
//! # use pyrucast::containers::mesh::Mesh;
//! # fn demo(mesh: &Mesh, temperature: &pyrucast::containers::node_field::NodeField)
//! # -> pyrucast::error::Result<()> {
//! archive::save("etude.pyr", &[
//!     ("maillage fin", mesh as &dyn archive::ArchiveRoot),
//!     ("T (°C)",       temperature),
//!     ("time step", &0.05_f64),
//! ])?;
//!
//! let mut objets = archive::load("etude.pyr")?;
//! let mesh2 = objets.mesh("maillage fin")?;
//! # Ok(())
//! # }
//! ```
//!
//! # What the file carries, and what it does not
//!
//! The rule is **recomputable ⇒ not written**. Every cache and every memoised
//! table stays out: the assembled CSR, the solver's factorization, the cell
//! colouring, the lazy index maps, a submesh's POI1 companion. What comes
//! back rebuilds the caches on demand, exactly as a freshly-built graph would;
//! a reloaded matrix is assembled again (`Matrix::assemble`) before it solves,
//! and a field built on a reloaded mesh lands on a fresh POI1 companion, not on
//! the support of the fields reloaded with it.
//!
//! Reference counts are not written either. Object lifetimes are counted by the
//! `Arc` inside each [`Handle`], which counts itself as
//! `load` hands the handles out. Node counts inside a
//! [`Coords`] are **recounted from zero**: each reloaded
//! sub-mesh re-increments the nodes it uses. The consequence is deliberate —
//! *reloaded nodes are counted only by the objects present in the file*.
//! Saving a bare `Coords` and reloading it gives nodes at count zero, exactly
//! as if the same objects had been rebuilt by hand without keeping a `Node`. A [`Node`](crate::atoms::Node) is an atom of the
//! caller's stack; it is not archived.
//!
//! # Reloading adds, it never replaces
//!
//! There is no global registry: [`load`] builds fresh objects and hands back
//! their handles. Whatever already lives in the session is untouched.
//!
//! # This is a session format, not an exchange format
//!
//! The file is pyrucast's own, versioned, and **breakable before 1.0.0** — an
//! unknown version is refused, never converted. To hand results to another tool,
//! use [`export_vtk`](crate::ops::export), which exists for that.

pub mod portable;
mod registry;
mod scope;

use crate::containers::element_field::{ElementField, SubElementField};
use crate::containers::evolution::{Evolution, SubEvolution};
use crate::containers::finite_element_space::{FiniteElementSpace, SubFiniteElementSpace};
use crate::containers::matrix::{Matrix, SubMatrix};
use crate::containers::mesh::{Mesh, SubMesh};
use crate::containers::model::{Model, SubModel};
use crate::containers::node_field::{NodeField, SubNodeField};
use crate::coords::Coords;
use crate::error::{PyrucastError, Result};
use crate::handle::Handle;
pub use portable::Portable;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::collections::BTreeMap;
use std::path::Path;

/// First eight bytes of every archive.
const MAGIC: &[u8; 8] = b"PYRUCAST";
/// Format number. Bumped on any incompatible change; before 1.0.0 no migration
/// is offered, an unknown number is simply refused.
const FORMAT: u32 = 8;

// ─── What a type must offer to be archived ──────────────────────────────────

/// A type that can be a node of a saved graph.
///
/// [`Portable`] supplies the byte contract — bincode, normalized little-endian,
/// `usize` by value as a variable-width integer, identical on Linux and Windows. This trait adds the two
/// things serde cannot express: a **tag** so a record can be dispatched back to
/// its type on reload, and a **hook** to rebuild what the file deliberately does
/// not carry.
///
/// Nothing here declares which objects an implementor points at: the walk is the
/// serialization itself: `Handle::serialize` interns what it meets. Adding a
/// `Handle` field to a
/// type therefore adds an edge, with nothing to keep in step.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::archive::{self, ArchiveRoot};
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
/// # let mesh = Mesh::from_submesh(sm);
/// # let chemin = std::env::temp_dir()
/// #     .join(format!("pyrucast_doc_{}_arc.pyr", std::process::id()));
/// // What an object must be able to do to enter an archive: name itself with
/// // a name that stays stable as long as the format number does not change.
/// // Every shareable building block implements it.
/// archive::save(&chemin, &[("maillage", &mesh as &dyn ArchiveRoot)])?;
/// assert_eq!(archive::load(&chemin)?["maillage"].type_name(), "Mesh");
/// # let _ = std::fs::remove_file(&chemin);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub trait Archivable: Portable + Any + Send + Sync {
    /// Name of the type in the file. Must be unique, and stable as long as the
    /// format number is.
    const TAG: &'static str;

    /// Called on a freshly decoded object, before anyone can see it.
    ///
    /// The place to rebuild what is recomputable, and the only one.
    fn on_load(&mut self) {}
}

// ─── Simple values ──────────────────────────────────────────────────────────

/// A value that is not a pyrucast object: the time step, the name of a load
/// case, the list of instants.
///
/// Lists are **homogeneous**. Nested lists and dictionaries are out of scope.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::archive::{self, ArchiveRoot};
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
/// # let mesh = Mesh::from_submesh(sm);
/// # let chemin = std::env::temp_dir()
/// #     .join(format!("pyrucast_doc_{}_val.pyr", std::process::id()));
/// # use pyrucast::archive::{Root, Value};
/// // The plain values an archive carries alongside the containers: scalars
/// // and lists, enough to store a set of parameters with the mesh it
/// // describes.
/// archive::save(&chemin, &[("pas", &0.25_f64 as &dyn ArchiveRoot),
///                          ("noms", &vec!["a".to_string()] as &dyn ArchiveRoot)])?;
/// let objets = archive::load(&chemin)?;
/// assert_eq!(objets.float("pas")?, 0.25);
/// assert_eq!(objets.texts("noms")?, vec!["a".to_string()]);
/// assert!(matches!(objets["pas"], Root::Value(Value::Float(_))));
/// # let _ = std::fs::remove_file(&chemin);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum Value {
    Bool(bool),
    Int(i64),
    Float(f64),
    Text(String),
    Bools(Vec<bool>),
    Ints(Vec<i64>),
    Floats(Vec<f64>),
    Texts(Vec<String>),
}

// ─── What comes back ────────────────────────────────────────────────────────

/// One named entry of a reloaded archive.
///
/// The set is **closed**, which is the point: a `match` on it is exhaustive, so
/// a type added to the archive cannot be silently forgotten at the boundary —
/// the Python binding included.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::archive::{self, ArchiveRoot};
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
/// # let mesh = Mesh::from_submesh(sm);
/// # let chemin = std::env::temp_dir()
/// #     .join(format!("pyrucast_doc_{}_root.pyr", std::process::id()));
/// // What an archive can carry at its root: the containers, plus the plain
/// // values. `type_name` names what was found — it is what the messages of a
/// // badly chosen typed accessor quote.
/// archive::save(&chemin, &[("maillage", &mesh as &dyn ArchiveRoot)])?;
/// let objets = archive::load(&chemin)?;
/// assert_eq!(objets["maillage"].type_name(), "Mesh");
/// # let _ = std::fs::remove_file(&chemin);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub enum Root {
    Coords(Handle<Coords>),
    Mesh(Mesh),
    SubMesh(Handle<SubMesh>),
    FiniteElementSpace(FiniteElementSpace),
    SubFiniteElementSpace(Handle<SubFiniteElementSpace>),
    NodeField(NodeField),
    SubNodeField(Handle<SubNodeField>),
    ElementField(ElementField),
    SubElementField(Handle<SubElementField>),
    Evolution(Evolution),
    SubEvolution(Handle<SubEvolution>),
    Model(Model),
    SubModel(Handle<SubModel>),
    Matrix(Matrix),
    SubMatrix(Handle<SubMatrix>),
    /// A simple value rather than a pyrucast object.
    Value(Value),
}

impl Root {
    /// Name of the kind held, for error messages: `"Mesh"`, `"float"`, …
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::archive::{self, ArchiveRoot};
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
    /// # let mesh = Mesh::from_submesh(sm);
    /// # let chemin = std::env::temp_dir()
    /// #     .join(format!("pyrucast_doc_{}_tn.pyr", std::process::id()));
    /// // What an archive can carry at its root: the containers, plus the plain
    /// // values. `type_name` names what was found — it is what the messages of
    /// // a badly chosen typed accessor quote.
    /// archive::save(&chemin, &[("maillage", &mesh as &dyn ArchiveRoot)])?;
    /// let objets = archive::load(&chemin)?;
    /// assert_eq!(objets["maillage"].type_name(), "Mesh");
    /// # let _ = std::fs::remove_file(&chemin);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn type_name(&self) -> &'static str {
        match self {
            Root::Coords(_) => Coords::TAG,
            Root::Mesh(_) => Mesh::TAG,
            Root::SubMesh(_) => SubMesh::TAG,
            Root::FiniteElementSpace(_) => FiniteElementSpace::TAG,
            Root::SubFiniteElementSpace(_) => SubFiniteElementSpace::TAG,
            Root::NodeField(_) => NodeField::TAG,
            Root::SubNodeField(_) => SubNodeField::TAG,
            Root::ElementField(_) => ElementField::TAG,
            Root::SubElementField(_) => SubElementField::TAG,
            Root::Evolution(_) => Evolution::TAG,
            Root::SubEvolution(_) => SubEvolution::TAG,
            Root::Model(_) => Model::TAG,
            Root::SubModel(_) => SubModel::TAG,
            Root::Matrix(_) => Matrix::TAG,
            Root::SubMatrix(_) => SubMatrix::TAG,
            Root::Value(v) => match v {
                Value::Bool(_) => "bool",
                Value::Int(_) => "int",
                Value::Float(_) => "float",
                Value::Text(_) => "str",
                Value::Bools(_) => "list[bool]",
                Value::Ints(_) => "list[int]",
                Value::Floats(_) => "list[float]",
                Value::Texts(_) => "list[str]",
            },
        }
    }
}

impl std::fmt::Debug for Root {
    /// Type and, for a shared object, its short tag — never the contents. A
    /// reloaded mesh may hold millions of cells.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Root::Coords(h) => write!(f, "{h}"),
            Root::SubMesh(h) => write!(f, "{h}"),
            Root::SubFiniteElementSpace(h) => write!(f, "{h}"),
            Root::SubNodeField(h) => write!(f, "{h}"),
            Root::SubElementField(h) => write!(f, "{h}"),
            Root::SubEvolution(h) => write!(f, "{h}"),
            Root::SubModel(h) => write!(f, "{h}"),
            Root::SubMatrix(h) => write!(f, "{h}"),
            Root::Value(v) => write!(f, "{v:?}"),
            other => write!(f, "<{}>", other.type_name()),
        }
    }
}

/// The named objects a [`load`] gave back.
///
/// Dereferences to a `BTreeMap`, so `keys()`, iteration and `len()` are
/// available — and sorted, which is also what makes an archive byte-reproducible.
/// The typed accessors ([`mesh`](Objects::mesh), …) exist to give an error that
/// names the key, the type expected and the type found.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::archive::{self, ArchiveRoot};
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
/// # let mesh = Mesh::from_submesh(sm);
/// # let chemin = std::env::temp_dir()
/// #     .join(format!("pyrucast_doc_{}_objets.pyr", std::process::id()));
/// # archive::save(&chemin, &[("maillage", &mesh as &dyn ArchiveRoot)]).unwrap();
/// # let objets = archive::load(&chemin).unwrap();
/// // The `Deref` to `BTreeMap` gives `keys`, `len` and iteration — sorted,
/// // which is also what makes an archive reproducible byte for byte.
/// assert_eq!(objets.len(), 1);
/// assert_eq!(objets.keys().collect::<Vec<_>>(), vec!["maillage"]);
/// # let _ = std::fs::remove_file(&chemin);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
#[derive(Default, Debug)]
pub struct Objects(BTreeMap<String, Root>);

impl std::ops::Deref for Objects {
    type Target = BTreeMap<String, Root>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Objects {
    /// Hand over the map itself, to walk every entry once — what the Python
    /// binding does to fill its dictionary.
    ///
    /// ```
    /// # use pyrucast::aggregate::Aggregate;
    /// # use pyrucast::archive::{self, ArchiveRoot};
    /// # use pyrucast::atoms::{ElementType, Node};
    /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
    /// # use pyrucast::coords::Coords;
    /// # use pyrucast::handle::Handle;
    /// # let coords = Handle::new(Coords::new(2).unwrap());
    /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
    /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
    /// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
    /// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
    /// # let mesh = Mesh::from_submesh(sm);
    /// # let chemin = std::env::temp_dir()
    /// #     .join(format!("pyrucast_doc_{}_inner.pyr", std::process::id()));
    /// # archive::save(&chemin, &[("maillage", &mesh as &dyn ArchiveRoot)]).unwrap();
    /// # let objets = archive::load(&chemin).unwrap();
    /// // Walking each entry once, whatever its type — what the Python binding
    /// // does to fill its dictionary.
    /// for (nom, racine) in objets.into_inner() {
    ///     assert_eq!((nom.as_str(), racine.type_name()), ("maillage", "Mesh"));
    /// }
    /// # let _ = std::fs::remove_file(&chemin);
    /// # Ok::<(), pyrucast::PyrucastError>(())
    /// ```
    pub fn into_inner(self) -> BTreeMap<String, Root> {
        self.0
    }

    fn wrong(&self, key: &str, expected: &str) -> PyrucastError {
        match self.0.get(key) {
            Some(r) => PyrucastError::Message(format!(
                "archive: \"{key}\" is a {}, not a {expected}",
                r.type_name()
            )),
            None => PyrucastError::Message(format!(
                "archive: no entry named \"{key}\" (available: {})",
                self.0.keys().cloned().collect::<Vec<_>>().join(", ")
            )),
        }
    }
}

/// Generates one typed accessor per variant: `objects.mesh("k")?`.
macro_rules! accessors {
    ($($name:ident, $variant:ident, $ty:ty, $label:literal;)*) => {
        impl Objects {
            $(
                #[doc = concat!("The `", $label, "` named `key`, or an error naming what was found instead.")]
                ///
                /// ```
                /// # use pyrucast::aggregate::Aggregate;
                /// # use pyrucast::archive::{self, ArchiveRoot};
                /// # use pyrucast::atoms::{ElementType, Node};
                /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
                /// # use pyrucast::coords::Coords;
                /// # use pyrucast::handle::Handle;
                /// # let coords = Handle::new(Coords::new(2).unwrap());
                /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
                /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
                /// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
                /// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
                /// # let mesh = Mesh::from_submesh(sm);
                /// # let chemin = std::env::temp_dir()
                /// #     .join(format!("pyrucast_doc_{}_sub.pyr", std::process::id()));
                /// archive::save(&chemin, &[("maillage", &mesh as &dyn ArchiveRoot)])?;
                /// let mut objets = archive::load(&chemin)?;
                ///
                /// // Every accessor is **typed**: asking for the wrong type
                /// // fails, naming what was found instead.
                /// assert_eq!(objets.mesh("maillage")?.len(), 1);
                /// assert!(objets.int("maillage").is_err());
                /// assert!(objets.mesh("absent").is_err());
                /// # let _ = std::fs::remove_file(&chemin);
                /// # Ok::<(), pyrucast::PyrucastError>(())
                /// ```
                pub fn $name(&self, key: &str) -> Result<$ty> {
                    match self.0.get(key) {
                        Some(Root::$variant(v)) => Ok(v.clone()),
                        _ => Err(self.wrong(key, $label)),
                    }
                }
            )*
        }
    };
}

accessors! {
    coords, Coords, Handle<Coords>, "Coords";
    submesh, SubMesh, Handle<SubMesh>, "SubMesh";
    subfespace, SubFiniteElementSpace, Handle<SubFiniteElementSpace>, "SubFiniteElementSpace";
    sub_node_field, SubNodeField, Handle<SubNodeField>, "SubNodeField";
    sub_element_field, SubElementField, Handle<SubElementField>, "SubElementField";
    sub_evolution, SubEvolution, Handle<SubEvolution>, "SubEvolution";
    sub_model, SubModel, Handle<SubModel>, "SubModel";
    sub_matrix, SubMatrix, Handle<SubMatrix>, "SubMatrix";
}

/// Generates the accessors for the aggregates, which come back by value and are
/// therefore **taken** out of the map rather than cloned.
macro_rules! take_accessors {
    ($($name:ident, $variant:ident, $ty:ty, $label:literal;)*) => {
        impl Objects {
            $(
                #[doc = concat!("The `", $label, "` named `key`, removed from the map (it is held by value).")]
                ///
                /// ```
                /// # use pyrucast::aggregate::Aggregate;
                /// # use pyrucast::archive::{self, ArchiveRoot};
                /// # use pyrucast::atoms::{ElementType, Node};
                /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
                /// # use pyrucast::coords::Coords;
                /// # use pyrucast::handle::Handle;
                /// # let coords = Handle::new(Coords::new(2).unwrap());
                /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
                /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
                /// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
                /// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
                /// # let mesh = Mesh::from_submesh(sm);
                /// # let chemin = std::env::temp_dir()
                /// #     .join(format!("pyrucast_doc_{}_agg.pyr", std::process::id()));
                /// archive::save(&chemin, &[("maillage", &mesh as &dyn ArchiveRoot)])?;
                /// let mut objets = archive::load(&chemin)?;
                ///
                /// // Every accessor is **typed**: asking for the wrong type
                /// // fails, naming what was found instead.
                /// assert_eq!(objets.mesh("maillage")?.len(), 1);
                /// assert!(objets.int("maillage").is_err());
                /// assert!(objets.mesh("absent").is_err());
                /// # let _ = std::fs::remove_file(&chemin);
                /// # Ok::<(), pyrucast::PyrucastError>(())
                /// ```
                pub fn $name(&mut self, key: &str) -> Result<$ty> {
                    match self.0.get(key) {
                        Some(Root::$variant(_)) => match self.0.remove(key) {
                            Some(Root::$variant(v)) => Ok(v),
                            _ => unreachable!("just matched"),
                        },
                        _ => Err(self.wrong(key, $label)),
                    }
                }
            )*
        }
    };
}

take_accessors! {
    mesh, Mesh, Mesh, "Mesh";
    fespace, FiniteElementSpace, FiniteElementSpace, "FiniteElementSpace";
    node_field, NodeField, NodeField, "NodeField";
    element_field, ElementField, ElementField, "ElementField";
    evolution, Evolution, Evolution, "Evolution";
    model, Model, Model, "Model";
    matrix, Matrix, Matrix, "Matrix";
}

/// Accessors for the simple values.
macro_rules! value_accessors {
    ($($name:ident, $variant:ident, $ty:ty, $label:literal;)*) => {
        impl Objects {
            $(
                #[doc = concat!("The `", $label, "` named `key`.")]
                ///
                /// ```
                /// # use pyrucast::aggregate::Aggregate;
                /// # use pyrucast::archive::{self, ArchiveRoot};
                /// # use pyrucast::atoms::{ElementType, Node};
                /// # use pyrucast::containers::mesh::{Mesh, SubMesh};
                /// # use pyrucast::coords::Coords;
                /// # use pyrucast::handle::Handle;
                /// # let coords = Handle::new(Coords::new(2).unwrap());
                /// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
                /// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
                /// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
                /// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
                /// # let mesh = Mesh::from_submesh(sm);
                /// # let chemin = std::env::temp_dir()
                /// #     .join(format!("pyrucast_doc_{}_val.pyr", std::process::id()));
                /// archive::save(&chemin, &[("maillage", &mesh as &dyn ArchiveRoot)])?;
                /// let mut objets = archive::load(&chemin)?;
                ///
                /// // Every accessor is **typed**: asking for the wrong type
                /// // fails, naming what was found instead.
                /// assert_eq!(objets.mesh("maillage")?.len(), 1);
                /// assert!(objets.int("maillage").is_err());
                /// assert!(objets.mesh("absent").is_err());
                /// # let _ = std::fs::remove_file(&chemin);
                /// # Ok::<(), pyrucast::PyrucastError>(())
                /// ```
                pub fn $name(&self, key: &str) -> Result<$ty> {
                    match self.0.get(key) {
                        Some(Root::Value(Value::$variant(v))) => Ok(v.clone()),
                        _ => Err(self.wrong(key, $label)),
                    }
                }
            )*
        }
    };
}

value_accessors! {
    bool, Bool, bool, "bool";
    int, Int, i64, "int";
    float, Float, f64, "float";
    text, Text, String, "str";
    bools, Bools, Vec<bool>, "list[bool]";
    ints, Ints, Vec<i64>, "list[int]";
    floats, Floats, Vec<f64>, "list[float]";
    texts, Texts, Vec<String>, "list[str]";
}

// ─── What can be handed to `save` ───────────────────────────────────────────

/// How a named entry is written. Implementation detail of the file format.
#[doc(hidden)]
#[derive(Serialize, Deserialize)]
pub enum Entry {
    /// A shared object: the identifier of its record.
    Object(u32),
    /// An aggregate, held by value and carried inline — nothing points at it.
    Inline { tag: String, payload: Vec<u8> },
    /// A simple value.
    Value(Value),
}

/// Anything that can be handed to [`save`] under a name.
///
/// Implemented for every handle to an archivable object, for the seven
/// aggregates, and for the simple values. Sealed in practice: the method is
/// hidden, since it speaks the file format.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::archive::{self, ArchiveRoot};
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
/// # let mesh = Mesh::from_submesh(sm);
/// # let chemin = std::env::temp_dir()
/// #     .join(format!("pyrucast_doc_{}_root2.pyr", std::process::id()));
/// // What can be named **at the root** of an archive: a container, or a
/// // plain value. That is the point of the `&dyn ArchiveRoot` that `save`
/// // calls for.
/// let racines: Vec<(&str, &dyn ArchiveRoot)> =
///     vec![("maillage", &mesh), ("pas", &0.25_f64)];
/// archive::save(&chemin, &racines)?;
/// let objets = archive::load(&chemin)?;
/// assert_eq!(objets.len(), 2);
/// # let _ = std::fs::remove_file(&chemin);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub trait ArchiveRoot {
    #[doc(hidden)]
    fn to_entry(&self) -> Result<Entry>;
}

impl<T: Archivable> ArchiveRoot for Handle<T> {
    fn to_entry(&self) -> Result<Entry> {
        Ok(Entry::Object(scope::intern_handle(self)?))
    }
}

/// The aggregates travel inline: they are held by value, and no handle inside
/// the graph ever points at one.
macro_rules! inline_roots {
    ($($ty:ty),* $(,)?) => {
        $(
            impl ArchiveRoot for $ty {
                fn to_entry(&self) -> Result<Entry> {
                    Ok(Entry::Inline {
                        tag: <$ty as Archivable>::TAG.to_string(),
                        payload: self.to_bytes()?,
                    })
                }
            }
        )*
    };
}

inline_roots!(
    Mesh,
    FiniteElementSpace,
    NodeField,
    ElementField,
    Evolution,
    Model,
    Matrix,
);

macro_rules! value_roots {
    ($($ty:ty => $variant:ident),* $(,)?) => {
        $(
            impl ArchiveRoot for $ty {
                fn to_entry(&self) -> Result<Entry> {
                    Ok(Entry::Value(Value::$variant(self.clone())))
                }
            }
        )*
    };
}

value_roots!(
    bool => Bool,
    i64 => Int,
    f64 => Float,
    String => Text,
    Vec<bool> => Bools,
    Vec<i64> => Ints,
    Vec<f64> => Floats,
    Vec<String> => Texts,
);

impl ArchiveRoot for str {
    fn to_entry(&self) -> Result<Entry> {
        Ok(Entry::Value(Value::Text(self.to_string())))
    }
}

// ─── The file ───────────────────────────────────────────────────────────────

#[derive(Serialize, Deserialize)]
struct Body {
    /// Informative only: written for whoever inspects the file, never read back.
    crate_version: String,
    /// `(identifier, tag, bytes)`, in dependency order.
    records: Vec<(u32, String, Vec<u8>)>,
    roots: BTreeMap<String, Entry>,
}

/// Write `roots` and everything they need to `path`.
///
/// Objects shared by several roots are written **once**; that is where the
/// no-duplication guarantee is kept. Saving twice the same objects produces the
/// same bytes.
///
/// Fails, rather than looping, if the graph has a cycle — only recomputable
/// caches may point backwards, and caches are not written.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::archive::{self, ArchiveRoot};
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
/// # let mesh = Mesh::from_submesh(sm);
/// # let chemin = std::env::temp_dir()
/// #     .join(format!("pyrucast_doc_{}_save.pyr", std::process::id()));
/// // Objects **shared** by several roots are written once only: that is
/// // where the non-duplication guarantee stands. Two saves of the same
/// // objects produce the same bytes.
/// archive::save(&chemin, &[("maillage", &mesh as &dyn ArchiveRoot)])?;
/// let a = std::fs::read(&chemin)?;
/// archive::save(&chemin, &[("maillage", &mesh as &dyn ArchiveRoot)])?;
/// assert_eq!(a, std::fs::read(&chemin)?);
/// // A name given twice is an error.
/// assert!(archive::save(&chemin,
///     &[("m", &mesh as &dyn ArchiveRoot), ("m", &mesh)]).is_err());
/// # let _ = std::fs::remove_file(&chemin);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn save<P: AsRef<Path>>(path: P, roots: &[(&str, &dyn ArchiveRoot)]) -> Result<()> {
    let (root_map, records) = scope::with_write(|| {
        // Sorted first, so the identifiers are handed out in a deterministic
        // order and the file is byte-reproducible.
        let mut sorted: Vec<_> = roots.iter().collect();
        sorted.sort_by_key(|(name, _)| *name);

        let mut map: BTreeMap<String, Entry> = BTreeMap::new();
        for (name, root) in sorted {
            if map.contains_key(*name) {
                return Err(PyrucastError::Message(format!(
                    "archive: \"{name}\" is given twice"
                )));
            }
            map.insert((*name).to_string(), root.to_entry()?);
        }
        Ok(map)
    })?;

    let body = Body {
        crate_version: crate::VERSION.to_string(),
        records: records
            .into_iter()
            .map(|r| (r.id, r.tag.to_string(), r.payload))
            .collect(),
        roots: root_map,
    };

    let mut out = Vec::with_capacity(4096);
    out.extend_from_slice(MAGIC);
    out.extend_from_slice(&FORMAT.to_le_bytes());
    out.extend_from_slice(&body.to_bytes()?);
    std::fs::write(path.as_ref(), &out)
        .map_err(|e| PyrucastError::Io(format!("writing {}: {e}", path.as_ref().display())))
}

/// Read back what [`save`] wrote, preserving what was shared.
///
/// The objects are **new**: nothing already alive in the session is touched.
///
/// ```
/// # use pyrucast::aggregate::Aggregate;
/// # use pyrucast::archive::{self, ArchiveRoot};
/// # use pyrucast::atoms::{ElementType, Node};
/// # use pyrucast::containers::mesh::{Mesh, SubMesh};
/// # use pyrucast::coords::Coords;
/// # use pyrucast::handle::Handle;
/// # let coords = Handle::new(Coords::new(2).unwrap());
/// # let n: Vec<Node> = [[0.0, 0.0], [1.0, 0.0]]
/// #     .iter().map(|p| Node::create_in(coords.clone(), p).unwrap()).collect();
/// # let mut sm = SubMesh::new(coords.clone(), ElementType::SEG2);
/// # sm.add_cell(&[n[0].id(), n[1].id()]).unwrap();
/// # let mesh = Mesh::from_submesh(sm);
/// # let chemin = std::env::temp_dir()
/// #     .join(format!("pyrucast_doc_{}_load.pyr", std::process::id()));
/// // What comes back is **fresh**: nothing already living in the session is
/// // touched.
/// archive::save(&chemin, &[("maillage", &mesh as &dyn ArchiveRoot)])?;
/// let mut objets = archive::load(&chemin)?;
/// let relu = objets.mesh("maillage")?;
/// # use pyrucast::handle::Handle as H;
/// assert!(!H::same_object(&relu.get(0)?, &mesh.get(0)?));
/// assert_eq!(relu.cell_count(), mesh.cell_count());
/// // A file that is not an archive is refused on its signature.
/// std::fs::write(&chemin, b"pas une archive")?;
/// assert!(archive::load(&chemin).is_err());
/// # let _ = std::fs::remove_file(&chemin);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
pub fn load<P: AsRef<Path>>(path: P) -> Result<Objects> {
    let bytes = std::fs::read(path.as_ref())
        .map_err(|e| PyrucastError::Io(format!("reading {}: {e}", path.as_ref().display())))?;

    if bytes.len() < 12 || &bytes[..8] != MAGIC {
        return Err(PyrucastError::Message(format!(
            "{} is not a pyrucast archive (bad signature)",
            path.as_ref().display()
        )));
    }
    let format = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
    if format != FORMAT {
        return Err(PyrucastError::Message(format!(
            "{} is in archive format {format}, this build reads format {FORMAT}. \
             Before version 1.0.0 no conversion is offered.",
            path.as_ref().display()
        )));
    }
    let body = Body::from_bytes(&bytes[12..])?;

    scope::with_read(|| {
        for (id, tag, payload) in &body.records {
            let object = registry::decode_node(tag, payload)?;
            scope::publish(*id, tag.clone(), object)?;
        }
        let mut out = BTreeMap::new();
        for (name, entry) in body.roots {
            let root = match entry {
                Entry::Value(v) => Ok(Root::Value(v)),
                Entry::Object(id) => {
                    let tag = scope::tag_of(id)?;
                    scope::with_object(id, |any| registry::wrap_root(&tag, any))?
                }
                Entry::Inline { tag, payload } => registry::decode_inline(&tag, &payload),
            }?;
            out.insert(name, root);
        }
        Ok(Objects(out))
    })
}