ymf 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ymf/archive.py ADDED
@@ -0,0 +1,2104 @@
1
+ """The YMF archive core: the approximation data model, plus YAML read/write.
2
+
3
+ This is the module simulation codes depend on. Its **only** third-party
4
+ dependency is ``pyyaml`` -- deliberately, so that a solver like Proteus can
5
+ write YMF archives without inheriting ``strictyaml``, ``pint`` or ``sympy``
6
+ (see ``ymf.schema`` / ``ymf.units``, which are behind the ``ymf[spec]`` and
7
+ ``ymf[units]`` extras).
8
+
9
+ The trust boundary
10
+ ------------------
11
+ Validation and writing are different jobs with different dependency
12
+ budgets:
13
+
14
+ - A **front-end** (``ymf.schema`` + ``ymf.units``, plus whatever tooling
15
+ wraps them) validates YMF *input* authored by a human or an LLM. It does
16
+ schema validation, unit coherence, dimensional analysis, standard-name
17
+ checking. It runs once, off the compute path, and may be as slow and as
18
+ thorough as it likes.
19
+ - A **solver** reads validated input and writes archive *output*. It
20
+ trusts the input's semantics and does not re-derive them.
21
+
22
+ So nothing here checks units, dimensional consistency or standard names.
23
+ What it *does* check is **structure**: that required keys are present, that
24
+ closed-set fields hold legal values, and that declared ``Dimensions`` match
25
+ the arrays they claim to describe. Those checks are O(1) per field and
26
+ fail loudly, naming the field. Trust, but verify cheaply.
27
+
28
+ Why not strictyaml here
29
+ -----------------------
30
+ ``strictyaml`` is the right tool for human-authored documents -- schema
31
+ validation, comment preservation, exact round-tripping -- and the wrong
32
+ tool for machine-written archive metadata. Measured on a realistic archive
33
+ document (100 timesteps x 16 ranks x 10 attributes):
34
+
35
+ ====================================== =========
36
+ serializer time
37
+ ====================================== =========
38
+ ``json.dumps`` 0.017 s
39
+ ``xml.etree`` (what Proteus did before) 0.078 s
40
+ ``pyyaml`` ``CSafeDumper`` (libyaml) 0.704 s
41
+ ``pyyaml`` ``safe_dump`` (pure Python) 2.258 s
42
+ ``strictyaml.as_document`` 18.778 s
43
+ ====================================== =========
44
+
45
+ That is ~240x the ElementTree code it replaces. This module therefore uses
46
+ ``pyyaml``, and prefers the libyaml-backed C dumper/loader -- the 3.2x gap
47
+ between ``CSafeDumper`` and the pure-Python fallback is large enough to be
48
+ worth knowing about, so :func:`require_libyaml` is provided for callers on
49
+ a hot path to assert on it rather than silently degrade.
50
+
51
+ The approximation tree
52
+ ----------------------
53
+ The tree a solver writes is an *approximation*: the name the archive of a
54
+ spec gives it (``outputs[key].approximation``), and the name of the
55
+ functions that build and check it (:func:`new_approximation`,
56
+ :func:`validate_approximation`, ...). ``domain`` is left meaning the region
57
+ a problem is posed on, ``model.strong_form.domain`` (see ``ymf.domain``).
58
+ The older names (``new_domain``, ``validate_domain``, ...) are aliases of
59
+ the new ones, kept for one release. A solver's own ``.ymf`` file still
60
+ stores the tree under its ``domain:`` key; that is the file format, and it
61
+ changes only with ``ymf_archive_version``. Below, and in parameter names,
62
+ "domain" still means this tree.
63
+
64
+ The domain model
65
+ ----------------
66
+ A *domain* is a plain dict -- no classes, no schema objects, so it costs
67
+ nothing to build, gathers across MPI natively, and serializes directly::
68
+
69
+ {"times": [{"time": float, "spaces": {name: space, ...}}, ...]}
70
+
71
+ There is a *mapping* of spaces inside each instant, not one grid, because a
72
+ solver writes one mesh per finite-element space: a real Proteus archive
73
+ commonly holds both ``Mesh Spatial_Domain`` (the linear base mesh) and
74
+ ``Mesh_c0p2_Lagrange`` (the quadratic space, on the same elements with more
75
+ nodes). 195 of the 814 archives surveyed when this model was designed had
76
+ two. A space first archived late is absent from the earlier instants. The
77
+ order of the names is the order they were first archived in.
78
+
79
+ Format 1 nested the other way, ``{"time_collections": [{"name": str, "data":
80
+ [step, ...]}, ...]}``; it is still accepted everywhere and
81
+ :func:`canonicalize_approximation` upgrades it. See
82
+ docs/design/time-outside-space.md.
83
+
84
+ A space at an instant takes exactly one of two forms:
85
+
86
+ *uniform* -- a single grid, which is what a serial run or a globally
87
+ synchronized parallel write produces::
88
+
89
+ {"topology": T, "geometry": G, "attributes": [A, ...]}
90
+
91
+ *spatial* -- a collection of grids, one per MPI rank, which is what a
92
+ subdomain-per-rank write produces::
93
+
94
+ {"spatial_collection": [grid, ...]}
95
+
96
+ and the pieces are::
97
+
98
+ grid = {"name": str?, "topology": T, "geometry": G, "attributes": [A, ...]}
99
+ T = {"type": str, "number_of_elements": int,
100
+ "nodes_per_element": int?, "data_item": D}
101
+ G = {"type": str, "data_item": D}
102
+ A = {"name": str, "attribute_type": str, "center": str, "data_item": D}
103
+ D = {"format": str, "data_type": str, "precision": int,
104
+ "dimensions": [int, ...], "data": str} # Format="HDF"
105
+ | {"format": "XML", ..., "include": str} # text sidecar file
106
+ | {"format": "XML", ..., "values": [num, ...]} # inline, row-major
107
+
108
+ Inline ``Values`` make an archive self-contained -- no HDF5 file, no
109
+ sidecar -- which suits small problems and solvers that avoid an HDF5
110
+ dependency. ``ymf2xmf`` writes them as the DataItem's text, as XDMF does.
111
+
112
+ Build these with the constructor helpers below (:func:`data_item`,
113
+ :func:`attribute`, :func:`topology`, :func:`geometry`, :func:`grid`,
114
+ :func:`new_approximation`, :func:`add_uniform_step`, :func:`add_spatial_step`)
115
+ rather than by hand -- they apply defaults consistently, which is what
116
+ makes :func:`canonicalize_approximation` able to state a complete list of
117
+ defaultable fields instead of guessing.
118
+
119
+ ``ymf.xdmf`` converts a domain built here into an ``.xmf`` file that
120
+ ParaView and VisIt read natively. Nothing in this module knows about XML.
121
+ """
122
+
123
+ from __future__ import annotations
124
+
125
+ import re
126
+ import os
127
+ import warnings
128
+ from pathlib import Path
129
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
130
+
131
+ import yaml
132
+
133
+ try: # pragma: no cover - depends on how pyyaml was built
134
+ from yaml import CSafeDumper as _YamlDumper, CSafeLoader as _YamlLoader
135
+
136
+ HAVE_LIBYAML = True
137
+ except ImportError: # pragma: no cover
138
+ from yaml import SafeDumper as _YamlDumper, SafeLoader as _YamlLoader
139
+
140
+ HAVE_LIBYAML = False
141
+
142
+
143
+ __all__ = [
144
+ "append_step",
145
+ "YmfArchiveError",
146
+ "HAVE_LIBYAML",
147
+ "require_libyaml",
148
+ "KNOWN_TOPOLOGY_TYPES",
149
+ "ATTRIBUTE_TYPES",
150
+ "CENTERINGS",
151
+ "DATA_TYPES",
152
+ "DATA_ITEM_FORMATS",
153
+ "GEOMETRY_TYPES",
154
+ "FACET_VIEWS",
155
+ "QUADRATIC_EDGES",
156
+ "geometry_order",
157
+ "nodes_per_cell",
158
+ "data_item",
159
+ "data_item_for",
160
+ "attribute",
161
+ "topology",
162
+ "geometry",
163
+ "grid",
164
+ "facets",
165
+ "provenance",
166
+ "check_facet_tags",
167
+ "new_approximation",
168
+ "add_instant",
169
+ "uniform_grid",
170
+ "spatial_grid",
171
+ "space_names",
172
+ "series",
173
+ "time_collections",
174
+ "transpose_collections",
175
+ "add_collection",
176
+ "add_uniform_step",
177
+ "add_spatial_step",
178
+ "canonicalize_approximation",
179
+ "fold_archive_keys",
180
+ "validate_approximation",
181
+ "check_dimensions",
182
+ "write_ymf",
183
+ "is_archive_text",
184
+ "read_document",
185
+ "write_document",
186
+ "check_version",
187
+ "package_version",
188
+ "load_array",
189
+ "inline_approximation",
190
+ "approximation_arrays",
191
+ "rebase_approximation",
192
+ "select_approximation",
193
+ "step_indices",
194
+ "read_ymf",
195
+ "dump_grid",
196
+ "load_grid",
197
+ "ARCHIVE_FORMAT_VERSION",
198
+ # the names before 2026-11, kept for one release (see the module docstring)
199
+ "new_domain",
200
+ "validate_domain",
201
+ "canonicalize_domain",
202
+ "select_domain",
203
+ "rebase_domain",
204
+ "inline_domain",
205
+ "domain_arrays",
206
+ ]
207
+
208
+
209
+ class YmfArchiveError(ValueError):
210
+ """A YMF archive document is structurally invalid.
211
+
212
+ Raised by :func:`validate_approximation` and :func:`check_dimensions`. The
213
+ message always names the offending path within the document (e.g.
214
+ ``TimeCollections[0].Data[3].Attributes[1].Center``) so a failure points at
215
+ the field that caused it rather than at the serializer.
216
+ """
217
+
218
+
219
+ #: Bumped when the on-disk archive layout changes incompatibly. Written
220
+ #: into every document by :func:`write_ymf` and checked by :func:`read_ymf`,
221
+ #: so a version mismatch produces a clear error instead of a confusing
222
+ #: parse failure somewhere downstream.
223
+ ARCHIVE_FORMAT_VERSION = 2
224
+
225
+ #: Document formats :func:`read_ymf` accepts. Format 1 nests time inside
226
+ #: space (``time_collections``, one per space); format 2 nests space inside
227
+ #: time (``times``, each instant holding its ``spaces``). A format 1
228
+ #: document is upgraded in memory on read and never written; see
229
+ #: docs/design/time-outside-space.md.
230
+ _READABLE_FORMAT_VERSIONS = (1, 2)
231
+
232
+ #: Separators framing an appended step. The end marker is YAML's explicit
233
+ #: document-end token, and it is what lets a reader tell a complete record
234
+ #: from a truncated one -- see :func:`append_step`.
235
+ _STEP_START = "---\n"
236
+ _STEP_END = "...\n"
237
+
238
+ #: XDMF 2.0 topology types. Closed on purpose: getting one of these wrong
239
+ #: yields an ``.xmf`` that a viewer rejects (or worse, silently misdraws),
240
+ #: and the set a solver can legitimately emit is knowable. Structured-mesh
241
+ #: types are included because XDMF defines them, even though the current
242
+ #: Proteus writers only emit unstructured ones.
243
+ KNOWN_TOPOLOGY_TYPES = frozenset(
244
+ {
245
+ # unstructured, linear
246
+ "Polyvertex",
247
+ "Polyline",
248
+ "Polygon",
249
+ "Triangle",
250
+ "Quadrilateral",
251
+ "Tetrahedron",
252
+ "Pyramid",
253
+ "Wedge",
254
+ "Hexahedron",
255
+ # unstructured, quadratic
256
+ "Edge_3",
257
+ "Tri_6",
258
+ "Triangle_6",
259
+ "Quad_8",
260
+ "Quadrilateral_8",
261
+ "Tet_10",
262
+ "Tetrahedron_10",
263
+ "Pyramid_13",
264
+ "Wedge_15",
265
+ "Hex_20",
266
+ "Hexahedron_20",
267
+ # heterogeneous
268
+ "Mixed",
269
+ # structured
270
+ "2DSMesh",
271
+ "2DRectMesh",
272
+ "2DCoRectMesh",
273
+ "3DSMesh",
274
+ "3DRectMesh",
275
+ "3DCoRectMesh",
276
+ }
277
+ )
278
+
279
+ #: Legal ``AttributeType`` values -- the rank of a field.
280
+ ATTRIBUTE_TYPES = frozenset({"Scalar", "Vector", "Tensor", "Tensor6", "Matrix", "GlobalID"})
281
+
282
+ #: Legal ``Center`` values -- what mesh entity a field is attached to.
283
+ CENTERINGS = frozenset({"Node", "Cell", "Face", "Edge", "Grid"})
284
+
285
+ #: Legal ``DataType`` values for a DataItem.
286
+ DATA_TYPES = frozenset({"Float", "Int", "UInt", "Char", "UChar"})
287
+
288
+ #: Legal ``Format`` values. ``HDF`` references an HDF5 dataset; ``XML``
289
+ #: means the values live in a text sidecar file pulled in by reference;
290
+ #: ``Binary`` references a raw binary file.
291
+ DATA_ITEM_FORMATS = frozenset({"HDF", "XML", "Binary"})
292
+
293
+ #: Legal ``Geometry`` types.
294
+ GEOMETRY_TYPES = frozenset({"XYZ", "XY", "X_Y_Z", "X_Y", "VXVYVZ", "ORIGIN_DXDYDZ", "ORIGIN_DXDY"})
295
+
296
+ #: Where a grid's facet list sits: ``"global"``, a mesh as a whole, whose
297
+ #: tags are 0 (untagged) or a condition (>0); or ``"subdomain"``, one rank's
298
+ #: piece, whose tags may also be -1 for a face on the interface between
299
+ #: ranks. -1 is a partitioner's product, so a global mesh never stores it.
300
+ FACET_VIEWS = frozenset({"global", "subdomain"})
301
+
302
+ #: Vertices of each unstructured cell type with a fixed node count.
303
+ _VERTICES = {
304
+ "Edge_3": 2,
305
+ "Triangle": 3, "Tri_6": 3, "Triangle_6": 3,
306
+ "Quadrilateral": 4, "Quad_8": 4, "Quadrilateral_8": 4,
307
+ "Tetrahedron": 4, "Tet_10": 4, "Tetrahedron_10": 4,
308
+ "Pyramid": 5, "Pyramid_13": 5,
309
+ "Wedge": 6, "Wedge_15": 6,
310
+ "Hexahedron": 8, "Hex_20": 8, "Hexahedron_20": 8,
311
+ }
312
+
313
+ #: The node order of the quadratic cell types. The vertices come first, in
314
+ #: the linear type's order; then one node on each edge, node
315
+ #: ``n_vertices + k`` sitting on the edge between the two vertices
316
+ #: ``QUADRATIC_EDGES[type][k]``. This is VTK's order, which is what a
317
+ #: viewer draws, since ParaView's XDMF readers pass connectivity through
318
+ #: unpermuted. Mesh generators do not all agree with it -- one widely used
319
+ #: generator numbers the last two edge nodes of a 10-node tetrahedron the
320
+ #: other way round, (2,3) before (1,3) -- so a writer whose source orders
321
+ #: edge nodes differently permutes them first; see
322
+ #: :func:`ymf.mesh.edge_node_permutation`.
323
+ QUADRATIC_EDGES = {
324
+ "Edge_3": ((0, 1),),
325
+ "Tri_6": ((0, 1), (1, 2), (2, 0)),
326
+ "Quad_8": ((0, 1), (1, 2), (2, 3), (3, 0)),
327
+ "Tet_10": ((0, 1), (1, 2), (2, 0), (0, 3), (1, 3), (2, 3)),
328
+ "Pyramid_13": ((0, 1), (1, 2), (2, 3), (3, 0), (0, 4), (1, 4), (2, 4), (3, 4)),
329
+ "Wedge_15": ((0, 1), (1, 2), (2, 0), (3, 4), (4, 5), (5, 3), (0, 3), (1, 4), (2, 5)),
330
+ "Hex_20": ((0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4),
331
+ (0, 4), (1, 5), (2, 6), (3, 7)),
332
+ }
333
+ for _long, _short in (("Triangle_6", "Tri_6"), ("Quadrilateral_8", "Quad_8"),
334
+ ("Tetrahedron_10", "Tet_10"), ("Hexahedron_20", "Hex_20")):
335
+ QUADRATIC_EDGES[_long] = QUADRATIC_EDGES[_short]
336
+ del _long, _short
337
+
338
+ #: The facet types a cell type's facet list may hold. A 1D cell's facets are
339
+ #: points, a 2D cell's are edges and a 3D cell's are faces, of the cell's
340
+ #: own geometry order; a wedge or pyramid has faces of two shapes, so its
341
+ #: facet list may be ``Mixed``.
342
+ _FACET_TYPES = {
343
+ "Polyline": {"Polyvertex"}, "Edge_3": {"Polyvertex"},
344
+ "Triangle": {"Polyline"}, "Quadrilateral": {"Polyline"}, "Polygon": {"Polyline"},
345
+ "Tri_6": {"Edge_3"}, "Triangle_6": {"Edge_3"},
346
+ "Quad_8": {"Edge_3"}, "Quadrilateral_8": {"Edge_3"},
347
+ "Tetrahedron": {"Triangle"}, "Hexahedron": {"Quadrilateral"},
348
+ "Wedge": {"Triangle", "Quadrilateral", "Mixed"},
349
+ "Pyramid": {"Triangle", "Quadrilateral", "Mixed"},
350
+ "Tet_10": {"Tri_6", "Triangle_6"}, "Tetrahedron_10": {"Tri_6", "Triangle_6"},
351
+ "Hex_20": {"Quad_8", "Quadrilateral_8"}, "Hexahedron_20": {"Quad_8", "Quadrilateral_8"},
352
+ "Wedge_15": {"Tri_6", "Triangle_6", "Quad_8", "Quadrilateral_8", "Mixed"},
353
+ "Pyramid_13": {"Tri_6", "Triangle_6", "Quad_8", "Quadrilateral_8", "Mixed"},
354
+ }
355
+
356
+ _SHA256 = re.compile(r"^[0-9a-f]{64}$")
357
+
358
+
359
+ def geometry_order(topology_type: str) -> Optional[int]:
360
+ """The geometry order a topology type carries: 1 linear, 2 quadratic.
361
+
362
+ The order is the type's, never a separate field, so the two cannot
363
+ disagree: a ``Tet_10`` grid is a quadratic tetrahedral mesh. ``Mixed``
364
+ has no single order and gives ``None``.
365
+ """
366
+ if topology_type not in KNOWN_TOPOLOGY_TYPES:
367
+ raise YmfArchiveError(
368
+ f"{topology_type!r} is not a known topology type. "
369
+ f"Known types: {sorted(KNOWN_TOPOLOGY_TYPES)}")
370
+ if topology_type == "Mixed":
371
+ return None
372
+ return 2 if topology_type in QUADRATIC_EDGES else 1
373
+
374
+
375
+ def nodes_per_cell(topology_type: str) -> Optional[int]:
376
+ """The node count a cell of this type has, or ``None`` where the type does
377
+ not fix it: ``Polyvertex``, ``Polyline`` and ``Polygon`` (which say so in
378
+ ``nodes_per_element``), ``Mixed`` and the structured types."""
379
+ if topology_type not in _VERTICES:
380
+ return None
381
+ return _VERTICES[topology_type] + len(QUADRATIC_EDGES.get(topology_type, ()))
382
+
383
+
384
+ # XDMF's own documented default for DataItem/@Precision. Faithful to the
385
+ # format rather than to what a solver usually writes -- use data_item_for()
386
+ # to infer the right value from an actual array instead of relying on this.
387
+ _DEFAULT_PRECISION = 4
388
+ _DEFAULT_TIME_COLLECTION_NAME = "TimeCollection"
389
+
390
+
391
+ def require_libyaml() -> None:
392
+ """Raise unless ``pyyaml`` was built with its libyaml C extension.
393
+
394
+ The pure-Python fallback is ~3.2x slower to dump and load. That is
395
+ tolerable for a one-off read but not for a solver writing an archive
396
+ every timestep, so a caller on that path should assert on it at
397
+ startup rather than discover it as unexplained slowness later.
398
+ """
399
+ if not HAVE_LIBYAML:
400
+ raise YmfArchiveError(
401
+ "pyyaml is installed without its libyaml C extension, which makes "
402
+ "YMF archive read/write about 3.2x slower. Install a pyyaml built "
403
+ "with libyaml (the conda-forge and manylinux wheels both are), or "
404
+ "call write_ymf/read_ymf without require_libyaml() to accept the "
405
+ "slower pure-Python path."
406
+ )
407
+
408
+
409
+ # ---------------------------------------------------------------------------
410
+ # constructors
411
+ #
412
+ # These exist so that defaults are applied in exactly one place. That is
413
+ # what lets canonicalize_approximation() enumerate every defaultable field rather
414
+ # than covering only the ones that happened to surface in a test.
415
+ # ---------------------------------------------------------------------------
416
+
417
+
418
+ def data_item(
419
+ dimensions: Sequence[int],
420
+ data: Optional[str] = None,
421
+ *,
422
+ include: Optional[str] = None,
423
+ values: Optional[Sequence[Any]] = None,
424
+ data_type: str = "Float",
425
+ precision: int = _DEFAULT_PRECISION,
426
+ fmt: Optional[str] = None,
427
+ ) -> Dict[str, Any]:
428
+ """Describe where an array lives.
429
+
430
+ Parameters
431
+ ----------
432
+ dimensions:
433
+ The array's shape, as a sequence of ints.
434
+ data:
435
+ An HDF5 reference of the form ``"file.h5:/dataset_name"``. Give
436
+ this for ``Format="HDF"`` (the default).
437
+ include:
438
+ Path to a text sidecar file holding the values. Give this instead
439
+ of ``data`` for ``Format="XML"``, the no-HDF5 fallback.
440
+ values:
441
+ The values themselves, flattened in row-major order, for an inline
442
+ ``Format="XML"`` DataItem: the archive then needs no other file.
443
+ Exactly one of ``data`` / ``include`` / ``values`` must be given.
444
+ data_type:
445
+ One of :data:`DATA_TYPES`.
446
+ precision:
447
+ Bytes per value. Defaults to XDMF's own default of 4, which is
448
+ very often *not* what you want -- ``float64`` needs 8. Prefer
449
+ :func:`data_item_for`, which reads it off the array.
450
+ fmt:
451
+ One of :data:`DATA_ITEM_FORMATS`. Inferred from which of
452
+ ``data``/``include``/``values`` was given, so it rarely needs passing.
453
+ """
454
+ if sum(x is not None for x in (data, include, values)) != 1:
455
+ raise YmfArchiveError(
456
+ "data_item() needs exactly one of data= (an HDF5 reference like "
457
+ "'out.h5:/u_t3'), include= (a path to a text sidecar file) or "
458
+ "values= (the values inline); "
459
+ f"got data={data!r}, include={include!r}, "
460
+ f"values={'<%d values>' % len(values) if values is not None else None}"
461
+ )
462
+ if fmt is None:
463
+ fmt = "HDF" if data is not None else "XML"
464
+ item: Dict[str, Any] = {
465
+ "format": fmt,
466
+ "data_type": data_type,
467
+ "precision": int(precision),
468
+ "dimensions": _FlowList(int(d) for d in dimensions),
469
+ }
470
+ if data is not None:
471
+ item["data"] = str(data)
472
+ elif include is not None:
473
+ item["include"] = str(include)
474
+ else:
475
+ item["values"] = _inline_values(values, data_type, "data_item()")
476
+ check_dimensions(item, [len(item["values"])], where="data_item()")
477
+ return item
478
+
479
+
480
+ class _FlowList(list):
481
+ """A list written as one ``[a, b, c]`` line rather than one per item.
482
+
483
+ ``Dimensions`` and inline ``Values`` use it, so a shape reads
484
+ ``[8, 3]`` and an array costs one (wrapped) line rather than a line
485
+ per number. It is a plain list in every other respect.
486
+ """
487
+
488
+
489
+ #: DataTypes whose values are integers.
490
+ _INTEGER_DATA_TYPES = frozenset({"Int", "UInt", "Char", "UChar"})
491
+
492
+
493
+ def _flatten(values: Any) -> List[Any]:
494
+ """Flatten nested sequences (or anything with ``.tolist()``) row-major."""
495
+ if hasattr(values, "tolist"): # numpy arrays, without importing numpy
496
+ values = values.tolist()
497
+ if not isinstance(values, (list, tuple)):
498
+ return [values]
499
+ flat: List[Any] = []
500
+ for v in values:
501
+ flat.extend(_flatten(v) if isinstance(v, (list, tuple)) else [v])
502
+ return flat
503
+
504
+
505
+ def _inline_values(values: Any, data_type: str, where: str) -> "_FlowList":
506
+ """Inline values as a flat list of numbers of the declared type."""
507
+ integral = data_type in _INTEGER_DATA_TYPES
508
+ result = _FlowList()
509
+ for i, v in enumerate(_flatten(values)):
510
+ if isinstance(v, bool) or not isinstance(v, (int, float)):
511
+ raise YmfArchiveError(
512
+ f"{where}.values[{i}]: {v!r} is not a number")
513
+ if integral:
514
+ if v != int(v):
515
+ raise YmfArchiveError(
516
+ f"{where}.values[{i}]: {v!r} is not an integer, but the "
517
+ f"DataType is {data_type}")
518
+ v = int(v)
519
+ else:
520
+ v = float(v)
521
+ result.append(v)
522
+ return result
523
+
524
+
525
+ #: numpy dtype kind -> XDMF DataType. Covers the kinds that can appear in a
526
+ #: mesh or field array; anything else is rejected rather than guessed at.
527
+ _DTYPE_KIND_TO_DATA_TYPE = {"f": "Float", "i": "Int", "u": "UInt", "b": "UChar"}
528
+
529
+
530
+ def data_item_for(
531
+ array: Any,
532
+ data: Optional[str] = None,
533
+ *,
534
+ include: Optional[str] = None,
535
+ inline: bool = False,
536
+ dimensions: Optional[Sequence[int]] = None,
537
+ check: bool = True,
538
+ ) -> Dict[str, Any]:
539
+ """Build a DataItem by reading shape and dtype off ``array``.
540
+
541
+ With ``inline=True`` the values are copied into the DataItem itself
542
+ (``Format="XML"``, ``Values``) instead of being referenced, so the
543
+ archive needs no HDF5 file or sidecar.
544
+
545
+ Prefer this over :func:`data_item` whenever the array is in hand. It
546
+ removes the three fields a caller can most easily get wrong --
547
+ ``Dimensions``, ``DataType`` and ``Precision`` -- by deriving all three
548
+ from the array itself, so a ``float64`` field cannot be described as
549
+ 4-byte, and a connectivity array cannot claim the wrong element count.
550
+
551
+ ``array`` needs a numpy-style ``.shape`` and ``.dtype``; numpy is not
552
+ imported here, so anything with those attributes works.
553
+
554
+ Pass ``dimensions`` only to declare a deliberately different shape from
555
+ the array's own -- flattening an ``(N, k)`` connectivity array to
556
+ ``[N*k]`` is the normal case. It is still checked for consistency, so a
557
+ genuine mismatch is rejected.
558
+
559
+ Pass ``check=False`` when ``array`` is deliberately *not* the whole of
560
+ what the DataItem describes, and is present only to supply the dtype.
561
+ That is the case for a collective parallel write: the DataItem covers
562
+ the assembled global array while this caller holds one rank's slice, so
563
+ the declared dimensions are larger than the array by design and
564
+ checking them would reject a correct write.
565
+ """
566
+ try:
567
+ shape, dtype = array.shape, array.dtype
568
+ except AttributeError as exc: # pragma: no cover - defensive
569
+ raise YmfArchiveError(
570
+ "data_item_for() needs an array with .shape and .dtype; got "
571
+ f"{type(array).__name__}. Use data_item() to state Dimensions, "
572
+ "DataType and Precision explicitly."
573
+ ) from exc
574
+
575
+ kind = dtype.kind
576
+ if kind not in _DTYPE_KIND_TO_DATA_TYPE:
577
+ raise YmfArchiveError(
578
+ f"data_item_for(): dtype {dtype!r} (kind {kind!r}) has no XDMF "
579
+ f"DataType equivalent. Supported kinds: "
580
+ f"{sorted(_DTYPE_KIND_TO_DATA_TYPE)}"
581
+ )
582
+
583
+ if inline and (data is not None or include is not None):
584
+ raise YmfArchiveError(
585
+ "data_item_for(): inline=True copies the values in, so it takes "
586
+ "no data= or include= reference")
587
+ item = data_item(
588
+ list(shape) if dimensions is None else dimensions,
589
+ data,
590
+ include=include,
591
+ values=array if inline else None,
592
+ data_type=_DTYPE_KIND_TO_DATA_TYPE[kind],
593
+ precision=dtype.itemsize,
594
+ )
595
+ if dimensions is not None and check:
596
+ check_dimensions(item, shape, where="data_item_for()")
597
+ return item
598
+
599
+
600
+ def attribute(
601
+ name: str,
602
+ item: Dict[str, Any],
603
+ *,
604
+ center: str = "Node",
605
+ attribute_type: str = "Scalar",
606
+ ) -> Dict[str, Any]:
607
+ """Describe one field defined over a grid.
608
+
609
+ ``center`` and ``attribute_type`` are the XDMF ``Center`` and
610
+ ``AttributeType``; both are validated against closed sets, so a
611
+ malformed field is not representable.
612
+ """
613
+ return {
614
+ "name": str(name),
615
+ "attribute_type": attribute_type,
616
+ "center": center,
617
+ "data_item": item,
618
+ }
619
+
620
+
621
+ def topology(
622
+ topology_type: str,
623
+ n_elements: int,
624
+ item: Dict[str, Any],
625
+ *,
626
+ nodes_per_element: Optional[int] = None,
627
+ ) -> Dict[str, Any]:
628
+ """Describe a grid's element connectivity.
629
+
630
+ ``nodes_per_element`` is only meaningful for the types that don't imply
631
+ it -- ``Polyvertex`` and ``Polyline`` -- and is omitted otherwise.
632
+ """
633
+ topo: Dict[str, Any] = {
634
+ "type": topology_type,
635
+ "number_of_elements": int(n_elements),
636
+ "data_item": item,
637
+ }
638
+ if nodes_per_element is not None:
639
+ topo["nodes_per_element"] = int(nodes_per_element)
640
+ return topo
641
+
642
+
643
+ def geometry(item: Dict[str, Any], *, geometry_type: str = "XYZ") -> Dict[str, Any]:
644
+ """Describe a grid's node coordinates."""
645
+ return {"type": geometry_type, "data_item": item}
646
+
647
+
648
+ def facets(
649
+ topo: Dict[str, Any],
650
+ tags: Dict[str, Any],
651
+ *,
652
+ view: str = "global",
653
+ ) -> Dict[str, Any]:
654
+ """Describe a grid's tagged facets: boundary faces (or edges, in 2D) and
655
+ an integer tag on each.
656
+
657
+ ``topo`` is a :func:`topology` of the facets, as tuples of the grid's
658
+ node numbers (a triangle's facets are ``Polyline`` with
659
+ ``nodes_per_element=2``, a ``Tet_10``'s are ``Tri_6``); ``tags`` is a
660
+ data item of one integer per facet: 0 untagged, >0 a condition. The
661
+ names of conditions belong to the specification, not to the mesh.
662
+ ``view`` is ``"global"`` for a whole mesh, or ``"subdomain"`` for one
663
+ rank's piece, where -1 marks a face on the interface between ranks
664
+ (:data:`FACET_VIEWS`). A face per facet, not a tag per node: a node at
665
+ a corner belongs to two faces that may carry different conditions.
666
+ """
667
+ return {"topology": topo, "tags": {"data_item": tags}, "view": view}
668
+
669
+
670
+ #: The method name of :func:`ymf.mesh.fingerprint`'s digest, recorded beside
671
+ #: it so that a later definition can be told apart from this one.
672
+ FINGERPRINT_METHOD = "ymf-mesh-1"
673
+
674
+
675
+ def provenance(
676
+ tool: str,
677
+ *,
678
+ version: Optional[str] = None,
679
+ files: Iterable[Dict[str, str]] = (),
680
+ extra: Optional[Dict[str, Any]] = None,
681
+ fingerprint: Optional[str] = None,
682
+ ) -> Dict[str, Any]:
683
+ """Describe where a grid came from: the tool that made it, its version,
684
+ the files it was made from with their SHA-256 checksums, and the mesh's
685
+ own fingerprint.
686
+
687
+ ``files`` is a list of ``{"name": ..., "sha256": ...}``;
688
+ :func:`ymf.mesh.file_provenance` computes the checksums from paths. The
689
+ tool is free text -- the archive names no tools -- and ``extra`` is a
690
+ mapping the writer may fill with anything else it wants kept.
691
+ ``fingerprint`` is :func:`ymf.mesh.fingerprint` of the mesh in its input
692
+ order (a SHA-256 hex digest), recorded as ``{method, sha256}``; a reader
693
+ recomputes it to check it holds the mesh it expects before reading data
694
+ on it.
695
+ """
696
+ block: Dict[str, Any] = {"tool": str(tool)}
697
+ if version is not None:
698
+ block["version"] = str(version)
699
+ block["files"] = [dict(f) for f in files]
700
+ if fingerprint is not None:
701
+ block["fingerprint"] = {"method": FINGERPRINT_METHOD, "sha256": str(fingerprint).lower()}
702
+ if extra:
703
+ block["extra"] = dict(extra)
704
+ return block
705
+
706
+
707
+ def _mesh_keys(facet_list: Optional[Dict[str, Any]],
708
+ source: Optional[Dict[str, Any]]) -> Dict[str, Any]:
709
+ keys: Dict[str, Any] = {}
710
+ if facet_list is not None:
711
+ keys["facets"] = facet_list
712
+ if source is not None:
713
+ keys["provenance"] = source
714
+ return keys
715
+
716
+
717
+ def grid(
718
+ topo: Dict[str, Any],
719
+ geom: Dict[str, Any],
720
+ attributes: Optional[Iterable[Dict[str, Any]]] = None,
721
+ *,
722
+ name: Optional[str] = None,
723
+ facets: Optional[Dict[str, Any]] = None,
724
+ provenance: Optional[Dict[str, Any]] = None,
725
+ ) -> Dict[str, Any]:
726
+ """Assemble one uniform grid: connectivity, coordinates, and fields.
727
+
728
+ A mesh may also carry its tagged ``facets`` (:func:`facets`) and its
729
+ ``provenance`` (:func:`provenance`).
730
+ """
731
+ g: Dict[str, Any] = {"topology": topo, "geometry": geom}
732
+ if name is not None:
733
+ g["name"] = str(name)
734
+ g["attributes"] = list(attributes) if attributes is not None else []
735
+ g.update(_mesh_keys(facets, provenance))
736
+ return g
737
+
738
+
739
+ def new_approximation(name: Optional[str] = None) -> Dict[str, Any]:
740
+ """Create an empty domain.
741
+
742
+ The domain is ``{"times": []}``: add instants with :func:`add_instant`.
743
+ ``name`` is the format 1 spelling, which started a domain with one named
744
+ time collection; given, it still does, and :func:`add_uniform_step` and
745
+ friends then keep building format 1 (which :func:`canonicalize_approximation`
746
+ upgrades). New code should not pass it.
747
+ """
748
+ if name is None:
749
+ return {"times": []}
750
+ return {"time_collections": [{"name": str(name), "data": []}]}
751
+
752
+
753
+ def uniform_grid(
754
+ topo: Dict[str, Any],
755
+ geom: Dict[str, Any],
756
+ attributes: Optional[Iterable[Dict[str, Any]]] = None,
757
+ *,
758
+ facets: Optional[Dict[str, Any]] = None,
759
+ provenance: Optional[Dict[str, Any]] = None,
760
+ ) -> Dict[str, Any]:
761
+ """The value of a space at an instant, as one grid: ``{topology, geometry, attributes}``,
762
+ and for a mesh optionally its ``facets`` and ``provenance`` (see :func:`grid`)."""
763
+ space = {"topology": topo, "geometry": geom,
764
+ "attributes": list(attributes) if attributes is not None else []}
765
+ space.update(_mesh_keys(facets, provenance))
766
+ return space
767
+
768
+
769
+ def spatial_grid(grids: Iterable[Dict[str, Any]]) -> Dict[str, Any]:
770
+ """The value of a space at an instant, as one grid per subdomain."""
771
+ return {"spatial_collection": list(grids)}
772
+
773
+
774
+ def add_instant(
775
+ domain: Dict[str, Any], time: float, spaces: Dict[str, Dict[str, Any]]
776
+ ) -> Dict[str, Any]:
777
+ """Append one instant holding ``spaces`` (name -> :func:`uniform_grid` or
778
+ :func:`spatial_grid`). Returns the new instant.
779
+
780
+ The order of ``spaces`` is the order the archive records its spaces in,
781
+ which a hot start depends on.
782
+ """
783
+ if "time_collections" in domain:
784
+ raise YmfArchiveError(
785
+ "domain is in format 1 (time_collections); add_instant needs a "
786
+ "format 2 domain, from new_approximation() with no name")
787
+ instant = {"time": float(time), "spaces": dict(spaces)}
788
+ domain.setdefault("times", []).append(instant)
789
+ return instant
790
+
791
+
792
+ def add_collection(domain: Dict[str, Any], name: str) -> Dict[str, Any]:
793
+ """Format 1 spelling: append a new named time collection. Returns it.
794
+
795
+ On a format 2 domain this does nothing, and returns ``None``: a space
796
+ exists once an instant holds it, so there is nothing to declare.
797
+ """
798
+ if "times" in domain:
799
+ return None
800
+ collections = domain.setdefault("time_collections", [])
801
+ if any(c.get("name") == name for c in collections):
802
+ raise YmfArchiveError(
803
+ f"domain already has a time collection named {name!r}; collection "
804
+ "names are how a reader tells the meshes apart, so they must be unique"
805
+ )
806
+ collection: Dict[str, Any] = {"name": str(name), "data": []}
807
+ collections.append(collection)
808
+ return collection
809
+
810
+
811
+ def _resolve_collection(domain: Dict[str, Any], collection: Any) -> Dict[str, Any]:
812
+ """Find a collection by index or by name, with a legible failure."""
813
+ collections = domain.get("time_collections")
814
+ if not collections:
815
+ raise YmfArchiveError(
816
+ "domain has no time collections; build it with new_approximation(name)"
817
+ )
818
+ if isinstance(collection, int):
819
+ try:
820
+ return collections[collection]
821
+ except IndexError:
822
+ raise YmfArchiveError(
823
+ f"domain has {len(collections)} time collection(s); no index "
824
+ f"{collection}"
825
+ ) from None
826
+ for c in collections:
827
+ if c.get("name") == collection:
828
+ return c
829
+ names = [c.get("name") for c in collections]
830
+ raise YmfArchiveError(
831
+ f"domain has no time collection named {collection!r}; it has {names}"
832
+ )
833
+
834
+
835
+ def _add_to_space(domain: Dict[str, Any], time: float, collection: Any,
836
+ grid_like: Dict[str, Any]) -> Dict[str, Any]:
837
+ """Set ``collection``'s value at ``time`` in a format 2 domain.
838
+
839
+ Joins the last instant if it is at that time and lacks the space, else
840
+ starts one, which is how a writer that goes space by space within a
841
+ step builds the instant. Returns the instant.
842
+ """
843
+ if collection is None:
844
+ collection = _DEFAULT_TIME_COLLECTION_NAME
845
+ elif isinstance(collection, int):
846
+ names = space_names(domain)
847
+ if not -len(names) <= collection < len(names):
848
+ raise YmfArchiveError(
849
+ "domain has %d space(s); no index %d. On a format 2 domain "
850
+ "a space is named." % (len(names), collection))
851
+ collection = names[collection]
852
+ t = float(time)
853
+ times = domain.setdefault("times", [])
854
+ # A writer fills an instant space by space, so the instant to join is the
855
+ # last one; a space already present there means this is a new instant.
856
+ if times and times[-1]["time"] == t and collection not in times[-1]["spaces"]:
857
+ times[-1]["spaces"][collection] = grid_like
858
+ return times[-1]
859
+ return add_instant(domain, t, {collection: grid_like})
860
+
861
+
862
+ def add_uniform_step(
863
+ domain: Dict[str, Any],
864
+ time: float,
865
+ topo: Dict[str, Any],
866
+ geom: Dict[str, Any],
867
+ attributes: Optional[Iterable[Dict[str, Any]]] = None,
868
+ *,
869
+ collection: Any = None,
870
+ ) -> Dict[str, Any]:
871
+ """Append a timestep holding a single grid. Returns the new step.
872
+
873
+ ``collection`` selects which time collection to append to, by index or
874
+ by name; it defaults to the first, which is the only one in a
875
+ single-mesh archive. On a format 2 domain it names the space, and the
876
+ step joins the instant at ``time``.
877
+ """
878
+ grid_like = uniform_grid(topo, geom, attributes)
879
+ if "times" in domain:
880
+ _add_to_space(domain, time, collection, grid_like)
881
+ return grid_like
882
+ step: Dict[str, Any] = {"time": float(time), **grid_like}
883
+ _resolve_collection(domain, 0 if collection is None else collection)["data"].append(step)
884
+ return step
885
+
886
+
887
+ def add_spatial_step(
888
+ domain: Dict[str, Any],
889
+ time: float,
890
+ grids: Iterable[Dict[str, Any]],
891
+ *,
892
+ collection: Any = None,
893
+ ) -> Dict[str, Any]:
894
+ """Append a timestep holding one grid per subdomain. Returns the new step."""
895
+ grid_like = spatial_grid(grids)
896
+ if "times" in domain:
897
+ _add_to_space(domain, time, collection, grid_like)
898
+ return grid_like
899
+ step = {"time": float(time), **grid_like}
900
+ _resolve_collection(domain, 0 if collection is None else collection)["data"].append(step)
901
+ return step
902
+
903
+
904
+ def space_names(domain: Dict[str, Any]) -> List[str]:
905
+ """The spaces of a format 2 domain, in the order they first appear."""
906
+ names: List[str] = []
907
+ seen = set()
908
+ for instant in domain.get("times", []):
909
+ for name in instant["spaces"]:
910
+ if name not in seen:
911
+ seen.add(name)
912
+ names.append(name)
913
+ return names
914
+
915
+
916
+ def series(domain: Dict[str, Any], name: str) -> List[Tuple[float, Dict[str, Any]]]:
917
+ """``[(time, grid), ...]`` for one space, in instant order.
918
+
919
+ The grid is the space's own dict (not a copy), so editing it edits the
920
+ domain.
921
+ """
922
+ return [(i["time"], i["spaces"][name])
923
+ for i in domain.get("times", []) if name in i["spaces"]]
924
+
925
+
926
+ def time_collections(domain: Dict[str, Any]) -> List[Dict[str, Any]]:
927
+ """The format 1 view of a format 2 domain: ``[{name, data: [step, ...]}]``.
928
+
929
+ For code that thinks one space at a time. A copy of the structure; the
930
+ grids inside are shared. A domain still in format 1 is returned as it is.
931
+ """
932
+ if "times" not in domain and "time_collections" in domain:
933
+ return domain["time_collections"]
934
+ return [{"name": name,
935
+ "data": [{"time": t, **grid_like} for t, grid_like in series(domain, name)]}
936
+ for name in space_names(domain)]
937
+
938
+
939
+ class _Joiner:
940
+ """Builds instants out of per-space steps, joining on exact time.
941
+
942
+ A step is keyed by ``(time, occurrence)``, where ``occurrence`` counts
943
+ the earlier steps of the same space at that same time, so a time that
944
+ legitimately recurs pairs up correctly. Times are compared exactly:
945
+ they are written with ``repr(float)`` and YAML returns them unchanged,
946
+ and a tolerance would merge instants that are really distinct.
947
+ """
948
+
949
+ def __init__(self) -> None:
950
+ self.times: List[Dict[str, Any]] = []
951
+ self._by_key: Dict[Tuple[float, int], Dict[str, Any]] = {}
952
+ self._seen: Dict[Tuple[str, float], int] = {}
953
+
954
+ def add(self, space: str, step: Dict[str, Any]) -> None:
955
+ t = float(step["time"])
956
+ occurrence = self._seen.get((space, t), 0)
957
+ self._seen[(space, t)] = occurrence + 1
958
+ instant = self._by_key.get((t, occurrence))
959
+ if instant is None:
960
+ instant = {"time": t, "spaces": {}}
961
+ self._by_key[(t, occurrence)] = instant
962
+ self.times.append(instant)
963
+ instant["spaces"][space] = {k: v for k, v in step.items() if k != "time"}
964
+
965
+
966
+ def transpose_collections(collections: Iterable[Dict[str, Any]]) -> List[Dict[str, Any]]:
967
+ """Turn format 1 time collections into format 2 instants.
968
+
969
+ Instants are ordered by time when every collection's own steps are in
970
+ non-decreasing time order (a space first archived late then lands among
971
+ the instants it belongs to, and equal times keep first-appearance order);
972
+ otherwise by first appearance, walking step 0 of every collection, then
973
+ step 1, and so on. Equal-length series zip either way. A space missing at
974
+ an instant is omitted from it. Collections keep their list order inside
975
+ each instant.
976
+ """
977
+ collections = [c for c in collections]
978
+ joiner = _Joiner()
979
+ longest = max((len(c.get("data", [])) for c in collections), default=0)
980
+ for i in range(longest):
981
+ for c in collections:
982
+ data = c.get("data", [])
983
+ if i < len(data):
984
+ joiner.add(c.get("name", _DEFAULT_TIME_COLLECTION_NAME), data[i])
985
+ order = [c.get("name", _DEFAULT_TIME_COLLECTION_NAME) for c in collections]
986
+ for instant in joiner.times:
987
+ instant["spaces"] = {n: instant["spaces"][n] for n in order if n in instant["spaces"]}
988
+ if all(all(a["time"] <= b["time"] for a, b in zip(c.get("data", []), c.get("data", [])[1:]))
989
+ for c in collections):
990
+ return sorted(joiner.times, key=lambda instant: instant["time"]) # stable
991
+ return joiner.times
992
+
993
+
994
+ # ---------------------------------------------------------------------------
995
+ # canonicalization
996
+ # ---------------------------------------------------------------------------
997
+
998
+
999
+ def _canonicalize_data_item(item: Dict[str, Any], where: str) -> Dict[str, Any]:
1000
+ """Fill in every defaultable DataItem field.
1001
+
1002
+ Serialization loses the distinction between "field omitted, assume the
1003
+ default" and "field explicitly set to the default" -- both come back
1004
+ explicit. So comparing a sparse hand-written dict against one that has
1005
+ been through a write/read cycle only works if the sparse one is
1006
+ canonicalized first. This is the single place that decides what those
1007
+ defaults are.
1008
+ """
1009
+ if "dimensions" not in item:
1010
+ raise YmfArchiveError(f"{where}: data_item has no 'dimensions'")
1011
+ present = [k for k in ("data", "include", "values") if k in item]
1012
+ if len(present) != 1:
1013
+ raise YmfArchiveError(
1014
+ f"{where}: data_item needs exactly one of 'data' (HDF5 reference), "
1015
+ f"'include' (text sidecar path) or 'values' (inline values); got "
1016
+ f"{' and '.join(present) if present else 'none'}"
1017
+ )
1018
+ has_data = present == ["data"]
1019
+ fmt = item.get("format", "HDF" if has_data else "XML")
1020
+ canonical: Dict[str, Any] = {
1021
+ "format": fmt,
1022
+ "data_type": item.get("data_type", "Float"),
1023
+ "precision": int(item.get("precision", _DEFAULT_PRECISION)),
1024
+ "dimensions": _FlowList(int(d) for d in item["dimensions"]),
1025
+ }
1026
+ if has_data:
1027
+ canonical["data"] = str(item["data"])
1028
+ elif "include" in item:
1029
+ canonical["include"] = str(item["include"])
1030
+ else:
1031
+ canonical["values"] = _inline_values(
1032
+ item["values"], canonical["data_type"], where)
1033
+ return canonical
1034
+
1035
+
1036
+ def _canonicalize_attribute(attr: Dict[str, Any], where: str) -> Dict[str, Any]:
1037
+ for key in ("name", "data_item"):
1038
+ if key not in attr:
1039
+ raise YmfArchiveError(f"{where}: Attribute has no {key!r}")
1040
+ return {
1041
+ "name": str(attr["name"]),
1042
+ "attribute_type": attr.get("attribute_type", "Scalar"),
1043
+ "center": attr.get("center", "Node"),
1044
+ "data_item": _canonicalize_data_item(attr["data_item"], f"{where}.data_item"),
1045
+ }
1046
+
1047
+
1048
+ def _canonicalize_topology(topo: Dict[str, Any], where: str) -> Dict[str, Any]:
1049
+ for key in ("type", "number_of_elements", "data_item"):
1050
+ if key not in topo:
1051
+ raise YmfArchiveError(f"{where}: Topology has no {key!r}")
1052
+ canonical: Dict[str, Any] = {
1053
+ "type": topo["type"],
1054
+ "number_of_elements": int(topo["number_of_elements"]),
1055
+ "data_item": _canonicalize_data_item(topo["data_item"], f"{where}.data_item"),
1056
+ }
1057
+ # NodesPerElement is genuinely optional rather than defaultable: there is
1058
+ # no correct value to invent for a Tetrahedron, so an absent key stays
1059
+ # absent and round-trips as absent.
1060
+ if "nodes_per_element" in topo:
1061
+ canonical["nodes_per_element"] = int(topo["nodes_per_element"])
1062
+ return canonical
1063
+
1064
+
1065
+ def _canonicalize_geometry(geom: Dict[str, Any], where: str) -> Dict[str, Any]:
1066
+ if "data_item" not in geom:
1067
+ raise YmfArchiveError(f"{where}: geometry has no 'data_item'")
1068
+ return {
1069
+ "type": geom.get("type", "XYZ"),
1070
+ "data_item": _canonicalize_data_item(geom["data_item"], f"{where}.data_item"),
1071
+ }
1072
+
1073
+
1074
+ def _canonicalize_facets(f: Dict[str, Any], where: str) -> Dict[str, Any]:
1075
+ for key in ("topology", "tags"):
1076
+ if key not in f:
1077
+ raise YmfArchiveError(f"{where}: facets has no {key!r}")
1078
+ if not isinstance(f["tags"], dict) or "data_item" not in f["tags"]:
1079
+ raise YmfArchiveError(f"{where}.tags: must be {{data_item: ...}}")
1080
+ return {
1081
+ "topology": _canonicalize_topology(f["topology"], f"{where}.topology"),
1082
+ "tags": {"data_item": _canonicalize_data_item(
1083
+ f["tags"]["data_item"], f"{where}.tags.data_item")},
1084
+ "view": str(f.get("view", "global")),
1085
+ }
1086
+
1087
+
1088
+ def _canonicalize_provenance(p: Dict[str, Any], where: str) -> Dict[str, Any]:
1089
+ if not isinstance(p, dict) or "tool" not in p:
1090
+ raise YmfArchiveError(f"{where}: provenance has no 'tool'")
1091
+ unknown = sorted(set(p) - {"tool", "version", "files", "fingerprint", "extra"})
1092
+ if unknown:
1093
+ raise YmfArchiveError(
1094
+ f"{where}: provenance takes tool, version, files, fingerprint and extra, "
1095
+ f"not {', '.join(unknown)}; put anything else under extra")
1096
+ canonical: Dict[str, Any] = {"tool": str(p["tool"])}
1097
+ if p.get("version") is not None:
1098
+ canonical["version"] = str(p["version"])
1099
+ files = []
1100
+ for i, entry in enumerate(p.get("files") or []):
1101
+ if not isinstance(entry, dict) or set(entry) != {"name", "sha256"}:
1102
+ raise YmfArchiveError(
1103
+ f"{where}.files[{i}]: a file is {{name, sha256}}, got {entry!r}")
1104
+ files.append({"name": str(entry["name"]), "sha256": str(entry["sha256"]).lower()})
1105
+ canonical["files"] = files
1106
+ if p.get("fingerprint") is not None:
1107
+ f = p["fingerprint"]
1108
+ if not isinstance(f, dict) or set(f) != {"method", "sha256"}:
1109
+ raise YmfArchiveError(
1110
+ f"{where}.fingerprint: a fingerprint is {{method, sha256}}, got {f!r}")
1111
+ canonical["fingerprint"] = {"method": str(f["method"]), "sha256": str(f["sha256"]).lower()}
1112
+ if p.get("extra"):
1113
+ if not isinstance(p["extra"], dict):
1114
+ raise YmfArchiveError(f"{where}.extra: must be a mapping")
1115
+ canonical["extra"] = dict(p["extra"])
1116
+ return canonical
1117
+
1118
+
1119
+ def _canonicalize_mesh_keys(src: Dict[str, Any], canonical: Dict[str, Any],
1120
+ where: str) -> None:
1121
+ """Carry a grid's optional ``facets`` and ``provenance`` into its canonical form."""
1122
+ if "facets" in src:
1123
+ canonical["facets"] = _canonicalize_facets(src["facets"], f"{where}.facets")
1124
+ if "provenance" in src:
1125
+ canonical["provenance"] = _canonicalize_provenance(
1126
+ src["provenance"], f"{where}.provenance")
1127
+
1128
+
1129
+ def _canonicalize_grid(g: Dict[str, Any], where: str) -> Dict[str, Any]:
1130
+ canonical: Dict[str, Any] = {}
1131
+ if "name" in g:
1132
+ canonical["name"] = str(g["name"])
1133
+ canonical["topology"] = _canonicalize_topology(g["topology"], f"{where}.topology")
1134
+ canonical["geometry"] = _canonicalize_geometry(g["geometry"], f"{where}.geometry")
1135
+ canonical["attributes"] = [
1136
+ _canonicalize_attribute(a, f"{where}.attributes[{i}]")
1137
+ for i, a in enumerate(g.get("attributes", []))
1138
+ ]
1139
+ _canonicalize_mesh_keys(g, canonical, where)
1140
+ return canonical
1141
+
1142
+
1143
+ def _canonicalize_step(step: Dict[str, Any], where: str) -> Dict[str, Any]:
1144
+ if "time" not in step:
1145
+ raise YmfArchiveError(f"{where}: step has no 'Time'")
1146
+ is_spatial = "spatial_collection" in step
1147
+ is_uniform = "topology" in step or "geometry" in step
1148
+ if is_spatial and is_uniform:
1149
+ raise YmfArchiveError(
1150
+ f"{where}: step has both 'SpatialCollection' and inline "
1151
+ "'Topology'/'Geometry'; a step is either one uniform grid or a "
1152
+ "collection of subdomain grids, not both"
1153
+ )
1154
+ if not is_spatial and not is_uniform:
1155
+ raise YmfArchiveError(
1156
+ f"{where}: step has neither 'SpatialCollection' nor "
1157
+ "'Topology'/'Geometry'"
1158
+ )
1159
+ canonical: Dict[str, Any] = {"time": float(step["time"])}
1160
+ if is_spatial:
1161
+ canonical["spatial_collection"] = [
1162
+ _canonicalize_grid(g, f"{where}.spatial_collection[{i}]")
1163
+ for i, g in enumerate(step["spatial_collection"])
1164
+ ]
1165
+ else:
1166
+ for key in ("topology", "geometry"):
1167
+ if key not in step:
1168
+ raise YmfArchiveError(f"{where}: uniform step has no {key!r}")
1169
+ canonical["topology"] = _canonicalize_topology(step["topology"], f"{where}.topology")
1170
+ canonical["geometry"] = _canonicalize_geometry(step["geometry"], f"{where}.geometry")
1171
+ canonical["attributes"] = [
1172
+ _canonicalize_attribute(a, f"{where}.attributes[{i}]")
1173
+ for i, a in enumerate(step.get("attributes", []))
1174
+ ]
1175
+ _canonicalize_mesh_keys(step, canonical, where)
1176
+ return canonical
1177
+
1178
+
1179
+ #: Capitalized spellings accepted on read and folded to the canonical ones.
1180
+ #:
1181
+ #: The archive's vocabulary came from XDMF, which capitalizes everything --
1182
+ #: elements (``Topology``, ``DataItem``) and their attributes
1183
+ #: (``NumberOfElements``, ``Precision``) alike -- and YMF followed by analogy,
1184
+ #: including for keys XDMF does not have (``TimeCollections``,
1185
+ #: ``SpatialCollection``, ``Attributes`` as a list). Keys are
1186
+ #: ``lower_case_with_underscores`` now; see "Naming" in
1187
+ #: docs/problem-specification.md.
1188
+ #:
1189
+ #: Values are not folded. ``Triangle``, ``Node``, ``Scalar``, ``Float``,
1190
+ #: ``XYZ`` name types, so they stay as they are -- which is also what XDMF
1191
+ #: needs when ymf2xmf writes them back out.
1192
+ _ARCHIVE_KEY_ALIASES = {
1193
+ "TimeCollections": "time_collections", "TimeCollection": "time_collection",
1194
+ "SpatialCollection": "spatial_collection",
1195
+ "NumberOfElements": "number_of_elements",
1196
+ "NodesPerElement": "nodes_per_element",
1197
+ "AttributeType": "attribute_type", "DataItem": "data_item",
1198
+ "DataType": "data_type", "Dimensions": "dimensions",
1199
+ "Attributes": "attributes", "Precision": "precision",
1200
+ "Topology": "topology", "Geometry": "geometry", "Include": "include",
1201
+ "Center": "center", "Format": "format", "Values": "values",
1202
+ "Name": "name", "Data": "data", "Time": "time", "Type": "type",
1203
+ }
1204
+
1205
+
1206
+ def fold_archive_keys(obj: Any) -> Any:
1207
+ """Rename any capitalized archive key to its canonical spelling.
1208
+
1209
+ Applied on read, so an archive written before the naming rule -- or by a
1210
+ writer not yet updated -- still loads. A document that already uses the
1211
+ canonical spelling passes through unchanged.
1212
+ """
1213
+ if isinstance(obj, dict):
1214
+ return {_ARCHIVE_KEY_ALIASES.get(k, k): fold_archive_keys(v)
1215
+ for k, v in obj.items()}
1216
+ if isinstance(obj, list):
1217
+ return [fold_archive_keys(v) for v in obj]
1218
+ return obj
1219
+
1220
+
1221
+ def canonicalize_approximation(domain: Dict[str, Any]) -> Dict[str, Any]:
1222
+ """Return ``domain`` in format 2, with every defaultable field filled in.
1223
+
1224
+ Accepts both shapes and always returns ``{"times": [...]}``: a format 1
1225
+ domain (``time_collections``, or the singular ``time_collection``) is
1226
+ upgraded with :func:`transpose_collections`. Use this before comparing a
1227
+ hand-written sparse domain against one read back from a file -- see
1228
+ :func:`_canonicalize_data_item` for why a direct ``==`` can otherwise
1229
+ fail without anything having been lost.
1230
+
1231
+ The defaults applied are exactly: ``DataItem.format`` (inferred from
1232
+ ``data`` vs ``include``), ``DataItem.data_type`` (``Float``),
1233
+ ``DataItem.precision`` (4, XDMF's default), ``attribute_type``
1234
+ (``Scalar``), ``center`` (``Node``), ``geometry.type`` (``XYZ``),
1235
+ ``attributes`` (empty list), and a format 1 collection's ``name``. Every
1236
+ other field is required, and ``nodes_per_element`` is optional-absent
1237
+ rather than defaulted.
1238
+ """
1239
+ domain = fold_archive_keys(domain)
1240
+ if "times" in domain:
1241
+ if "time_collections" in domain or "time_collection" in domain:
1242
+ raise YmfArchiveError(
1243
+ "domain has both 'times' and 'time_collections'; a domain is "
1244
+ "in one format or the other")
1245
+ instants = domain["times"]
1246
+ else:
1247
+ collections = domain.get("time_collections")
1248
+ if collections is None:
1249
+ single = domain.get("time_collection")
1250
+ if single is None:
1251
+ return {}
1252
+ # Singular form is input sugar; the canonical output is always the list.
1253
+ collections = [single]
1254
+ seen: Dict[str, int] = {}
1255
+ canonical_collections = []
1256
+ for ci, collection in enumerate(collections):
1257
+ name = collection.get("name", _DEFAULT_TIME_COLLECTION_NAME)
1258
+ if name in seen:
1259
+ raise YmfArchiveError(
1260
+ f"time_collections[{ci}].name: duplicate collection name {name!r} "
1261
+ f"(also at time_collections[{seen[name]}]); names are how a reader "
1262
+ "tells the meshes apart, so they must be unique"
1263
+ )
1264
+ seen[name] = ci
1265
+ canonical_collections.append(
1266
+ {
1267
+ "name": name,
1268
+ "data": [
1269
+ _canonicalize_step(step, f"time_collections[{ci}].data[{i}]")
1270
+ for i, step in enumerate(collection.get("data", []))
1271
+ ],
1272
+ }
1273
+ )
1274
+ return {"times": transpose_collections(canonical_collections)}
1275
+ result = []
1276
+ for i, instant in enumerate(instants):
1277
+ where = f"times[{i}]"
1278
+ if "time" not in instant:
1279
+ raise YmfArchiveError(f"{where}: instant has no 'time'")
1280
+ spaces = instant.get("spaces")
1281
+ if not isinstance(spaces, dict) or not spaces:
1282
+ raise YmfArchiveError(f"{where}.spaces: must name at least one space")
1283
+ canonical_spaces = {}
1284
+ for name, space in spaces.items():
1285
+ step = _canonicalize_step(dict(space, time=instant["time"]),
1286
+ f"{where}.spaces[{name}]")
1287
+ del step["time"]
1288
+ canonical_spaces[str(name)] = step
1289
+ result.append({"time": float(instant["time"]), "spaces": canonical_spaces})
1290
+ return {"times": result}
1291
+
1292
+
1293
+ # ---------------------------------------------------------------------------
1294
+ # structural validation -- the cheap half of the trust boundary
1295
+ # ---------------------------------------------------------------------------
1296
+
1297
+
1298
+ def _validate_data_item(item: Dict[str, Any], where: str) -> None:
1299
+ fmt = item["format"]
1300
+ if fmt not in DATA_ITEM_FORMATS:
1301
+ raise YmfArchiveError(
1302
+ f"{where}.format: {fmt!r} is not one of {sorted(DATA_ITEM_FORMATS)}"
1303
+ )
1304
+ if item["data_type"] not in DATA_TYPES:
1305
+ raise YmfArchiveError(
1306
+ f"{where}.data_type: {item['data_type']!r} is not one of {sorted(DATA_TYPES)}"
1307
+ )
1308
+ if item["precision"] <= 0:
1309
+ raise YmfArchiveError(f"{where}.precision: must be positive, got {item['precision']}")
1310
+ dims = item["dimensions"]
1311
+ if not dims:
1312
+ raise YmfArchiveError(f"{where}.dimensions: must not be empty")
1313
+ if any(d < 0 for d in dims):
1314
+ raise YmfArchiveError(f"{where}.dimensions: must be non-negative, got {dims}")
1315
+ if fmt == "XML" and "include" not in item and "values" not in item:
1316
+ raise YmfArchiveError(f"{where}: format='XML' requires 'include' or 'values'")
1317
+ if "values" in item:
1318
+ if fmt != "XML":
1319
+ raise YmfArchiveError(
1320
+ f"{where}: inline 'values' need format='XML', not {fmt!r}")
1321
+ check_dimensions(item, [len(item["values"])], where=where)
1322
+ if fmt == "HDF" and "data" not in item:
1323
+ raise YmfArchiveError(f"{where}: format='HDF' requires 'data'")
1324
+
1325
+
1326
+ def _validate_grid_like(g: Dict[str, Any], where: str) -> None:
1327
+ topo = g["topology"]
1328
+ if topo["type"] not in KNOWN_TOPOLOGY_TYPES:
1329
+ raise YmfArchiveError(
1330
+ f"{where}.topology.Type: {topo['type']!r} is not a known XDMF "
1331
+ f"topology type. Known types: {sorted(KNOWN_TOPOLOGY_TYPES)}"
1332
+ )
1333
+ _validate_data_item(topo["data_item"], f"{where}.topology.data_item")
1334
+
1335
+ geom = g["geometry"]
1336
+ if geom["type"] not in GEOMETRY_TYPES:
1337
+ raise YmfArchiveError(
1338
+ f"{where}.geometry.Type: {geom['type']!r} is not one of {sorted(GEOMETRY_TYPES)}"
1339
+ )
1340
+ _validate_data_item(geom["data_item"], f"{where}.geometry.data_item")
1341
+
1342
+ seen: Dict[Tuple[str, str], int] = {}
1343
+ for i, attr in enumerate(g["attributes"]):
1344
+ at = f"{where}.attributes[{i}]"
1345
+ if attr["attribute_type"] not in ATTRIBUTE_TYPES:
1346
+ raise YmfArchiveError(
1347
+ f"{at}.attribute_type: {attr['attribute_type']!r} is not one of "
1348
+ f"{sorted(ATTRIBUTE_TYPES)}"
1349
+ )
1350
+ if attr["center"] not in CENTERINGS:
1351
+ raise YmfArchiveError(
1352
+ f"{at}.center: {attr['center']!r} is not one of {sorted(CENTERINGS)}"
1353
+ )
1354
+ # Viewers keep fields on different entities apart (point data and
1355
+ # cell data are separate namespaces in VTK), so the same name may
1356
+ # appear once per centering -- exporters commonly write T both
1357
+ # cell- and node-centred. Twice on the same entity is a duplicate.
1358
+ key = (attr["name"], attr["center"])
1359
+ if key in seen:
1360
+ raise YmfArchiveError(
1361
+ f"{at}.name: duplicate {attr['center']}-centred attribute name "
1362
+ f"{attr['name']!r} (also at {where}.attributes[{seen[key]}]); "
1363
+ "viewers key fields by name, so duplicates silently shadow "
1364
+ "each other"
1365
+ )
1366
+ seen[key] = i
1367
+ _validate_data_item(attr["data_item"], f"{at}.data_item")
1368
+
1369
+ if "facets" in g:
1370
+ _validate_facets(g, f"{where}.facets")
1371
+ if "provenance" in g:
1372
+ for i, entry in enumerate(g["provenance"]["files"]):
1373
+ if not _SHA256.match(entry["sha256"]):
1374
+ raise YmfArchiveError(
1375
+ f"{where}.provenance.files[{i}].sha256: {entry['sha256']!r} is "
1376
+ "not a SHA-256 digest (64 hexadecimal digits)")
1377
+ f = g["provenance"].get("fingerprint")
1378
+ if f is not None and not _SHA256.match(f["sha256"]):
1379
+ raise YmfArchiveError(
1380
+ f"{where}.provenance.fingerprint.sha256: {f['sha256']!r} is not a "
1381
+ "SHA-256 digest (64 hexadecimal digits)")
1382
+
1383
+
1384
+ def _validate_facets(g: Dict[str, Any], where: str) -> None:
1385
+ """The facet list's structure, and its tags where they are inline.
1386
+
1387
+ Tags held in an HDF5 file are not read here (validation stays O(1) per
1388
+ field); :func:`ymf.mesh.check_facets` reads them.
1389
+ """
1390
+ f = g["facets"]
1391
+ cell_type = g["topology"]["type"]
1392
+ facet_topo = f["topology"]
1393
+ allowed = _FACET_TYPES.get(cell_type)
1394
+ if allowed is None and cell_type != "Mixed":
1395
+ raise YmfArchiveError(
1396
+ f"{where}: a {cell_type} grid cannot carry a facet list; facets are "
1397
+ "for unstructured grids")
1398
+ if allowed is not None and facet_topo["type"] not in allowed:
1399
+ raise YmfArchiveError(
1400
+ f"{where}.topology.type: the facets of {cell_type} cells are "
1401
+ f"{' or '.join(sorted(allowed))}, not {facet_topo['type']!r}")
1402
+ if facet_topo["type"] not in KNOWN_TOPOLOGY_TYPES:
1403
+ raise YmfArchiveError(
1404
+ f"{where}.topology.type: {facet_topo['type']!r} is not a known topology type")
1405
+ _validate_data_item(facet_topo["data_item"], f"{where}.topology.data_item")
1406
+ if facet_topo["data_item"]["data_type"] not in _INTEGER_DATA_TYPES:
1407
+ raise YmfArchiveError(f"{where}.topology.data_item: node numbers must be integers")
1408
+ if f["view"] not in FACET_VIEWS:
1409
+ raise YmfArchiveError(
1410
+ f"{where}.view: {f['view']!r} is not one of {sorted(FACET_VIEWS)}")
1411
+ tags = f["tags"]["data_item"]
1412
+ _validate_data_item(tags, f"{where}.tags.data_item")
1413
+ if tags["data_type"] not in ("Int", "UInt"):
1414
+ raise YmfArchiveError(
1415
+ f"{where}.tags.data_item.data_type: tags are integers (Int), not "
1416
+ f"{tags['data_type']!r}")
1417
+ n = facet_topo["number_of_elements"]
1418
+ dims = list(tags["dimensions"])
1419
+ if dims not in ([n], [n, 1]):
1420
+ raise YmfArchiveError(
1421
+ f"{where}.tags.data_item.dimensions: one tag per facet, {[n]}, got {dims}")
1422
+ if "values" in tags:
1423
+ check_facet_tags(tags["values"], f["view"], f"{where}.tags")
1424
+
1425
+
1426
+ def check_facet_tags(tags: Iterable[int], view: str, where: str = "facets.tags") -> None:
1427
+ """Refuse facet tags the view cannot hold: below -1 anywhere, and -1 in a
1428
+ global mesh (a rank interface exists only once the mesh is partitioned)."""
1429
+ lowest = min((int(t) for t in tags), default=0)
1430
+ if lowest < -1:
1431
+ raise YmfArchiveError(
1432
+ f"{where}: tag {lowest} is not a tag; 0 is untagged, >0 a condition, "
1433
+ "-1 a rank interface")
1434
+ if lowest == -1 and view == "global":
1435
+ raise YmfArchiveError(
1436
+ f"{where}: tag -1 marks a rank interface, which a global mesh never "
1437
+ "stores; the partitioner (or a per-rank reader) sets it, in a "
1438
+ "subdomain view")
1439
+
1440
+
1441
+ def validate_approximation(domain: Dict[str, Any]) -> Dict[str, Any]:
1442
+ """Check ``domain`` is structurally sound; return it canonicalized.
1443
+
1444
+ This is the solver-side half of the trust boundary: it verifies
1445
+ structure, not semantics. It checks that required keys are present,
1446
+ that closed-set fields (``AttributeType``, ``Center``, ``DataType``,
1447
+ ``Format``, topology and geometry types) hold legal values, and that no
1448
+ grid has two attributes of the same name. It does **not** check units,
1449
+ dimensional consistency, or standard names -- see the module docstring.
1450
+
1451
+ Raises :class:`YmfArchiveError` naming the offending path.
1452
+ """
1453
+ canonical = canonicalize_approximation(domain)
1454
+ for i, instant in enumerate(canonical.get("times", [])):
1455
+ for name, space in instant["spaces"].items():
1456
+ where = f"times[{i}].spaces[{name}]"
1457
+ if "spatial_collection" in space:
1458
+ if not space["spatial_collection"]:
1459
+ raise YmfArchiveError(f"{where}.spatial_collection: must not be empty")
1460
+ for j, g in enumerate(space["spatial_collection"]):
1461
+ _validate_grid_like(g, f"{where}.spatial_collection[{j}]")
1462
+ else:
1463
+ _validate_grid_like(space, where)
1464
+ return canonical
1465
+
1466
+
1467
+ def check_dimensions(item: Dict[str, Any], shape: Sequence[int], where: str = "data_item") -> None:
1468
+ """Assert a DataItem's declared ``Dimensions`` match an array's shape.
1469
+
1470
+ The cheapest high-value check at the boundary: a mismatch here is the
1471
+ failure mode where an archive is written without error and then loads
1472
+ as garbage, or not at all, in a viewer. Call it where the array is
1473
+ still in hand.
1474
+
1475
+ ``shape`` is compared flattened-length-wise as well as element-wise, so
1476
+ declaring ``[N*k]`` for an ``(N, k)`` array is accepted -- that is a
1477
+ normal and intentional thing to do for XDMF connectivity arrays.
1478
+ """
1479
+ declared = [int(d) for d in item["dimensions"]]
1480
+ actual = [int(s) for s in shape]
1481
+ if declared == actual:
1482
+ return
1483
+ n_declared, n_actual = 1, 1
1484
+ for d in declared:
1485
+ n_declared *= d
1486
+ for s in actual:
1487
+ n_actual *= s
1488
+ if n_declared != n_actual:
1489
+ raise YmfArchiveError(
1490
+ f"{where}.dimensions: declared {declared} ({n_declared} values) but "
1491
+ f"the array has shape {actual} ({n_actual} values)"
1492
+ )
1493
+
1494
+
1495
+ # ---------------------------------------------------------------------------
1496
+ # YAML serialization
1497
+ # ---------------------------------------------------------------------------
1498
+
1499
+
1500
+ class _ArchiveDumper(_YamlDumper):
1501
+ """The libyaml dumper, writing inline ``Values`` on one line."""
1502
+
1503
+ def ignore_aliases(self, data):
1504
+ # An archive repeats a record (the ADR form, the software versions)
1505
+ # in each output; written out each time, so each output reads alone.
1506
+ return True
1507
+
1508
+
1509
+ def _represent_str(dumper, data):
1510
+ # multi-line text (derivations, solution formulas) as a readable | block
1511
+ style = "|" if "\n" in data else None
1512
+ return dumper.represent_scalar("tag:yaml.org,2002:str", data, style=style)
1513
+
1514
+
1515
+ _SHORT_LIST = 72
1516
+
1517
+
1518
+ def _represent_list(dumper, data):
1519
+ # a short list of scalars on one line: unknowns: [v, p], cells: [4, 8]
1520
+ scalar = all(isinstance(x, (int, float, bool, type(None)))
1521
+ or isinstance(x, str) and "\n" not in x for x in data)
1522
+ flow = scalar and sum(len(str(x)) + 2 for x in data) <= _SHORT_LIST
1523
+ return dumper.represent_sequence("tag:yaml.org,2002:seq", data, flow_style=flow)
1524
+
1525
+
1526
+ _ArchiveDumper.add_representer(str, _represent_str)
1527
+ _ArchiveDumper.add_representer(list, _represent_list)
1528
+ _ArchiveDumper.add_representer(
1529
+ _FlowList,
1530
+ lambda dumper, data: dumper.represent_sequence(
1531
+ "tag:yaml.org,2002:seq", data, flow_style=True))
1532
+
1533
+
1534
+ def _dump(obj: Any) -> str:
1535
+ if not HAVE_LIBYAML:
1536
+ warnings.warn(
1537
+ "pyyaml has no libyaml C extension; YMF archive writes are about "
1538
+ "3.2x slower than they need to be. Call "
1539
+ "ymf.archive.require_libyaml() at startup to make this an error.",
1540
+ RuntimeWarning,
1541
+ stacklevel=3,
1542
+ )
1543
+ return yaml.dump(
1544
+ obj, Dumper=_ArchiveDumper, default_flow_style=False, sort_keys=False,
1545
+ allow_unicode=True,
1546
+ )
1547
+
1548
+
1549
+ # PyYAML implements YAML 1.1, whose float grammar wants a decimal point and
1550
+ # a signed exponent. So "1.0e-10" is a number while "1e-10", "1E-10",
1551
+ # "1e+10", "-1e-10" and "1.5e3" all come back as *strings*. strictyaml,
1552
+ # which reads a spec as written, accepts every one of them as a number.
1553
+ #
1554
+ # That left the same file meaning two different things depending on which
1555
+ # reader saw it: a spec validated as a file had a numeric tolerance, and the
1556
+ # same spec carried inside an archive had a string. Nothing warned; the
1557
+ # value simply stopped being a number somewhere downstream.
1558
+ #
1559
+ # This resolver adds the exponent forms YAML 1.2 and JSON accept. It is
1560
+ # registered on a subclass, so pyyaml's own SafeLoader -- which other code
1561
+ # in the same process may be using -- is left exactly as it was.
1562
+ _YAML12_FLOAT = re.compile(
1563
+ r"^[-+]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)[eE][-+]?[0-9]+$"
1564
+ )
1565
+
1566
+
1567
+ class _SpecLoader(_YamlLoader): # noqa: D401 - a loader, not a function
1568
+ """``_YamlLoader`` that also reads YAML 1.2 scientific notation."""
1569
+
1570
+
1571
+ _SpecLoader.add_implicit_resolver(
1572
+ "tag:yaml.org,2002:float", _YAML12_FLOAT, list("-+.0123456789")
1573
+ )
1574
+
1575
+
1576
+ def _load(text: str) -> Any:
1577
+ return yaml.load(text, Loader=_SpecLoader)
1578
+
1579
+
1580
+ def write_ymf(
1581
+ domain: Dict[str, Any],
1582
+ path: str | Path,
1583
+ extra: Optional[Any] = None,
1584
+ *,
1585
+ validate: bool = True,
1586
+ ) -> None:
1587
+ """Write a domain as a ``.ymf`` YAML document.
1588
+
1589
+ Parameters
1590
+ ----------
1591
+ domain:
1592
+ The domain dict. Canonicalized on the way out, so the file always
1593
+ has every defaultable field explicit.
1594
+ extra:
1595
+ Optional non-archive YMF content (``model``, ``solution_paths``,
1596
+ ``vvuq``, ...) to carry alongside. Unlike the XDMF path, which has
1597
+ to base64 it into an ``<Information>`` element, YAML holds it
1598
+ directly and readably.
1599
+ validate:
1600
+ Run :func:`validate_approximation` first. Leave this on unless you are
1601
+ deliberately writing a document you know to be partial.
1602
+ """
1603
+ checked = validate_approximation(domain) if validate else canonicalize_approximation(domain)
1604
+ document: Dict[str, Any] = {"ymf_archive_version": ARCHIVE_FORMAT_VERSION, "domain": checked}
1605
+ if extra is not None:
1606
+ document["extra"] = extra
1607
+ Path(path).write_text(_dump(document), encoding="utf-8")
1608
+
1609
+
1610
+ def append_step(
1611
+ path: str | Path,
1612
+ instant_or_collection: Any,
1613
+ step: Optional[Dict[str, Any]] = None,
1614
+ *,
1615
+ fsync: bool = False,
1616
+ ) -> None:
1617
+ """Append one instant to a ``.ymf`` file, without rewriting it.
1618
+
1619
+ A writer that produces a timestep at a time should not have to rewrite
1620
+ the whole document to record it. Rewriting is O(steps) per step, which
1621
+ is O(steps^2) over a run -- an inheritance from XML, where a document
1622
+ has to be closed to be well formed. YAML has no such requirement: a
1623
+ stream of documents separated by ``---`` is valid after any complete
1624
+ document, so an instant can simply be appended and flushed.
1625
+
1626
+ The file therefore has two shapes, and :func:`read_ymf` accepts both:
1627
+
1628
+ * **one document**, what :func:`write_ymf` produces, with every instant
1629
+ in ``times``. This is the canonical form and what a completed run
1630
+ leaves behind.
1631
+ * **a stream**: that same document first, then one document per
1632
+ instant. This is what a run in progress leaves, and what a run that
1633
+ was killed leaves for good.
1634
+
1635
+ ``instant`` is ``{"time": t, "spaces": {name: grid_or_spatial}}``. It
1636
+ holds every space known at that instant, so a record names no collection
1637
+ and a space first archived at step 40 is just a key that first appears
1638
+ in the 41st record. An instant is also the unit of atomicity: a run
1639
+ killed mid-write loses a whole instant or none of it, never one space of
1640
+ it.
1641
+
1642
+ The format 1 call, ``append_step(path, collection, step)``, still works
1643
+ and appends a record for one space at one time; :func:`read_ymf` joins
1644
+ such records into instants on read.
1645
+
1646
+ ``fsync`` forces the write to disk rather than to the page cache. It is
1647
+ off by default: a flush already survives the process dying, which is the
1648
+ case this exists for, and only a machine losing power needs more.
1649
+ """
1650
+ if step is None:
1651
+ record = {"step": instant_or_collection}
1652
+ else:
1653
+ record = {"collection": instant_or_collection, "step": step}
1654
+ text = _dump(record)
1655
+ with open(path, "a", encoding="utf-8") as stream:
1656
+ # One write, so a concurrent reader sees a whole record or none. The
1657
+ # trailing "..." is YAML's explicit document-end marker, and it is
1658
+ # what makes truncation detectable: a half-written step is usually
1659
+ # still *valid* YAML -- cutting inside a mapping leaves a shorter
1660
+ # mapping -- so a reader cannot tell a partial record from a complete
1661
+ # one by parsing it. It can tell by the marker being absent.
1662
+ stream.write(_STEP_START + text + _STEP_END)
1663
+ stream.flush()
1664
+ if fsync:
1665
+ os.fsync(stream.fileno())
1666
+
1667
+
1668
+ def read_ymf(path: str | Path) -> Tuple[Dict[str, Any], Optional[Any]]:
1669
+ """Read a ``.ymf`` document written by :func:`write_ymf`.
1670
+
1671
+ Returns a ``(domain, extra)`` tuple, the domain always in format 2
1672
+ (a format 1 document is upgraded; see :func:`transpose_collections`). Raises :class:`YmfArchiveError` on
1673
+ a format-version mismatch, so an archive from an incompatible writer
1674
+ fails with a clear message rather than a confusing downstream
1675
+ ``KeyError``.
1676
+
1677
+ Reads both shapes described in :func:`append_step`: a single document,
1678
+ or that document followed by one per appended step. An appended instant
1679
+ is added to ``times``; a format 1 record, which names its collection, is
1680
+ joined into the instant at its time.
1681
+
1682
+ A trailing partial document -- a run killed mid-write -- is dropped,
1683
+ with every complete step before it kept. That is the whole point of
1684
+ appending: the archive degrades by one step rather than by all of them.
1685
+ """
1686
+ text = Path(path).read_text(encoding="utf-8")
1687
+ documents, truncated = _load_stream(text)
1688
+ if not documents:
1689
+ raise YmfArchiveError(f"{path}: no YAML document found")
1690
+ document = documents[0]
1691
+ if not isinstance(document, dict):
1692
+ raise YmfArchiveError(f"{path}: expected a YAML mapping at the top level")
1693
+ version = document.get("ymf_archive_version")
1694
+ if version not in _READABLE_FORMAT_VERSIONS:
1695
+ raise YmfArchiveError(
1696
+ f"{path}: archive format version {version!r}, but this ymf writes "
1697
+ f"version {ARCHIVE_FORMAT_VERSION} and reads "
1698
+ f"{', '.join(str(v) for v in _READABLE_FORMAT_VERSIONS)}"
1699
+ )
1700
+ domain = _upgrade_domain(document.get("domain", {}))
1701
+ for record in documents[1:]:
1702
+ if not isinstance(record, dict) or "step" not in record:
1703
+ raise YmfArchiveError(
1704
+ f"{path}: appended document is not a step record; got "
1705
+ f"{sorted(record) if isinstance(record, dict) else type(record).__name__}"
1706
+ )
1707
+ if "collection" in record:
1708
+ _fold_step(domain, record["collection"], record["step"])
1709
+ elif version == 1:
1710
+ raise YmfArchiveError(
1711
+ f"{path}: a format 1 document holds records that name a "
1712
+ "collection; this one holds an instant")
1713
+ else:
1714
+ domain.setdefault("times", []).append(fold_archive_keys(record["step"]))
1715
+ if truncated:
1716
+ warnings.warn(
1717
+ f"{path}: the last appended step is incomplete and was dropped "
1718
+ f"-- the run that wrote it did not finish. The {len(documents) - 1} "
1719
+ f"complete steps before it were kept.",
1720
+ RuntimeWarning,
1721
+ stacklevel=2,
1722
+ )
1723
+ return domain, document.get("extra")
1724
+
1725
+
1726
+ def _upgrade_domain(domain: Any) -> Dict[str, Any]:
1727
+ """A domain in format 2 shape, without canonicalizing it.
1728
+
1729
+ Cheaper than :func:`canonicalize_approximation`, which :func:`read_ymf` leaves
1730
+ to the caller as it always has: this only moves format 1's steps into
1731
+ instants.
1732
+ """
1733
+ domain = fold_archive_keys(domain)
1734
+ if not isinstance(domain, dict) or "times" in domain:
1735
+ return domain
1736
+ collections = domain.get("time_collections")
1737
+ if collections is None and domain.get("time_collection") is not None:
1738
+ collections = [domain["time_collection"]]
1739
+ if collections is None:
1740
+ return domain
1741
+ return dict({k: v for k, v in domain.items()
1742
+ if k not in ("time_collections", "time_collection")},
1743
+ times=transpose_collections(collections))
1744
+
1745
+
1746
+ def _fold_step(domain: Dict[str, Any], collection: str, step: Dict[str, Any]) -> None:
1747
+ """Put a record that names its collection into the instant at its time.
1748
+
1749
+ The format 1 record: one space at one time. It joins the last instant if
1750
+ that is at the same time and lacks the space, as a writer that goes
1751
+ space by space within a step produces them, and otherwise starts one.
1752
+ """
1753
+ step = fold_archive_keys(step)
1754
+ grid_like = {k: v for k, v in step.items() if k != "time"}
1755
+ _add_to_space(domain, step["time"], collection, grid_like)
1756
+
1757
+
1758
+ def _load_stream(text: str) -> Tuple[List[Any], bool]:
1759
+ """Every complete document in ``text``, and whether a partial one followed.
1760
+
1761
+ Completeness is decided by the document-end marker :func:`append_step`
1762
+ writes, not by whether the text parses. A writer killed mid-record
1763
+ usually leaves something that still parses -- truncating a mapping
1764
+ gives a shorter mapping -- so parsing is not evidence of completeness.
1765
+ Anything after the last marker is a partial write and is dropped.
1766
+ """
1767
+ end = text.rfind(_STEP_END)
1768
+ if end == -1:
1769
+ # no appended steps; a partial first one may still be there
1770
+ start = text.find(_STEP_START)
1771
+ if start == -1:
1772
+ return list(yaml.load_all(text, Loader=_SpecLoader)), False
1773
+ return list(yaml.load_all(text[:start], Loader=_SpecLoader)), True
1774
+ complete = text[: end + len(_STEP_END)]
1775
+ truncated = text[end + len(_STEP_END):].strip() != ""
1776
+ return list(yaml.load_all(complete, Loader=_SpecLoader)), truncated
1777
+
1778
+
1779
+ def load_array(item: Dict[str, Any], base_dir: str | Path = "."):
1780
+ """The array a DataItem holds or points at, as a numpy array.
1781
+
1782
+ Inline ``Values`` are reshaped to ``Dimensions``; an HDF5 reference
1783
+ ``"file.h5:/dataset"`` is read with the file relative to ``base_dir``
1784
+ (the archive's directory). Needs numpy, and h5py for references --
1785
+ imported here, so the archive core still needs neither.
1786
+ """
1787
+ import numpy
1788
+ if "values" in item:
1789
+ dtype = "f%d" % item["precision"] if item["data_type"] == "Float" else (
1790
+ "u%d" if item["data_type"] in ("UInt", "UChar") else "i%d") % item["precision"]
1791
+ return numpy.array(item["values"], dtype=dtype).reshape(item["dimensions"])
1792
+ if item.get("format") == "HDF" and "data" in item:
1793
+ import h5py
1794
+ filename, dataset = str(item["data"]).rsplit(":", 1)
1795
+ with h5py.File(Path(base_dir) / filename, "r") as f:
1796
+ return f[dataset][()]
1797
+ raise YmfArchiveError("load_array: no inline Values or HDF5 reference in %r" % (item,))
1798
+
1799
+
1800
+ def _data_items(domain: Dict[str, Any]):
1801
+ """Every DataItem dict of a canonical domain, with a readable path.
1802
+
1803
+ Paths are ``<space>/<n>/...`` where ``n`` counts that space's own
1804
+ steps, so they do not depend on which other spaces an instant holds.
1805
+ """
1806
+ for name in space_names(domain):
1807
+ for i, (_, space) in enumerate(series(domain, name)):
1808
+ for j, g in enumerate(space.get("spatial_collection", [space])):
1809
+ where = "%s/%d%s" % (name, i, "" if "topology" in space else "/%d" % j)
1810
+ yield where + "/Topology", g["topology"]
1811
+ yield where + "/Geometry", g["geometry"]
1812
+ for a in g["attributes"]:
1813
+ yield "%s/%s/%s" % (where, a.get("center", "Node"), a["name"]), a
1814
+ if "facets" in g:
1815
+ yield where + "/Facets/Topology", g["facets"]["topology"]
1816
+ yield where + "/Facets/Tags", g["facets"]["tags"]
1817
+
1818
+
1819
+ def step_indices(spec: Any, n: int) -> List[int]:
1820
+ """The step indices ``spec`` picks out of ``n`` steps, in order.
1821
+
1822
+ ``spec`` is a comma-separated list of Python indices and slices --
1823
+ ``"-1"`` the last step, ``"0,5,9"``, ``"2:8"``, ``"::10"`` every tenth,
1824
+ ``"-3:"`` the last three -- or a sequence of ints. Negative indices
1825
+ count from the end as in Python; an index outside ``range(n)`` is
1826
+ refused rather than silently dropped, since it names a step the
1827
+ archive does not have.
1828
+ """
1829
+ if isinstance(spec, str):
1830
+ parts = [p.strip() for p in spec.split(",") if p.strip()]
1831
+ else:
1832
+ parts = [str(int(i)) for i in spec]
1833
+ chosen: List[int] = []
1834
+ for part in parts:
1835
+ if ":" in part:
1836
+ try:
1837
+ bounds = [int(b) if b.strip() else None for b in part.split(":")]
1838
+ except ValueError:
1839
+ raise YmfArchiveError("step selection %r is not a slice" % (part,)) from None
1840
+ if len(bounds) > 3:
1841
+ raise YmfArchiveError("step selection %r has too many colons" % (part,))
1842
+ indices = list(range(n))[slice(*bounds)]
1843
+ else:
1844
+ try:
1845
+ index = int(part)
1846
+ except ValueError:
1847
+ raise YmfArchiveError(
1848
+ "step selection %r is neither an index nor a slice" % (part,)) from None
1849
+ if not -n <= index < n:
1850
+ raise YmfArchiveError(
1851
+ "step %d does not exist; the archive holds %d step(s)" % (index, n))
1852
+ indices = [index % n]
1853
+ for i in indices:
1854
+ if i not in chosen:
1855
+ chosen.append(i)
1856
+ return chosen
1857
+
1858
+
1859
+ def select_approximation(
1860
+ domain: Dict[str, Any],
1861
+ *,
1862
+ collections: Optional[Sequence[str]] = None,
1863
+ fields: Optional[Sequence[str]] = None,
1864
+ steps: Any = None,
1865
+ ) -> Dict[str, Any]:
1866
+ """A copy of ``domain`` holding only the chosen collections, fields and steps.
1867
+
1868
+ An archive of a long run with several spaces and a dozen fields is more
1869
+ than a viewer wants to open at once, and more than anyone wants to copy;
1870
+ this is the cherry-picking behind ``ymf2xmf --collection/--field/--steps``.
1871
+
1872
+ ``collections`` names the time collections to keep, each either a
1873
+ collection's exact name or a substring of one (``"c0p2"`` for
1874
+ ``Mesh_c0p2_Lagrange``). ``fields`` names the attributes to keep on
1875
+ every grid; ``steps`` is a :func:`step_indices` selection applied to
1876
+ every collection. ``None`` keeps everything. A name that matches
1877
+ nothing is refused, with what the archive does hold, rather than
1878
+ yielding an emptier archive than was asked for.
1879
+ """
1880
+ import copy
1881
+
1882
+ domain = canonicalize_approximation(domain)
1883
+ names = space_names(domain)
1884
+ chosen_names = names
1885
+ if collections is not None:
1886
+ chosen_names = []
1887
+ for want in collections:
1888
+ matched = [n for n in names if n == want or want in n]
1889
+ if not matched:
1890
+ raise YmfArchiveError(
1891
+ "no collection matches %r; the archive holds %s" % (want, names))
1892
+ for n in matched:
1893
+ if n not in chosen_names:
1894
+ chosen_names.append(n)
1895
+ # keep the archive's own order of spaces, not the order asked for
1896
+ chosen_names = [n for n in names if n in chosen_names]
1897
+
1898
+ def grids_of(space: Dict[str, Any]):
1899
+ if "spatial_collection" in space:
1900
+ return space["spatial_collection"]
1901
+ return [space]
1902
+
1903
+ if fields is not None:
1904
+ present = set()
1905
+ for instant in domain.get("times", []):
1906
+ for n in chosen_names:
1907
+ for g in grids_of(instant["spaces"].get(n, {"attributes": []})):
1908
+ present.update(a["name"] for a in g.get("attributes", []))
1909
+ missing = [f for f in fields if f not in present]
1910
+ if missing:
1911
+ raise YmfArchiveError(
1912
+ "no field named %s; the archive holds %s"
1913
+ % (", ".join(repr(f) for f in missing), sorted(present)))
1914
+
1915
+ # An instant that holds none of the chosen spaces is not in the selection,
1916
+ # and `steps` then counts the instants that remain.
1917
+ kept = [i for i in domain.get("times", [])
1918
+ if any(n in i["spaces"] for n in chosen_names)]
1919
+ indices = (step_indices(steps, len(kept)) if steps is not None
1920
+ else list(range(len(kept))))
1921
+ new_times = []
1922
+ for k in indices:
1923
+ instant = kept[k]
1924
+ spaces = {}
1925
+ for n in chosen_names:
1926
+ if n not in instant["spaces"]:
1927
+ continue
1928
+ space = copy.deepcopy(instant["spaces"][n])
1929
+ if fields is not None:
1930
+ for g in grids_of(space):
1931
+ g["attributes"] = [a for a in g.get("attributes", [])
1932
+ if a["name"] in fields]
1933
+ spaces[n] = space
1934
+ new_times.append({"time": instant["time"], "spaces": spaces})
1935
+ return dict(domain, times=new_times)
1936
+
1937
+
1938
+ def inline_approximation(domain: Dict[str, Any], base_dir: str | Path = ".") -> Dict[str, Any]:
1939
+ """A copy of ``domain`` with every referenced array copied in as ``Values``.
1940
+
1941
+ The result needs no HDF5 file or sidecar: the ``.ymf`` (and the ``.xmf``
1942
+ derived from it) is self-contained.
1943
+ """
1944
+ import copy
1945
+ out = copy.deepcopy(canonicalize_approximation(domain))
1946
+ for _, owner in _data_items(out):
1947
+ item = owner["data_item"]
1948
+ if "values" in item:
1949
+ continue
1950
+ array = load_array(item, base_dir)
1951
+ owner["data_item"] = data_item_for(array, inline=True, dimensions=item["dimensions"])
1952
+ return validate_approximation(out)
1953
+
1954
+
1955
+ def rebase_approximation(domain: Dict[str, Any], from_dir: str | Path,
1956
+ to_dir: str | Path) -> Dict[str, Any]:
1957
+ """A copy of ``domain`` whose HDF5 references resolve from ``to_dir``.
1958
+
1959
+ References are relative to the archive that holds them. An output
1960
+ carried into an archive in another directory (by ``extends``) keeps
1961
+ pointing at the same files.
1962
+ """
1963
+ import copy
1964
+ import os
1965
+ out = copy.deepcopy(canonicalize_approximation(domain))
1966
+ if Path(from_dir).resolve() == Path(to_dir).resolve():
1967
+ return out
1968
+ for _, owner in _data_items(out):
1969
+ item = owner["data_item"]
1970
+ if item.get("format") == "HDF" and "data" in item:
1971
+ filename, dataset = str(item["data"]).rsplit(":", 1)
1972
+ moved = os.path.relpath(Path(from_dir).resolve() / filename,
1973
+ Path(to_dir).resolve())
1974
+ item["data"] = "%s:%s" % (Path(moved).as_posix(), dataset)
1975
+ return out
1976
+
1977
+
1978
+ def approximation_arrays(domain: Dict[str, Any], base_dir: str | Path = "."):
1979
+ """{path: array} for every DataItem, however each is stored."""
1980
+ return {where: load_array(owner["data_item"], base_dir)
1981
+ for where, owner in _data_items(canonicalize_approximation(domain))}
1982
+
1983
+
1984
+ # ---------------------------------------------------------------------------
1985
+ # documents: a specification, or an archive -- the specification plus the
1986
+ # outputs computed from it (see ymf.closure)
1987
+ # ---------------------------------------------------------------------------
1988
+
1989
+
1990
+ def _release(version: str) -> Tuple[int, ...]:
1991
+ """(major, minor, patch) of a version string; () if it has none."""
1992
+ import re
1993
+ m = re.match(r"(\d+)(?:\.(\d+))?(?:\.(\d+))?", str(version))
1994
+ return tuple(int(g) for g in m.groups() if g is not None) if m else ()
1995
+
1996
+
1997
+ def package_version() -> str:
1998
+ """The installed ymf version: the version every document is written as."""
1999
+ from ymf import __version__
2000
+ return __version__
2001
+
2002
+
2003
+ def check_version(document: Dict[str, Any], where: str = "document") -> None:
2004
+ """Refuse a document written by a newer ymf than this one.
2005
+
2006
+ The ``ymf:`` key holds the package version that wrote a document; the
2007
+ schema version is the package version. A newer writer may use fields
2008
+ this reader does not know, so it is refused rather than half-read. An
2009
+ unversioned (development) reader cannot tell, and does not refuse.
2010
+ """
2011
+ written = _release(document.get("ymf", ""))
2012
+ reader = _release(package_version())
2013
+ if written and reader and reader != (0, 0, 0) and written > reader:
2014
+ raise YmfArchiveError(
2015
+ "%s was written by ymf %s, newer than this ymf %s; upgrade ymf to read it"
2016
+ % (where, document["ymf"], package_version()))
2017
+
2018
+
2019
+ def is_archive_text(text: str) -> bool:
2020
+ """True if this YMF text is an archive rather than a bare specification.
2021
+
2022
+ An archive carries the ``ymf:`` version it was written by and its
2023
+ ``outputs:``; a specification carries neither, so the top-level keys
2024
+ are enough to tell them apart.
2025
+
2026
+ Deliberately a test on the *text*, and deliberately here in the core.
2027
+ Which loader to use is the one decision that has to be made before any
2028
+ loader runs -- an archive holds arrays and must go to the fast pyyaml
2029
+ path, a specification to the validating one -- so asking cannot be
2030
+ allowed to require the validating stack. It lived in ymf.compose until
2031
+ 2026-10-13, which meant a core-only install could not ask the question
2032
+ at all: proteus's ymf_run imported it and died on "No module named
2033
+ 'strictyaml'" (cekees/proteus#46).
2034
+ """
2035
+ return re.search(r"^(ymf|outputs):", text, re.M) is not None
2036
+
2037
+
2038
+ def read_document(path: str | Path) -> Dict[str, Any]:
2039
+ """Load a YMF document (spec or archive) as plain data, quickly.
2040
+
2041
+ pyyaml with libyaml, no schema: archives hold arrays, and strictyaml
2042
+ is far too slow for them. Validate the specification part with
2043
+ ymf.schema (ymf.closure.load does).
2044
+ """
2045
+ document = _load(Path(path).read_text(encoding="utf-8"))
2046
+ if not isinstance(document, dict):
2047
+ raise YmfArchiveError(f"{path}: expected a YAML mapping at the top level")
2048
+ check_version(document, str(path))
2049
+ return document
2050
+
2051
+
2052
+ def write_document(path: str | Path, document: Dict[str, Any]) -> None:
2053
+ """Write a spec or archive: ``ymf:`` first, then the rest in order.
2054
+
2055
+ Each output's ``approximation`` is validated and canonicalized, and
2056
+ written with one-line Dimensions and Values.
2057
+ """
2058
+ out: Dict[str, Any] = {"ymf": package_version()}
2059
+ for key, value in document.items():
2060
+ if key == "ymf":
2061
+ continue
2062
+ if key == "outputs":
2063
+ value = {k: _canonical_output(k, v) for k, v in value.items()}
2064
+ out[key] = value
2065
+ Path(path).write_text(_dump(out), encoding="utf-8")
2066
+
2067
+
2068
+ def _canonical_output(key: str, output: Dict[str, Any]) -> Dict[str, Any]:
2069
+ output = dict(output)
2070
+ if "approximation" in output:
2071
+ try:
2072
+ output["approximation"] = validate_approximation(output["approximation"])
2073
+ except YmfArchiveError as exc:
2074
+ raise YmfArchiveError("outputs[%s].approximation: %s" % (key, exc)) from exc
2075
+ return output
2076
+
2077
+
2078
+ def dump_grid(g: Dict[str, Any]) -> str:
2079
+ """Serialize one grid to a YAML string.
2080
+
2081
+ For metadata that travels rather than lands in a file: a per-subdomain
2082
+ grid fragment stashed in an HDF5 dataset, or gathered across MPI. Pairs
2083
+ with :func:`load_grid`.
2084
+ """
2085
+ return _dump(g)
2086
+
2087
+
2088
+ def load_grid(text: str) -> Dict[str, Any]:
2089
+ """Inverse of :func:`dump_grid`."""
2090
+ return _load(text)
2091
+
2092
+
2093
+ # ---------------------------------------------------------------------------
2094
+ # The names before 2026-11 (docs/changes.md), kept for one release. They are
2095
+ # the same function objects, so a caller sees no difference, keyword
2096
+ # arguments included; a release should warn before they go.
2097
+ # ---------------------------------------------------------------------------
2098
+ new_domain = new_approximation
2099
+ validate_domain = validate_approximation
2100
+ canonicalize_domain = canonicalize_approximation
2101
+ select_domain = select_approximation
2102
+ rebase_domain = rebase_approximation
2103
+ inline_domain = inline_approximation
2104
+ domain_arrays = approximation_arrays