maggie 0.2.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.
- maggie/__init__.py +20 -0
- maggie/__main__.py +8 -0
- maggie/app.py +192 -0
- maggie/constants.py +6 -0
- maggie/core/__init__.py +7 -0
- maggie/core/dims.py +90 -0
- maggie/core/field.py +239 -0
- maggie/core/mesh.py +72 -0
- maggie/core/session.py +262 -0
- maggie/core/views.py +136 -0
- maggie/core/xs.py +175 -0
- maggie/gui/__init__.py +7 -0
- maggie/gui/field_view.py +256 -0
- maggie/gui/load_window.py +432 -0
- maggie/gui/theme.py +16 -0
- maggie/gui/viewer_window.py +55 -0
- maggie/gui/widgets.py +143 -0
- maggie/io/__init__.py +23 -0
- maggie/io/base.py +149 -0
- maggie/io/presets.py +76 -0
- maggie/io/readers/__init__.py +7 -0
- maggie/io/readers/arrays.py +222 -0
- maggie/io/readers/ndiffusion.py +95 -0
- maggie/io/schema.py +207 -0
- maggie/plot.py +233 -0
- maggie-0.2.0.dist-info/METADATA +216 -0
- maggie-0.2.0.dist-info/RECORD +31 -0
- maggie-0.2.0.dist-info/WHEEL +5 -0
- maggie-0.2.0.dist-info/entry_points.txt +5 -0
- maggie-0.2.0.dist-info/licenses/LICENSE +21 -0
- maggie-0.2.0.dist-info/top_level.txt +1 -0
maggie/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""MAGGIE - Mesh-Agnostic Graphics for Group-wise Iteration and Evolution.
|
|
2
|
+
|
|
3
|
+
Visualizes flux from static and time-dependent transport and diffusion codes.
|
|
4
|
+
|
|
5
|
+
Only the Qt-free surface (data model and IO) is exported here, so
|
|
6
|
+
``import maggie`` never pulls in Qt. The GUI lives in ``maggie.gui``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
10
|
+
|
|
11
|
+
from maggie.core import Field, UnstructuredMesh
|
|
12
|
+
from maggie.io import detect, entries, load, save, write_flux
|
|
13
|
+
|
|
14
|
+
try: # single source of truth: the version in pyproject.toml
|
|
15
|
+
__version__ = version("maggie")
|
|
16
|
+
except PackageNotFoundError: # running from a source tree that is not installed
|
|
17
|
+
__version__ = "0+unknown"
|
|
18
|
+
|
|
19
|
+
__all__ = ["Field", "UnstructuredMesh", "detect", "entries", "load", "save",
|
|
20
|
+
"write_flux", "__version__"]
|
maggie/__main__.py
ADDED
maggie/app.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Command-line entry point.
|
|
2
|
+
|
|
3
|
+
maggie open the load screen
|
|
4
|
+
maggie flux.npy --dim 1 --axes "time,x,group" --scatter xs.npz --view
|
|
5
|
+
fill in the load screen (and,
|
|
6
|
+
with --view, go straight to plots)
|
|
7
|
+
maggie info FILE [KEY] print what MAGGIE finds in FILE
|
|
8
|
+
|
|
9
|
+
File arguments may name an array inside a container as ``FILE:KEY``, e.g.
|
|
10
|
+
``--scatter c5g7.npz:xs_scatter``.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import os
|
|
17
|
+
import sys
|
|
18
|
+
from typing import Optional
|
|
19
|
+
|
|
20
|
+
from maggie.core.session import ArraySource, FluxSource, GridSpec, LoadSpec
|
|
21
|
+
from maggie.core.xs import FROM_TO, TO_FROM
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _source(text: Optional[str]) -> Optional[ArraySource]:
|
|
25
|
+
if not text:
|
|
26
|
+
return None
|
|
27
|
+
if os.path.exists(text) or ":" not in text:
|
|
28
|
+
return ArraySource(text)
|
|
29
|
+
path, key = text.rsplit(":", 1)
|
|
30
|
+
return ArraySource(path, key or None)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# --------------------------------------------------------------------------- #
|
|
34
|
+
# maggie info
|
|
35
|
+
# --------------------------------------------------------------------------- #
|
|
36
|
+
def info(argv) -> int:
|
|
37
|
+
parser = argparse.ArgumentParser(prog="maggie info",
|
|
38
|
+
description="Print what MAGGIE finds in a file.")
|
|
39
|
+
parser.add_argument("file")
|
|
40
|
+
parser.add_argument("key", nargs="?")
|
|
41
|
+
parser.add_argument("--reader")
|
|
42
|
+
parser.add_argument("--preset", help="bare-array preset: ants, discrete1, ndiffusion")
|
|
43
|
+
parser.add_argument("--layout", help="preset layout, e.g. '1D time-dependent'")
|
|
44
|
+
parser.add_argument("--dims", help="axis names, e.g. 'time,x,group'")
|
|
45
|
+
args = parser.parse_args(argv)
|
|
46
|
+
|
|
47
|
+
import maggie.io as mio
|
|
48
|
+
|
|
49
|
+
try:
|
|
50
|
+
found = mio.detect(args.file)
|
|
51
|
+
if not found:
|
|
52
|
+
print(f"No reader recognises {args.file}")
|
|
53
|
+
return 1
|
|
54
|
+
print("Readers:")
|
|
55
|
+
for rdr, score in found:
|
|
56
|
+
print(f" {rdr.name:<12} {rdr.label:<28} confidence {score}")
|
|
57
|
+
chosen = args.reader or found[0][0].name
|
|
58
|
+
print(f"\nEntries ({chosen}):")
|
|
59
|
+
for entry in mio.entries(args.file, chosen):
|
|
60
|
+
print(f" {entry.key!r:<40} {entry.describe()}")
|
|
61
|
+
options = {k: v for k, v in (("preset", args.preset), ("layout", args.layout),
|
|
62
|
+
("dims", args.dims)) if v}
|
|
63
|
+
field = mio.load(args.file, args.key, reader=chosen, **options)
|
|
64
|
+
except (ValueError, KeyError, FileNotFoundError) as exc:
|
|
65
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
66
|
+
return 1
|
|
67
|
+
print(f"\nLoaded {field!r}")
|
|
68
|
+
for dim in field.dims:
|
|
69
|
+
kind = "edges" if field.edges(dim) is not None else (
|
|
70
|
+
"centres" if dim in field.coords else "index only")
|
|
71
|
+
c = field.centers(dim)
|
|
72
|
+
print(f" {dim:<10} n={field.size(dim):<6} {kind:<10} [{c.min():.4g} .. {c.max():.4g}]")
|
|
73
|
+
print(f" values [{field.values.min():.4g} .. {field.values.max():.4g}]")
|
|
74
|
+
for k, v in field.attrs.items():
|
|
75
|
+
print(f" attr {k} = {v}")
|
|
76
|
+
return 0
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# --------------------------------------------------------------------------- #
|
|
80
|
+
# GUI
|
|
81
|
+
# --------------------------------------------------------------------------- #
|
|
82
|
+
def parse_gui_args(argv) -> tuple[LoadSpec, bool]:
|
|
83
|
+
parser = argparse.ArgumentParser(
|
|
84
|
+
prog="maggie", description=__doc__,
|
|
85
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
86
|
+
parser.add_argument("flux", nargs="*", help="flux file(s), each FILE or FILE:KEY")
|
|
87
|
+
parser.add_argument("--dim", type=int, choices=(1, 2, 3), default=1,
|
|
88
|
+
help="spatial dimension (default 1)")
|
|
89
|
+
parser.add_argument("--axes", help="axis order of bare flux arrays, e.g. 'time,x,group'")
|
|
90
|
+
parser.add_argument("--scatter", help="scattering cross section FILE[:KEY]")
|
|
91
|
+
parser.add_argument("--fission", help="fission cross section FILE[:KEY]")
|
|
92
|
+
parser.add_argument("--map", help="material map FILE[:KEY]")
|
|
93
|
+
parser.add_argument("--order", choices=(TO_FROM, FROM_TO), default=TO_FROM,
|
|
94
|
+
help="cross-section matrix index order (default to_from)")
|
|
95
|
+
for dim in ("energy", "x", "y", "z", "time"):
|
|
96
|
+
parser.add_argument(f"--{dim}-grid", help=f"{dim} edges or centres FILE[:KEY]")
|
|
97
|
+
parser.add_argument("--view", action="store_true",
|
|
98
|
+
help="skip the load screen and open the plots directly")
|
|
99
|
+
args = parser.parse_args(argv)
|
|
100
|
+
|
|
101
|
+
from maggie.core import dims as D
|
|
102
|
+
|
|
103
|
+
axes = D.parse(args.axes) if args.axes else None
|
|
104
|
+
fluxes = []
|
|
105
|
+
for text in args.flux:
|
|
106
|
+
src = _source(text)
|
|
107
|
+
fluxes.append(FluxSource(src.path, src.key, dims=axes))
|
|
108
|
+
grids = {}
|
|
109
|
+
for name, dim in (("energy", D.GROUP), ("x", D.X), ("y", D.Y), ("z", D.Z), ("time", D.TIME)):
|
|
110
|
+
source = _source(getattr(args, f"{name}_grid"))
|
|
111
|
+
if source is not None:
|
|
112
|
+
grids[dim] = GridSpec("file", source=source)
|
|
113
|
+
spec = LoadSpec(dimension=args.dim, fluxes=fluxes, scatter=_source(args.scatter),
|
|
114
|
+
fission=_source(args.fission), material_map=_source(args.map),
|
|
115
|
+
matrix_order=args.order, grids=grids)
|
|
116
|
+
return spec, args.view
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Controller:
|
|
120
|
+
"""Shows the load screen, then the viewer; File > Load new data goes back."""
|
|
121
|
+
|
|
122
|
+
def __init__(self):
|
|
123
|
+
self.load_window = None
|
|
124
|
+
self.viewer = None
|
|
125
|
+
|
|
126
|
+
def show_load(self, spec=None, message: Optional[str] = None) -> None:
|
|
127
|
+
from maggie.gui.load_window import LoadWindow
|
|
128
|
+
|
|
129
|
+
window = LoadWindow(spec)
|
|
130
|
+
window.loaded.connect(self.show_viewer)
|
|
131
|
+
if message:
|
|
132
|
+
window.show_message(message, error=True)
|
|
133
|
+
window.show()
|
|
134
|
+
if self.load_window is not None:
|
|
135
|
+
self.load_window.close()
|
|
136
|
+
self.load_window = window
|
|
137
|
+
|
|
138
|
+
def show_viewer(self, session) -> None:
|
|
139
|
+
from maggie.gui.viewer_window import ViewerWindow
|
|
140
|
+
|
|
141
|
+
viewer = ViewerWindow(session)
|
|
142
|
+
viewer.reload_requested.connect(self.show_load)
|
|
143
|
+
viewer.show()
|
|
144
|
+
if self.viewer is not None:
|
|
145
|
+
self.viewer.close()
|
|
146
|
+
self.viewer = viewer
|
|
147
|
+
if self.load_window is not None:
|
|
148
|
+
self.load_window.close()
|
|
149
|
+
self.load_window = None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def main(argv=None) -> int:
|
|
153
|
+
argv = sys.argv[1:] if argv is None else list(argv)
|
|
154
|
+
if argv[:1] == ["info"]:
|
|
155
|
+
return info(argv[1:])
|
|
156
|
+
|
|
157
|
+
try:
|
|
158
|
+
spec, go = parse_gui_args(argv)
|
|
159
|
+
except ValueError as exc:
|
|
160
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
161
|
+
return 2
|
|
162
|
+
|
|
163
|
+
# Import Qt lazily so `maggie info` and `--help` need no display.
|
|
164
|
+
import maggie.gui # noqa: F401 (pins matplotlib to PySide6)
|
|
165
|
+
from PySide6.QtWidgets import QApplication
|
|
166
|
+
|
|
167
|
+
from maggie.core.session import LoadError, build_session
|
|
168
|
+
from maggie.gui.theme import apply_theme
|
|
169
|
+
|
|
170
|
+
app = QApplication.instance() or QApplication(sys.argv[:1])
|
|
171
|
+
apply_theme(app)
|
|
172
|
+
controller = Controller()
|
|
173
|
+
app._maggie_controller = controller # keep alive for the event loop
|
|
174
|
+
|
|
175
|
+
session, message = None, None
|
|
176
|
+
if go and spec.fluxes:
|
|
177
|
+
try:
|
|
178
|
+
session = build_session(spec)
|
|
179
|
+
except LoadError as exc:
|
|
180
|
+
message = str(exc)
|
|
181
|
+
if session is not None:
|
|
182
|
+
controller.show_viewer(session)
|
|
183
|
+
else:
|
|
184
|
+
try:
|
|
185
|
+
controller.show_load(spec, message)
|
|
186
|
+
except (ValueError, OSError) as exc: # a command-line file that cannot be read
|
|
187
|
+
controller.show_load(None, str(exc))
|
|
188
|
+
return app.exec()
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
if __name__ == "__main__":
|
|
192
|
+
sys.exit(main())
|
maggie/constants.py
ADDED
maggie/core/__init__.py
ADDED
maggie/core/dims.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Canonical dimension names shared by every reader and the GUI.
|
|
2
|
+
|
|
3
|
+
A :class:`~maggie.core.field.Field` labels each array axis with one of these
|
|
4
|
+
names, so code downstream never has to know which solver wrote the file.
|
|
5
|
+
Readers may use other names for axes MAGGIE has no special meaning for (an
|
|
6
|
+
solver-specific axis, for instance); those still load and
|
|
7
|
+
can be sliced, they just get no special treatment.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Iterable, Tuple
|
|
13
|
+
|
|
14
|
+
# Structured spatial axes (cell-centred values; coords are edges or centres).
|
|
15
|
+
X, Y, Z = "x", "y", "z"
|
|
16
|
+
R, THETA, PHI = "r", "theta", "phi" # cylindrical / spherical meshes
|
|
17
|
+
# One axis over the cells of a flattened or unstructured mesh.
|
|
18
|
+
CELL = "cell"
|
|
19
|
+
# One axis over geometric regions with no mesh attached (e.g. material
|
|
20
|
+
# regions or flat source regions). Coords, if any, are region ids.
|
|
21
|
+
REGION = "region"
|
|
22
|
+
|
|
23
|
+
GROUP = "group" # energy group (coords: edges, len G+1, or centres)
|
|
24
|
+
GROUP_OUT = "group_out" # outgoing energy group (scattering-matrix tallies)
|
|
25
|
+
TIME = "time" # time step / time bin
|
|
26
|
+
ANGLE = "angle" # discrete ordinate
|
|
27
|
+
MOMENT = "moment" # flux moment (Legendre / spherical harmonic)
|
|
28
|
+
MU = "mu" # polar-cosine bin
|
|
29
|
+
AZI = "azi" # azimuthal bin
|
|
30
|
+
POLAR = "polar" # polar-angle bin
|
|
31
|
+
|
|
32
|
+
SPATIAL = (X, Y, Z, R, THETA, PHI, CELL, REGION)
|
|
33
|
+
|
|
34
|
+
# Short / legacy spellings accepted wherever a user types a dimension name.
|
|
35
|
+
# ``I``/``G``/``T`` are the labels MAGGIE 0.1 used.
|
|
36
|
+
ALIASES = {
|
|
37
|
+
"i": X, "j": Y, "k": Z,
|
|
38
|
+
"g": GROUP, "e": GROUP, "energy": GROUP, "groups": GROUP,
|
|
39
|
+
"t": TIME, "step": TIME, "steps": TIME,
|
|
40
|
+
"n": ANGLE, "angles": ANGLE, "ordinate": ANGLE,
|
|
41
|
+
"m": MOMENT, "moments": MOMENT,
|
|
42
|
+
"cells": CELL, "fsr": REGION, "regions": REGION,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def normalize(name: str) -> str:
|
|
47
|
+
"""Map a user-typed dimension name to its canonical spelling."""
|
|
48
|
+
key = name.strip().lower()
|
|
49
|
+
return ALIASES.get(key, key)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def parse(spec) -> Tuple[str, ...]:
|
|
53
|
+
"""Parse a dimension ordering into canonical names.
|
|
54
|
+
|
|
55
|
+
Accepts a sequence (``("I", "G")``) or a string (``"I x G"``,
|
|
56
|
+
``"time,x,group"``, ``"T I G"``). Raises ``ValueError`` on duplicates.
|
|
57
|
+
"""
|
|
58
|
+
if isinstance(spec, str):
|
|
59
|
+
names: Iterable[str] = _split(spec)
|
|
60
|
+
else:
|
|
61
|
+
names = spec
|
|
62
|
+
dims = tuple(normalize(n) for n in names)
|
|
63
|
+
if len(set(dims)) != len(dims):
|
|
64
|
+
raise ValueError(f"Duplicate dimension in {spec!r}")
|
|
65
|
+
return dims
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _split(text: str):
|
|
69
|
+
"""Split ``"I x G"``, ``"time,x,group"`` or ``"time x y group"``.
|
|
70
|
+
|
|
71
|
+
``x`` is both a dim name and the classic ordering separator, so it counts
|
|
72
|
+
as a separator only when it alternates with names (``a x b x c``).
|
|
73
|
+
"""
|
|
74
|
+
if "," in text:
|
|
75
|
+
return [p.strip() for p in text.split(",") if p.strip()]
|
|
76
|
+
tokens = text.split()
|
|
77
|
+
if len(tokens) >= 3 and len(tokens) % 2 == 1 and all(
|
|
78
|
+
t.lower() == "x" for t in tokens[1::2]
|
|
79
|
+
):
|
|
80
|
+
return tokens[0::2]
|
|
81
|
+
return tokens
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def placeholder(ndim: int) -> Tuple[str, ...]:
|
|
85
|
+
"""Names for axes whose meaning is not known yet (``dim_0``, ``dim_1``...)."""
|
|
86
|
+
return tuple(f"dim_{i}" for i in range(ndim))
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def is_placeholder(name: str) -> bool:
|
|
90
|
+
return name.startswith("dim_")
|
maggie/core/field.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""The one data type every reader produces: :class:`Field`.
|
|
2
|
+
|
|
3
|
+
A field is an n-dimensional array whose axes are *named* (see
|
|
4
|
+
:mod:`maggie.core.dims`), plus whatever context the file had: coordinates per
|
|
5
|
+
axis, a standard deviation for Monte Carlo tallies, an unstructured mesh for a
|
|
6
|
+
``cell`` axis, and free-form attributes (code, keff, units...).
|
|
7
|
+
|
|
8
|
+
Coordinates follow one rule: an axis of length ``n`` takes coords of length
|
|
9
|
+
``n + 1`` (bin edges) or ``n`` (point values or centres). Use
|
|
10
|
+
:meth:`Field.edges` and :meth:`Field.centers` instead of checking yourself.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass, field, replace
|
|
16
|
+
from typing import Dict, Mapping, Optional, Sequence, Tuple, Union
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
from maggie.core import dims as D
|
|
21
|
+
from maggie.core.mesh import UnstructuredMesh
|
|
22
|
+
|
|
23
|
+
Index = Union[int, slice, Sequence[int], np.ndarray]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(eq=False)
|
|
27
|
+
class Field:
|
|
28
|
+
values: np.ndarray
|
|
29
|
+
dims: Tuple[str, ...]
|
|
30
|
+
name: str = "flux"
|
|
31
|
+
coords: Dict[str, np.ndarray] = field(default_factory=dict)
|
|
32
|
+
std: Optional[np.ndarray] = None
|
|
33
|
+
mesh: Optional[UnstructuredMesh] = None
|
|
34
|
+
attrs: Dict[str, object] = field(default_factory=dict)
|
|
35
|
+
|
|
36
|
+
def __post_init__(self) -> None:
|
|
37
|
+
self.values = np.asarray(self.values)
|
|
38
|
+
self.dims = D.parse(self.dims) if self.dims else ()
|
|
39
|
+
if len(self.dims) != self.values.ndim:
|
|
40
|
+
raise ValueError(
|
|
41
|
+
f"{self.name}: {len(self.dims)} dims {self.dims} given for an "
|
|
42
|
+
f"array of shape {self.values.shape}")
|
|
43
|
+
if self.std is not None:
|
|
44
|
+
self.std = np.asarray(self.std)
|
|
45
|
+
if self.std.shape != self.values.shape:
|
|
46
|
+
raise ValueError(
|
|
47
|
+
f"{self.name}: std shape {self.std.shape} does not match "
|
|
48
|
+
f"values shape {self.values.shape}")
|
|
49
|
+
self.coords = {D.normalize(k): np.asarray(v).ravel()
|
|
50
|
+
for k, v in self.coords.items() if v is not None}
|
|
51
|
+
for dim, c in self.coords.items():
|
|
52
|
+
if dim not in self.dims:
|
|
53
|
+
raise ValueError(f"{self.name}: coords given for missing dim {dim!r}")
|
|
54
|
+
n = self.size(dim)
|
|
55
|
+
if c.size not in (n, n + 1):
|
|
56
|
+
raise ValueError(
|
|
57
|
+
f"{self.name}: {dim!r} has {n} entries, so its coords need "
|
|
58
|
+
f"{n} (centres) or {n + 1} (edges) values, got {c.size}")
|
|
59
|
+
if self.mesh is not None:
|
|
60
|
+
if D.CELL not in self.dims:
|
|
61
|
+
raise ValueError(f"{self.name}: a mesh needs a {D.CELL!r} dim")
|
|
62
|
+
if self.mesh.n_cells != self.size(D.CELL):
|
|
63
|
+
raise ValueError(
|
|
64
|
+
f"{self.name}: mesh has {self.mesh.n_cells} cells but the "
|
|
65
|
+
f"{D.CELL!r} dim has {self.size(D.CELL)}")
|
|
66
|
+
|
|
67
|
+
# -- shape -------------------------------------------------------------- #
|
|
68
|
+
@property
|
|
69
|
+
def shape(self) -> Tuple[int, ...]:
|
|
70
|
+
return self.values.shape
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def ndim(self) -> int:
|
|
74
|
+
return self.values.ndim
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def sizes(self) -> Dict[str, int]:
|
|
78
|
+
return dict(zip(self.dims, self.values.shape))
|
|
79
|
+
|
|
80
|
+
def has(self, dim: str) -> bool:
|
|
81
|
+
return D.normalize(dim) in self.dims
|
|
82
|
+
|
|
83
|
+
def axis(self, dim: str) -> int:
|
|
84
|
+
dim = D.normalize(dim)
|
|
85
|
+
try:
|
|
86
|
+
return self.dims.index(dim)
|
|
87
|
+
except ValueError:
|
|
88
|
+
raise KeyError(f"{self.name} has no {dim!r} dim (dims: {self.dims})") from None
|
|
89
|
+
|
|
90
|
+
def size(self, dim: str) -> int:
|
|
91
|
+
return self.values.shape[self.axis(dim)]
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def spatial_dims(self) -> Tuple[str, ...]:
|
|
95
|
+
return tuple(d for d in self.dims if d in D.SPATIAL)
|
|
96
|
+
|
|
97
|
+
@property
|
|
98
|
+
def is_time_dependent(self) -> bool:
|
|
99
|
+
return D.TIME in self.dims and self.size(D.TIME) > 1
|
|
100
|
+
|
|
101
|
+
# -- coordinates -------------------------------------------------------- #
|
|
102
|
+
def edges(self, dim: str) -> Optional[np.ndarray]:
|
|
103
|
+
"""Bin edges (length n+1) for ``dim``, or ``None`` if only centres are known."""
|
|
104
|
+
dim = D.normalize(dim)
|
|
105
|
+
c = self.coords.get(dim)
|
|
106
|
+
return c if c is not None and c.size == self.size(dim) + 1 else None
|
|
107
|
+
|
|
108
|
+
def centers(self, dim: str) -> np.ndarray:
|
|
109
|
+
"""Coordinate per entry of ``dim``: midpoints of edges, the given
|
|
110
|
+
centres, or the index ``0..n-1`` when the file had no coords."""
|
|
111
|
+
dim = D.normalize(dim)
|
|
112
|
+
n = self.size(dim)
|
|
113
|
+
c = self.coords.get(dim)
|
|
114
|
+
if c is None:
|
|
115
|
+
return np.arange(n, dtype=float)
|
|
116
|
+
if c.size == n + 1:
|
|
117
|
+
return 0.5 * (c[:-1] + c[1:])
|
|
118
|
+
return c
|
|
119
|
+
|
|
120
|
+
# -- reshaping ---------------------------------------------------------- #
|
|
121
|
+
def _new(self, values, dims, std, coords, mesh=None, **kw) -> "Field":
|
|
122
|
+
return replace(self, values=values, dims=tuple(dims), std=std,
|
|
123
|
+
coords=coords, mesh=mesh, attrs=dict(self.attrs), **kw)
|
|
124
|
+
|
|
125
|
+
def rename(self, mapping: Mapping[str, str]) -> "Field":
|
|
126
|
+
"""Rename dims, e.g. to name placeholder ``dim_0`` axes."""
|
|
127
|
+
mapping = {D.normalize(k): D.normalize(v) for k, v in mapping.items()}
|
|
128
|
+
dims = tuple(mapping.get(d, d) for d in self.dims)
|
|
129
|
+
coords = {mapping.get(k, k): v for k, v in self.coords.items()}
|
|
130
|
+
mesh = self.mesh if D.CELL in dims else None
|
|
131
|
+
return self._new(self.values, dims, self.std, coords, mesh)
|
|
132
|
+
|
|
133
|
+
def with_dims(self, dims) -> "Field":
|
|
134
|
+
"""Relabel every axis at once (the array is not moved)."""
|
|
135
|
+
return self.rename(dict(zip(self.dims, D.parse(dims))))
|
|
136
|
+
|
|
137
|
+
def transpose(self, *dims: str) -> "Field":
|
|
138
|
+
"""Reorder axes. Dims left out keep their relative order at the end."""
|
|
139
|
+
wanted = [D.normalize(d) for d in dims]
|
|
140
|
+
order = wanted + [d for d in self.dims if d not in wanted]
|
|
141
|
+
perm = [self.axis(d) for d in order]
|
|
142
|
+
std = None if self.std is None else self.std.transpose(perm)
|
|
143
|
+
return self._new(self.values.transpose(perm), order, std,
|
|
144
|
+
dict(self.coords), self.mesh)
|
|
145
|
+
|
|
146
|
+
def isel(self, **indexers: Index) -> "Field":
|
|
147
|
+
"""Select by integer position along named dims.
|
|
148
|
+
|
|
149
|
+
An integer drops the dim; a slice or index array keeps it (and
|
|
150
|
+
subsets its coords). ``field.isel(time=-1, group=slice(0, 3))``.
|
|
151
|
+
"""
|
|
152
|
+
index = [slice(None)] * self.ndim
|
|
153
|
+
coords = dict(self.coords)
|
|
154
|
+
drop = set()
|
|
155
|
+
for dim, ix in indexers.items():
|
|
156
|
+
dim = D.normalize(dim)
|
|
157
|
+
ax = self.axis(dim)
|
|
158
|
+
index[ax] = ix
|
|
159
|
+
c = coords.pop(dim, None)
|
|
160
|
+
if np.ndim(ix) == 0 and not isinstance(ix, slice):
|
|
161
|
+
drop.add(dim)
|
|
162
|
+
continue
|
|
163
|
+
if c is not None:
|
|
164
|
+
coords[dim] = _subset_coords(c, self.size(dim), ix)
|
|
165
|
+
values = self.values[tuple(index)]
|
|
166
|
+
std = None if self.std is None else self.std[tuple(index)]
|
|
167
|
+
dims = [d for d in self.dims if d not in drop]
|
|
168
|
+
mesh = self.mesh if D.CELL in dims and D.CELL not in indexers else None
|
|
169
|
+
return self._new(values, dims, std, coords, mesh)
|
|
170
|
+
|
|
171
|
+
def sum(self, dim: str) -> "Field":
|
|
172
|
+
"""Sum over ``dim``. Standard deviations add in quadrature (the
|
|
173
|
+
entries are assumed independent)."""
|
|
174
|
+
ax = self.axis(dim)
|
|
175
|
+
values = self.values.sum(axis=ax)
|
|
176
|
+
std = None if self.std is None else np.sqrt((self.std ** 2).sum(axis=ax))
|
|
177
|
+
dims = [d for d in self.dims if d != D.normalize(dim)]
|
|
178
|
+
coords = {k: v for k, v in self.coords.items() if k != D.normalize(dim)}
|
|
179
|
+
mesh = self.mesh if D.CELL in dims else None
|
|
180
|
+
return self._new(values, dims, std, coords, mesh)
|
|
181
|
+
|
|
182
|
+
def squeeze(self) -> "Field":
|
|
183
|
+
"""Drop every dim of length 1."""
|
|
184
|
+
keep = {d: 0 for d, n in self.sizes.items() if n == 1}
|
|
185
|
+
return self.isel(**keep) if keep else self
|
|
186
|
+
|
|
187
|
+
def unflatten(self, dim: str, new_dims: Sequence[str],
|
|
188
|
+
shape: Sequence[int], order: str = "C") -> "Field":
|
|
189
|
+
"""Split one axis into several, e.g. NeutronDiffusion's flattened 2-D
|
|
190
|
+
``cell`` axis (row ``i * ny + j``) into ``("x", "y")`` with ``(nx, ny)``.
|
|
191
|
+
Use ``order="F"`` when the first new dim varies fastest."""
|
|
192
|
+
ax = self.axis(dim)
|
|
193
|
+
new_dims = D.parse(new_dims)
|
|
194
|
+
shape = tuple(int(s) for s in shape)
|
|
195
|
+
if int(np.prod(shape)) != self.values.shape[ax]:
|
|
196
|
+
raise ValueError(
|
|
197
|
+
f"Cannot split {dim!r} of length {self.values.shape[ax]} into {shape}")
|
|
198
|
+
|
|
199
|
+
def split(a):
|
|
200
|
+
moved = np.moveaxis(a, ax, -1)
|
|
201
|
+
out = moved.reshape(moved.shape[:-1] + shape, order=order)
|
|
202
|
+
return np.moveaxis(out, range(out.ndim - len(shape), out.ndim),
|
|
203
|
+
range(ax, ax + len(shape)))
|
|
204
|
+
|
|
205
|
+
dims = list(self.dims[:ax]) + list(new_dims) + list(self.dims[ax + 1:])
|
|
206
|
+
coords = {k: v for k, v in self.coords.items() if k != D.normalize(dim)}
|
|
207
|
+
std = None if self.std is None else split(self.std)
|
|
208
|
+
return self._new(split(self.values), dims, std, coords)
|
|
209
|
+
|
|
210
|
+
def assign_coords(self, **coords) -> "Field":
|
|
211
|
+
merged = dict(self.coords)
|
|
212
|
+
merged.update({D.normalize(k): v for k, v in coords.items() if v is not None})
|
|
213
|
+
return self._new(self.values, self.dims, self.std, merged, self.mesh)
|
|
214
|
+
|
|
215
|
+
# -- display ------------------------------------------------------------ #
|
|
216
|
+
def describe(self) -> str:
|
|
217
|
+
shape = " x ".join(f"{d}={n}" for d, n in self.sizes.items()) or "scalar"
|
|
218
|
+
extra = []
|
|
219
|
+
if self.std is not None:
|
|
220
|
+
extra.append("std")
|
|
221
|
+
if self.mesh is not None:
|
|
222
|
+
extra.append(f"mesh({self.mesh.n_cells} cells)")
|
|
223
|
+
tail = f" [{', '.join(extra)}]" if extra else ""
|
|
224
|
+
return f"{self.name}: {shape}{tail}"
|
|
225
|
+
|
|
226
|
+
def __repr__(self) -> str:
|
|
227
|
+
return f"<Field {self.describe()}>"
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _subset_coords(c: np.ndarray, n: int, ix) -> Optional[np.ndarray]:
|
|
231
|
+
"""Coords for a slice/index-array selection along an axis of length ``n``."""
|
|
232
|
+
if c.size == n:
|
|
233
|
+
return c[ix]
|
|
234
|
+
# Edges: keep the edges of each selected bin. Contiguous unit-step
|
|
235
|
+
# selections keep shared edges; anything else falls back to centres.
|
|
236
|
+
picked = np.arange(n)[ix]
|
|
237
|
+
if picked.size and np.all(np.diff(picked) == 1):
|
|
238
|
+
return c[picked[0]:picked[-1] + 2]
|
|
239
|
+
return 0.5 * (c[:-1] + c[1:])[picked]
|
maggie/core/mesh.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Unstructured mesh topology.
|
|
2
|
+
|
|
3
|
+
Structured meshes need no class: a :class:`~maggie.core.field.Field` carries
|
|
4
|
+
their edges as coords on its ``x``/``y``/``z`` (or ``r``/``theta``/``phi``)
|
|
5
|
+
axes. An unstructured mesh (NeutronDiffusion's unstructured solver)
|
|
6
|
+
is stored here and attached to the field's ``cell`` axis.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(eq=False)
|
|
17
|
+
class UnstructuredMesh:
|
|
18
|
+
"""Cells as lists of point indices, stored compressed (CSR).
|
|
19
|
+
|
|
20
|
+
Cell ``i`` uses points ``connectivity[offsets[i]:offsets[i + 1]]``. For
|
|
21
|
+
polygons these are the vertices in order. For 3-D cells they are the
|
|
22
|
+
cell's distinct vertices, which is enough for centroids and slicing.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
points: np.ndarray # (n_points, 2 or 3)
|
|
26
|
+
connectivity: np.ndarray # (offsets[-1],) int
|
|
27
|
+
offsets: np.ndarray # (n_cells + 1,) int, starts at 0
|
|
28
|
+
|
|
29
|
+
def __post_init__(self) -> None:
|
|
30
|
+
self.points = np.asarray(self.points, dtype=float)
|
|
31
|
+
self.connectivity = np.asarray(self.connectivity, dtype=np.int64)
|
|
32
|
+
self.offsets = np.asarray(self.offsets, dtype=np.int64)
|
|
33
|
+
if self.points.ndim != 2 or self.points.shape[1] not in (2, 3):
|
|
34
|
+
raise ValueError(f"points must be (n, 2) or (n, 3), got {self.points.shape}")
|
|
35
|
+
if self.offsets.ndim != 1 or self.offsets.size < 1 or self.offsets[0] != 0:
|
|
36
|
+
raise ValueError("offsets must be 1-D and start at 0")
|
|
37
|
+
if self.offsets[-1] != self.connectivity.size:
|
|
38
|
+
raise ValueError(
|
|
39
|
+
f"offsets end at {self.offsets[-1]} but connectivity has "
|
|
40
|
+
f"{self.connectivity.size} entries")
|
|
41
|
+
if self.connectivity.size and (
|
|
42
|
+
self.connectivity.min() < 0 or self.connectivity.max() >= len(self.points)
|
|
43
|
+
):
|
|
44
|
+
raise ValueError("connectivity refers to points that do not exist")
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def n_cells(self) -> int:
|
|
48
|
+
return self.offsets.size - 1
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def spatial_dim(self) -> int:
|
|
52
|
+
return self.points.shape[1]
|
|
53
|
+
|
|
54
|
+
def cell(self, i: int) -> np.ndarray:
|
|
55
|
+
return self.connectivity[self.offsets[i]:self.offsets[i + 1]]
|
|
56
|
+
|
|
57
|
+
def centroids(self) -> np.ndarray:
|
|
58
|
+
"""Vertex-average centre of every cell, ``(n_cells, spatial_dim)``."""
|
|
59
|
+
counts = np.diff(self.offsets)
|
|
60
|
+
owner = np.repeat(np.arange(self.n_cells), counts)
|
|
61
|
+
sums = np.zeros((self.n_cells, self.spatial_dim))
|
|
62
|
+
np.add.at(sums, owner, self.points[self.connectivity])
|
|
63
|
+
return sums / np.maximum(counts, 1)[:, None]
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def from_cells(cls, points, cells) -> "UnstructuredMesh":
|
|
67
|
+
"""Build from a list of per-cell point-index sequences."""
|
|
68
|
+
cells = [np.asarray(c, dtype=np.int64).ravel() for c in cells]
|
|
69
|
+
offsets = np.zeros(len(cells) + 1, dtype=np.int64)
|
|
70
|
+
offsets[1:] = np.cumsum([c.size for c in cells])
|
|
71
|
+
conn = np.concatenate(cells) if cells else np.zeros(0, dtype=np.int64)
|
|
72
|
+
return cls(points, conn, offsets)
|