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/boundaries.py ADDED
@@ -0,0 +1,119 @@
1
+ """Boundary kind: how a boundary condition reaches the discrete problem (strong, weak, none), and a weak one's parameters.
2
+
3
+ A condition says *what* holds on a boundary (a value, a flux). Its ``imposed`` says *how the discrete problem enforces
4
+ it*, which is what picks the boundary term a kernel evaluates there (the engine's face kinds ``Strong``,
5
+ ``WeakDirichlet`` and ``Flux``; C19's gap note G8)::
6
+
7
+ - {region: inlet, variable: φ, type: dirichlet, only: inflow, imposed: strong} # rows of the system replaced
8
+ - {region: inlet, variable: φ, type: dirichlet, only: inflow, imposed: weak, # penalty and consistency terms
9
+ penalty: 100.0, form: symmetric}
10
+ - {region: outlet, variable: φ, type: neumann, value: 0.0} # none: the natural condition
11
+
12
+ * ``strong``: the unknown's degrees of freedom on the boundary are set to the value (a Dirichlet condition).
13
+ * ``weak``: the value is enforced through terms of the weak form (Nitsche): a penalty ``penalty / h`` and, by ``form``, the
14
+ adjoint consistency term: ``symmetric`` (SIPG), ``nonsymmetric`` (NIPG) or ``incomplete`` (IIPG, none). Dirichlet only.
15
+ * ``none``: nothing constrains the solution on the boundary; the boundary integral carries the given flux (Neumann, Robin)
16
+ or leaves with the solution's own trace (``open``).
17
+
18
+ The kind is what a condition's *type* allows: a Dirichlet condition (and the Dirichlet part of ``slip``, ``inflow``,
19
+ ``characteristic``) is ``strong`` or ``weak`` (default ``strong``); Neumann, Robin and ``open`` are ``none``;
20
+ ``periodic`` is none of them (the faces are identified). :func:`kind_of` gives the kind of a condition, stated or the
21
+ default; :func:`check_condition` refuses what does not make sense (a strong Neumann condition, a penalty on a strong
22
+ one); :func:`kinds` lists every condition of a document with its kind.
23
+
24
+ When an alias is expanded (``ymf.conditions``) the kind goes to the Dirichlet components only: ``slip, imposed: weak`` is
25
+ a weak normal condition and a natural tangential one. ``split_problem`` gives each condition's ``kind``, and for a weak
26
+ one its ``penalty`` and ``form``, so a generator picks the face kernel from the declaration and not from the model's name.
27
+
28
+ Stdlib only, like the rest of the spec core.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ from typing import Any, Dict, List, Optional
34
+
35
+ __all__ = ["BoundaryError", "BOUNDARY_KINDS", "WEAK_FORMS", "kind_of", "check_condition", "kinds"]
36
+
37
+
38
+ class BoundaryError(ValueError):
39
+ """A boundary kind a spec states that does not make sense."""
40
+
41
+
42
+ BOUNDARY_KINDS: Dict[str, str] = {
43
+ "strong": "the degrees of freedom on the boundary are set to the value",
44
+ "weak": "the value is enforced through penalty and consistency terms of the weak form (Nitsche)",
45
+ "none": "no constraint on the solution: the boundary integral carries the given flux, or the solution's own trace",
46
+ }
47
+
48
+ WEAK_FORMS: Dict[str, str] = {
49
+ "symmetric": "SIPG: the adjoint consistency term with the sign that keeps the form symmetric",
50
+ "nonsymmetric": "NIPG: the adjoint consistency term with the opposite sign",
51
+ "incomplete": "IIPG: no adjoint consistency term",
52
+ }
53
+
54
+ #: the types a condition's kind is chosen for (the Dirichlet part), and the types that are always ``none``
55
+ _DIRICHLET = ("dirichlet", "slip", "inflow", "characteristic")
56
+ _NATURAL = ("neumann", "robin", "open")
57
+
58
+
59
+ def kind_of(condition: Dict[str, Any]) -> Optional[str]:
60
+ """The boundary kind of a condition (an alias, or an abstract one): what it states, or its type's default. None for
61
+ ``periodic``."""
62
+ kind = condition.get("type")
63
+ if kind == "periodic":
64
+ return None
65
+ stated = condition.get("imposed")
66
+ if stated is not None:
67
+ return str(stated)
68
+ return "strong" if kind in _DIRICHLET else "none"
69
+
70
+
71
+ def check_condition(condition: Dict[str, Any], where: str) -> None:
72
+ """``imposed``, ``penalty`` and ``form`` of a condition agree with its type. Raises :class:`BoundaryError`."""
73
+ kind = condition.get("type")
74
+ stated = condition.get("imposed")
75
+ has_weak_keys = [k for k in ("penalty", "form") if condition.get(k) is not None]
76
+ if stated is not None and str(stated) not in BOUNDARY_KINDS:
77
+ raise BoundaryError("%s: imposed %s is not one of %s" % (where, stated, ", ".join(BOUNDARY_KINDS)))
78
+ if kind == "periodic":
79
+ if stated is not None or has_weak_keys:
80
+ raise BoundaryError("%s: a periodic condition identifies faces; it has no kind" % (where,))
81
+ return
82
+ if kind in _NATURAL and stated is not None and str(stated) != "none":
83
+ raise BoundaryError(
84
+ "%s: a %s condition is imposed none (the boundary integral carries it); %s is for a Dirichlet condition"
85
+ % (where, kind, stated))
86
+ if kind in _DIRICHLET and stated is not None and str(stated) == "none":
87
+ raise BoundaryError(
88
+ "%s: a %s condition imposes a value, strong or weak; to impose nothing give no condition, or open"
89
+ % (where, kind))
90
+ weak = kind_of(condition) == "weak"
91
+ if has_weak_keys and not weak:
92
+ raise BoundaryError("%s: %s belong to a weak condition (imposed: weak); this one is %s" % (
93
+ where, " and ".join(has_weak_keys), kind_of(condition)))
94
+ if condition.get("penalty") is not None:
95
+ try:
96
+ ok = float(condition["penalty"]) > 0
97
+ except (TypeError, ValueError):
98
+ ok = False
99
+ if not ok:
100
+ raise BoundaryError("%s: penalty %s is not a positive number" % (where, condition["penalty"]))
101
+ if condition.get("form") is not None and str(condition["form"]) not in WEAK_FORMS:
102
+ raise BoundaryError("%s: form %s is not one of %s" % (where, condition["form"], ", ".join(WEAK_FORMS)))
103
+
104
+
105
+ def kinds(doc: Dict[str, Any]) -> List[Dict[str, Any]]:
106
+ """Every boundary condition of the document, expanded, as ``{region, variable, type, [component], [only], kind,
107
+ [penalty], [form]}`` in order: what a solver reads to choose its boundary terms."""
108
+ from ymf.conditions import expand
109
+ from ymf.normalize import boundary_conditions
110
+ strong = ((expand(doc).get("model") or {}).get("strong_form") or {})
111
+ out = []
112
+ for bc in boundary_conditions(strong):
113
+ entry = {k: bc[k] for k in ("region", "variable", "type", "component", "only") if bc.get(k) is not None}
114
+ entry["kind"] = kind_of(bc)
115
+ for k in ("penalty", "form"):
116
+ if bc.get(k) is not None:
117
+ entry[k] = bc[k]
118
+ out.append(entry)
119
+ return out
ymf/cli.py ADDED
@@ -0,0 +1,307 @@
1
+ """Command line entry points.
2
+
3
+ Only ``ymf2xmf`` so far: it turns a ``.ymf`` archive into the ``.xmf`` that
4
+ ParaView and VisIt read.
5
+
6
+ This exists because of the campaign's decision that a solver writes YMF and
7
+ nothing else. XDMF is a *consumer* of a YMF archive, not a second format
8
+ the solver has to keep in step -- so the conversion happens here, on
9
+ demand, rather than in the writer. A solver that emits both has two
10
+ representations to keep consistent and will eventually fail to.
11
+
12
+ Deliberately in the ``pyyaml``-only core: this reads YAML and writes XML,
13
+ both of which :mod:`ymf.archive` and :mod:`ymf.xdmf` do without the
14
+ validation stack. Running the converter must not require ``ymf[spec]``.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import sys
21
+ from pathlib import Path
22
+ from typing import List, Optional, Sequence
23
+
24
+ from ymf.archive import (YmfArchiveError, canonicalize_approximation, read_ymf, select_approximation,
25
+ space_names, time_collections,
26
+ validate_approximation)
27
+ from ymf.xdmf import write_xdmf
28
+
29
+ __all__ = ["archive2xmf", "describe", "ymf2xmf", "ymf2xmf_main"]
30
+
31
+
32
+ def _default_output(source: Path) -> Path:
33
+ """``run.ymf`` -> ``run.xmf``, keeping any other suffixes intact."""
34
+ return source.with_suffix(".xmf")
35
+
36
+
37
+ def ymf2xmf(
38
+ source: str | Path,
39
+ output: Optional[str | Path] = None,
40
+ *,
41
+ validate: bool = True,
42
+ collections: Optional[Sequence[str]] = None,
43
+ fields: Optional[Sequence[str]] = None,
44
+ steps: Optional[str] = None,
45
+ ) -> Path:
46
+ """Write the ``.xmf`` for a ``.ymf`` archive. Returns the output path.
47
+
48
+ Parameters
49
+ ----------
50
+ source:
51
+ The ``.ymf`` archive.
52
+ output:
53
+ Where to write. Defaults to ``source`` with a ``.xmf`` suffix.
54
+ validate:
55
+ Check the archive's structure before converting. On by default: a
56
+ malformed archive is better reported here, with the offending
57
+ field named, than as a file a viewer silently mis-draws.
58
+ collections, fields, steps:
59
+ Convert only these: see :func:`ymf.archive.select_approximation`. The
60
+ ``.xmf`` then describes a part of the archive, which is what a
61
+ viewer opening one space, one field or one instant of a long run
62
+ wants; the ``.ymf`` is untouched.
63
+
64
+ The archive's ``extra`` payload -- ``model``, ``solution_paths``,
65
+ ``vvuq`` and anything else with no XDMF equivalent -- is carried into
66
+ the ``.xmf`` as the base64 ``<Information Name="YMF">`` element that
67
+ :func:`ymf.xdmf.read_xdmf` can recover. Generic XDMF consumers parse
68
+ and ignore it, so nothing is lost by converting and nothing is
69
+ imposed on the viewer.
70
+ """
71
+ source = Path(source)
72
+ domain, extra = read_ymf(source)
73
+ if not domain:
74
+ raise YmfArchiveError(
75
+ "%s holds no domain, so there is nothing to convert" % (source,))
76
+ domain = validate_approximation(domain) if validate else canonicalize_approximation(domain)
77
+ if collections is not None or fields is not None or steps is not None:
78
+ domain = select_approximation(domain, collections=collections, fields=fields, steps=steps)
79
+ destination = Path(output) if output is not None else _default_output(source)
80
+ write_xdmf(domain, destination, ymf_extra=extra)
81
+ return destination
82
+
83
+
84
+ def archive2xmf(
85
+ source: str | Path,
86
+ outdir: Optional[str | Path] = None,
87
+ keys: Optional[Sequence[str]] = None,
88
+ *,
89
+ validate: bool = True,
90
+ ) -> List[Path]:
91
+ """Write one ``.xmf`` per output of an archive. Returns the paths.
92
+
93
+ Each is named ``<stem>_<digest>.xmf`` after the output's key (beside
94
+ its ``<stem>_<digest>.h5``, if it has one), and
95
+ carries the realized spec and that output's record (everything but
96
+ its arrays) as the ``<Information Name="YMF">`` element.
97
+ """
98
+ from ymf.archive import read_document
99
+ from ymf.closure import archive_stem, file_stem
100
+ source = Path(source)
101
+ document = read_document(source)
102
+ outputs = document.get("outputs") or {}
103
+ if not outputs:
104
+ raise YmfArchiveError("%s holds no outputs, so there is nothing to convert" % (source,))
105
+ unknown = [k for k in keys or () if k not in outputs]
106
+ if unknown:
107
+ raise YmfArchiveError("%s has no output %s" % (source, ", ".join(unknown)))
108
+ spec = {k: v for k, v in document.items() if k != "outputs"}
109
+ outdir = Path(outdir) if outdir is not None else source.parent
110
+ written = []
111
+ for key in keys or list(outputs):
112
+ output = outputs[key]
113
+ domain = output.get("approximation")
114
+ if not domain:
115
+ continue
116
+ domain = validate_approximation(domain) if validate else canonicalize_approximation(domain)
117
+ record = {k: v for k, v in output.items() if k != "approximation"}
118
+ destination = outdir / (file_stem(archive_stem(source), key) + ".xmf")
119
+ write_xdmf(domain, destination, ymf_extra=dict(spec, output=key, record=record))
120
+ written.append(destination)
121
+ return written
122
+
123
+
124
+ def _is_archive(source: Path) -> bool:
125
+ """An archive in the current form: a spec with ``outputs``."""
126
+ import re
127
+ with open(source, encoding="utf-8") as f:
128
+ for line in f:
129
+ if re.match(r"(ymf|outputs):", line):
130
+ return True
131
+ if line.startswith("ymf_archive_version:"):
132
+ return False
133
+ return False
134
+
135
+
136
+ def _fields_of(collection) -> List[str]:
137
+ """Every field name any grid of the collection carries, in first-seen order."""
138
+ names: List[str] = []
139
+ for step in collection.get("data", []):
140
+ grids = step.get("spatial_collection", [step])
141
+ for g in grids:
142
+ for a in g.get("attributes", []):
143
+ if a["name"] not in names:
144
+ names.append(a["name"])
145
+ return names
146
+
147
+
148
+ def describe(domain) -> List[str]:
149
+ """What an archive holds, one line per collection, for ``--show`` and ``--verbose``.
150
+
151
+ Each collection is numbered so the interactive prompt can refer to it.
152
+ """
153
+ lines = []
154
+ for i, collection in enumerate(time_collections(canonicalize_approximation(domain)), start=1):
155
+ steps = collection["data"]
156
+ times = [step["time"] for step in steps]
157
+ span = ("no steps" if not times
158
+ else "1 step at t=%g" % times[0] if len(times) == 1
159
+ else "%d steps, t=%g..%g" % (len(times), times[0], times[-1]))
160
+ detail = ""
161
+ if steps:
162
+ first = steps[0]
163
+ if "spatial_collection" in first:
164
+ detail = ", %d subdomains" % len(first["spatial_collection"])
165
+ first = first["spatial_collection"][0]
166
+ detail += ", %s topology" % first["topology"]["type"]
167
+ fields = _fields_of(collection)
168
+ if fields:
169
+ detail += ", fields: %s" % ", ".join(fields)
170
+ lines.append(" %d. %s: %s%s" % (i, collection["name"], span, detail))
171
+ return lines
172
+
173
+
174
+ _describe = describe
175
+
176
+
177
+ def _pick(prompt: str, options: Sequence[str], ask=None) -> Optional[List[str]]:
178
+ """Ask for some of ``options`` by number; blank keeps them all (None)."""
179
+ ask = ask or input
180
+ for i, option in enumerate(options, start=1):
181
+ print(" %d. %s" % (i, option))
182
+ answer = ask(prompt).strip()
183
+ if not answer:
184
+ return None
185
+ chosen = []
186
+ for token in answer.replace(",", " ").split():
187
+ try:
188
+ index = int(token)
189
+ except ValueError:
190
+ raise YmfArchiveError("%r is not a number" % (token,)) from None
191
+ if not 1 <= index <= len(options):
192
+ raise YmfArchiveError("%d is not one of 1..%d" % (index, len(options)))
193
+ if options[index - 1] not in chosen:
194
+ chosen.append(options[index - 1])
195
+ return chosen
196
+
197
+
198
+ def interactive_selection(domain, ask=None):
199
+ """Ask which collections, fields and steps to convert.
200
+
201
+ Returns ``(collections, fields, steps)`` as :func:`ymf2xmf` takes
202
+ them, each ``None`` where everything was kept. ``ask`` defaults to
203
+ ``input`` (looked up at call time, so a test can replace it); tests
204
+ pass their own.
205
+ """
206
+ ask = ask or input
207
+ collections = time_collections(canonicalize_approximation(domain))
208
+ names = [c["name"] for c in collections]
209
+ print("Collections (blank for all):")
210
+ chosen_names = _pick("collections> ", names, ask)
211
+ kept = [c for c in collections if chosen_names is None or c["name"] in chosen_names]
212
+ fields: List[str] = []
213
+ for c in kept:
214
+ for f in _fields_of(c):
215
+ if f not in fields:
216
+ fields.append(f)
217
+ chosen_fields = None
218
+ if fields:
219
+ print("Fields (blank for all):")
220
+ chosen_fields = _pick("fields> ", fields, ask)
221
+ n_steps = max((len(c.get("data", [])) for c in kept), default=0)
222
+ steps = None
223
+ if n_steps > 1:
224
+ answer = ask("Steps of %d, as indices or slices, e.g. -1, 0:10, ::5 (blank for all)> "
225
+ % (n_steps,)).strip()
226
+ steps = answer or None
227
+ return chosen_names, chosen_fields, steps
228
+
229
+
230
+ def ymf2xmf_main(argv: Optional[Sequence[str]] = None) -> int:
231
+ """``ymf2xmf`` console entry point."""
232
+ parser = argparse.ArgumentParser(
233
+ prog="ymf2xmf",
234
+ description="Convert a YMF archive into an XDMF (.xmf) file that "
235
+ "ParaView and VisIt can open. The heavy data is not "
236
+ "copied -- the .xmf references the same HDF5 datasets "
237
+ "the .ymf does, so it must sit beside them.")
238
+ parser.add_argument("archive", help="the .ymf archive to convert")
239
+ parser.add_argument("-o", "--output",
240
+ help="output path (default: the archive with a .xmf suffix); "
241
+ "for an archive with outputs, the directory to write to")
242
+ parser.add_argument("--key", action="append",
243
+ help="convert only this output (repeatable; default: all)")
244
+ parser.add_argument("--no-validate", action="store_true",
245
+ help="skip the structural check before converting")
246
+ parser.add_argument("-v", "--verbose", action="store_true",
247
+ help="describe what the archive holds")
248
+ parser.add_argument("--show", action="store_true",
249
+ help="describe what the archive holds and stop; convert nothing")
250
+ parser.add_argument("-c", "--collection", action="append", metavar="NAME",
251
+ help="convert only this space (time collection), by name or part of one "
252
+ "(repeatable; default: all)")
253
+ parser.add_argument("-f", "--field", action="append", metavar="NAME",
254
+ help="convert only this field (repeatable; default: all)")
255
+ parser.add_argument("-s", "--steps", metavar="SPEC",
256
+ help="convert only these instants: indices and slices, e.g. -1, "
257
+ "0:10, ::5 (default: all)")
258
+ parser.add_argument("-i", "--interactive", action="store_true",
259
+ help="ask which collections, fields and steps to convert")
260
+ args = parser.parse_args(argv)
261
+
262
+ source = Path(args.archive)
263
+ if not source.exists():
264
+ parser.error("no such file: %s" % (source,))
265
+
266
+ try:
267
+ if _is_archive(source):
268
+ for destination in archive2xmf(source, args.output, args.key,
269
+ validate=not args.no_validate):
270
+ print("wrote %s" % (destination,))
271
+ return 0
272
+ collections, fields, steps = args.collection, args.field, args.steps
273
+ if args.verbose or args.show or args.interactive:
274
+ domain, _ = read_ymf(source)
275
+ domain = canonicalize_approximation(domain)
276
+ print("%s" % (source,))
277
+ if not args.interactive:
278
+ times = [i["time"] for i in domain.get("times", [])]
279
+ if times:
280
+ print(" %d instant%s, t=%g..%g, %d space%s"
281
+ % (len(times), "" if len(times) == 1 else "s",
282
+ times[0], times[-1], len(space_names(domain)),
283
+ "" if len(space_names(domain)) == 1 else "s"))
284
+ for line in describe(domain):
285
+ print(line)
286
+ if args.show:
287
+ return 0
288
+ if args.interactive:
289
+ collections, fields, steps = interactive_selection(domain)
290
+ destination = ymf2xmf(source, args.output,
291
+ validate=not args.no_validate,
292
+ collections=collections, fields=fields, steps=steps)
293
+ except YmfArchiveError as exc:
294
+ # A structural problem in the archive, named. Not a traceback:
295
+ # the user asked to convert a file, and the file is the problem.
296
+ print("ymf2xmf: %s" % (exc,), file=sys.stderr)
297
+ return 1
298
+ except OSError as exc:
299
+ print("ymf2xmf: %s" % (exc,), file=sys.stderr)
300
+ return 1
301
+
302
+ print("wrote %s" % (destination,))
303
+ return 0
304
+
305
+
306
+ if __name__ == "__main__": # pragma: no cover
307
+ raise SystemExit(ymf2xmf_main())