spacetimer 0.1.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.
spacetimer/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ from spacetimer.bitround import apply_keepbits, convention_keepbits, round_mantissa
4
+ from spacetimer.core import (
5
+ PRESETS,
6
+ Costs,
7
+ Encoding,
8
+ Preset,
9
+ Report,
10
+ SizeBasis,
11
+ UseCase,
12
+ VarSpec,
13
+ recommend,
14
+ report,
15
+ )
16
+
17
+ try:
18
+ __version__ = version("spacetimer")
19
+ except PackageNotFoundError:
20
+ __version__ = "0.0.0+dev"
21
+
22
+ __all__ = [
23
+ "PRESETS",
24
+ "Costs",
25
+ "Encoding",
26
+ "Preset",
27
+ "Report",
28
+ "SizeBasis",
29
+ "UseCase",
30
+ "VarSpec",
31
+ "apply_keepbits",
32
+ "convention_keepbits",
33
+ "recommend",
34
+ "report",
35
+ "round_mantissa",
36
+ ]
spacetimer/_html.py ADDED
@@ -0,0 +1,172 @@
1
+ """Notebook HTML for ``Report._repr_html_``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import html
7
+ import math
8
+ from collections.abc import Mapping
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from spacetimer._svg import cube_svg
13
+ from spacetimer.core import Costs, MiB, VarSpec
14
+
15
+ # no asterisks in this CSS: Python-Markdown reads them as emphasis when the docs embed it
16
+ # !important: JupyterLab and MkDocs Material both style tables in rendered HTML
17
+ REPORT_CSS = """<style>
18
+ .st-report{display:block;box-sizing:border-box;width:100%;max-width:900px;background:#14112e;color:#e7e4fa;border:2px solid #2b2557;
19
+ box-shadow:6px 6px 0 #07061a;padding:12px;margin:0 6px 6px 0;
20
+ font:11px/1.6 "Press Start 2P",ui-monospace,monospace}
21
+ .st-var{border-bottom:2px solid #2b2557;margin-bottom:8px;padding-bottom:6px}
22
+ .st-var:last-child{border:0;margin:0;padding:0}
23
+ .st-tog{display:block;cursor:pointer;color:#c9c4ee}
24
+ .st-tog b{color:#7ff0e4;font-weight:400}
25
+ .st-tog input{position:absolute;opacity:0}
26
+ .st-arrow::before{content:"▸";display:inline-block;width:1.2em;color:#3fc9bc;
27
+ font:16px/1 system-ui,sans-serif}
28
+ .st-tog input:checked+.st-arrow::before{content:"▾"}
29
+ .st-tog input:focus-visible+.st-arrow{outline:2px solid #ffd54a}
30
+ .st-tog:has(input:not(:checked))+.st-fold{display:none}
31
+ .st-fold{padding-left:1.6em}
32
+ .st-body{display:flex;flex-wrap:wrap;gap:16px;align-items:center;
33
+ justify-content:space-between;padding:8px 0}
34
+ .st-shard{display:none}
35
+ .st-var:has(.st-sh input:checked) .st-shard{display:inline}
36
+ .st-var:has(.st-sh input:checked) .st-chunk{display:none}
37
+ .st-sh{display:inline-block;margin-top:10px;color:#c9c4ee;cursor:pointer}
38
+ .st-sh input{accent-color:#3fc9bc;vertical-align:middle;margin:0 6px 0 0}
39
+ .st-report td.st-dims{text-align:center;color:#c9c4ee!important}
40
+ .st-note{color:#9c96c8;margin:6px 0 8px}
41
+ .st-read div{margin:4px 0}
42
+ .st-ic{display:inline-block;width:32px;height:32px;margin-right:10px;vertical-align:middle;
43
+ background:center no-repeat;image-rendering:pixelated}
44
+ .st-fig{flex:0 0 250px;height:240px;display:flex;align-items:center;justify-content:center}
45
+ .st-wide{flex-basis:100%}
46
+ .st-fig svg{max-width:100%;max-height:100%;width:auto;height:auto}
47
+ .st-enc{background:#07061a;border:2px solid #2b2557;padding:4px 8px;margin:6px 0 4px 1.6em}
48
+ .st-report .st-enc td{text-align:left}
49
+ .st-report .st-enc tr:first-child>th,.st-report .st-enc tr:first-child>td{border-top:0}
50
+ .st-report table{display:table;border-collapse:collapse;margin:0;border:0;font:inherit;font-size:10px}
51
+ .st-report tr{background:transparent!important}
52
+ .st-report th,.st-report td{padding:4px 7px;text-align:right;border:0;
53
+ border-top:2px solid #2b2557;color:#e7e4fa!important;background:transparent!important}
54
+ .st-report th{color:#3fc9bc!important;border-top:0;font-weight:400}
55
+ .st-report th:first-child,.st-report td:first-child{text-align:left}
56
+ </style>"""
57
+
58
+
59
+ def _icon_css(path: Path) -> str:
60
+ b = path.read_bytes()
61
+ # PNGs are 4x; bytes 16-24 of a PNG are its width and height
62
+ w, h = int.from_bytes(b[16:20]) // 4, int.from_bytes(b[20:24]) // 4
63
+ return (
64
+ f".st-ic-{path.stem}{{background-size:{w}px {h}px;"
65
+ f'background-image:url("data:image/png;base64,{base64.b64encode(b).decode()}")}}\n'
66
+ )
67
+
68
+
69
+ # the docs' time and space sprites, inlined so a notebook needs no assets
70
+ REPORT_CSS = REPORT_CSS.replace(
71
+ "</style>",
72
+ "".join(map(_icon_css, sorted((Path(__file__).parent / "icons").glob("*.png"))))
73
+ + "</style>",
74
+ )
75
+
76
+
77
+ def _fmt_bytes(n: float) -> str:
78
+ for unit in ("B", "KiB", "MiB", "GiB"):
79
+ if n < 1024:
80
+ return f"{n:,.0f} B" if unit == "B" else f"{n:,.1f} {unit}"
81
+ n /= 1024
82
+ return f"{n:,.1f} TiB"
83
+
84
+
85
+ def _codec_row(codec: Any) -> tuple[str, str]:
86
+ """Name and settings of a Zarr v3 codec, or a numcodecs one from a v2 store."""
87
+ if hasattr(codec, "to_dict"):
88
+ conf = codec.to_dict()
89
+ name, params = conf["name"], conf.get("configuration", {})
90
+ else:
91
+ params = dict(codec.get_config())
92
+ name = params.pop("id")
93
+ return str(name), ", ".join(f"{k}={v}" for k, v in params.items())
94
+
95
+
96
+ def _toggle(label: str, *, opened: bool) -> str:
97
+ return (
98
+ f'<label class="st-tog"><input type="checkbox"{" checked" if opened else ""}>'
99
+ f'<span class="st-arrow"></span>{label}</label>'
100
+ )
101
+
102
+
103
+ def _var_html(
104
+ spec: VarSpec, enc: Mapping[str, Any], costs: Costs, *, ratio: float, opened: bool
105
+ ) -> str:
106
+ chunks, shards = enc["chunks"], enc.get("shards")
107
+ cols = [("array", spec.shape), ("chunk", chunks)]
108
+ if shards:
109
+ cols.append(("shard", shards))
110
+ raw = [math.prod(g) * spec.dtype.itemsize for _, g in cols]
111
+ rows = [
112
+ ("shape", ["x".join(map(str, g)) for _, g in cols]),
113
+ ("size", [_fmt_bytes(b) for b in raw]),
114
+ (
115
+ "count",
116
+ [
117
+ f"{math.prod(math.ceil(n / k) for n, k in zip(spec.shape, g)):,}"
118
+ for _, g in cols
119
+ ],
120
+ ),
121
+ ]
122
+ th = "".join(f"<th>{h}</th>" for h in ("", *(c for c, _ in cols)))
123
+ trs = (
124
+ f'<tr><th>dims</th><td colspan="{len(cols)}" class="st-dims">'
125
+ f"{html.escape(' x '.join(spec.dims))}</td></tr>"
126
+ ) + "".join(
127
+ f"<tr><th>{label}</th>" + "".join(f"<td>{v}</td>" for v in vals) + "</tr>"
128
+ for label, vals in rows
129
+ )
130
+ reads = "".join(
131
+ f'<div><i class="st-ic st-ic-{icon}"></i>one {what} reads {n:,} chunk{"s" * (n != 1)}, '
132
+ f"{_fmt_bytes(mib * MiB)}</div>"
133
+ for icon, what, n, mib in (
134
+ ("space", "map", costs.slice_chunks, costs.slice_mib),
135
+ ("time", "time series", costs.series_chunks, costs.series_mib),
136
+ )
137
+ )
138
+ note = f"sizes are uncompressed; reads assume compression_ratio={ratio:g}"
139
+
140
+ def by_dim(grid: tuple[int, ...]) -> str:
141
+ return ", ".join(f"{d}={n}" for d, n in zip(spec.dims, grid))
142
+
143
+ kv = [("chunks", by_dim(chunks))]
144
+ if shards:
145
+ per = [s // c for s, c in zip(shards, chunks)]
146
+ kv += [
147
+ ("shards", by_dim(shards)),
148
+ ("chunks per shard", f"{' x '.join(map(str, per))} = {math.prod(per):,}"),
149
+ ]
150
+ kv += [_codec_row(codec) for codec in enc.get("compressors", ())]
151
+ enc_rows = "".join(
152
+ f"<tr><th>{html.escape(k)}</th><td>{html.escape(v)}</td></tr>" for k, v in kv
153
+ )
154
+ head = (
155
+ f"<b>{html.escape(spec.name)}</b> ({html.escape(', '.join(spec.dims))}) "
156
+ f"{spec.dtype}"
157
+ )
158
+ swap = (
159
+ '<label class="st-sh"><input type="checkbox">show shards</label>'
160
+ if shards
161
+ else ""
162
+ )
163
+ return (
164
+ f'<div class="st-var">{_toggle(head, opened=opened)}<div class="st-fold">'
165
+ f'<div class="st-body"><div><table class="st-info"><thead><tr>{th}</tr></thead>'
166
+ f"<tbody>{trs}</tbody></table>{swap}</div>"
167
+ f'<div class="st-fig{" st-wide" * (len(spec.dims) > 3)}">{cube_svg(spec.dims, spec.shape, chunks, shards)}</div></div>'
168
+ f'<div class="st-read">{reads}</div><div class="st-note">{note}</div>'
169
+ f"{_toggle('encoding', opened=False)}"
170
+ f'<div class="st-fold st-enc"><table class="st-kv">{enc_rows}</table></div>'
171
+ "</div></div>"
172
+ )
spacetimer/_svg.py ADDED
@@ -0,0 +1,196 @@
1
+ """Pixel-art chunk cube for ``Report._repr_html_``.
2
+
3
+ Same idea as ``dask.array.svg`` (oblique cube, capped line count), plus shards.
4
+ """
5
+
6
+ import html
7
+ import math
8
+ from typing import NamedTuple
9
+
10
+ # docs/stylesheets/spacetimer.css tokens; notebooks do not load that CSS
11
+ FRONT, TOP, SIDE = "#145b5c", "#1e7f7a", "#0f3b44"
12
+ LINE, LABEL, ZOOM = "#3fc9bc", "#c9c4ee", "#ffd54a"
13
+
14
+ EDGE = 96 # units for the longest axis
15
+ MAX_LINES = 16 # per axis, per layer
16
+ SCALE = 2 # screen px per unit
17
+ GAP = 10 # units between figures
18
+
19
+
20
+ def _edge(n: int, biggest: int) -> int:
21
+ """Log-scaled so 4480x32x32 stays readable."""
22
+ return max(4, round(EDGE * math.log(n + 1) / math.log(biggest + 1)))
23
+
24
+
25
+ def _stride(n: int, step: int, length: int, inner: int = 0) -> int:
26
+ """Draw every ``stride``-th block boundary when there are too many. A strided shard
27
+ grid (``inner`` = chunk size) draws fewer lines than its chunk grid, by log count."""
28
+ count = math.ceil(n / step)
29
+ cap = min(MAX_LINES, length // 6)
30
+ if inner and 0 < cap < count:
31
+ cap = max(1, round(cap * math.log(count) / math.log(math.ceil(n / inner))))
32
+ return math.ceil(count / (cap + 1))
33
+
34
+
35
+ def _cuts(n: int, step: int, length: int, outer: int = 0, inner: int = 0) -> list[int]:
36
+ """Unit offsets of block boundaries. With ``outer`` (shard size), the stride divides
37
+ the drawn shard spacing so every shard line is also a chunk line."""
38
+ stride = _stride(n, step, length, inner)
39
+ if outer and stride > 1:
40
+ span = outer // step * _stride(n, outer, length, step)
41
+ # nearest divisor, so chunks stay finer than shards; up to ~2x the line cap
42
+ divisors = {
43
+ d
44
+ for i in range(1, math.isqrt(span) + 1)
45
+ if span % i == 0
46
+ for d in (i, span // i)
47
+ }
48
+ stride = min(divisors, key=lambda c: abs(math.log(c / stride)))
49
+ count = math.ceil(n / step)
50
+ cuts = {round(k * step / n * length) for k in range(stride, count, stride)}
51
+ return sorted(cuts - {0, length})
52
+
53
+
54
+ def _poly(points: list[tuple[int, int]], fill: str) -> str:
55
+ pts = " ".join(f"{x},{y}" for x, y in points)
56
+ return f'<polygon points="{pts}" fill="{fill}"/>'
57
+
58
+
59
+ class _Fig(NamedTuple):
60
+ body: str
61
+ w: int
62
+ h: int
63
+ d: int
64
+ cell: tuple[int, int, int, int] # x, y, width, height of one front-face chunk
65
+
66
+
67
+ def cube_svg(
68
+ dims: tuple[str, ...],
69
+ shape: tuple[int, ...],
70
+ chunks: tuple[int, ...],
71
+ shards: tuple[int, ...] | None = None,
72
+ ) -> str:
73
+ """Up to three axes per figure, split like dask: the last three are the cube.
74
+
75
+ Each leading figure is linked to the next by a zoom callout: one of its
76
+ chunks (yellow) holds the whole figure to its right.
77
+ """
78
+ groups, start = [], 0
79
+ while start < len(shape):
80
+ stop = start + ((len(shape) - start) % 3 or 3)
81
+ groups.append(range(start, stop))
82
+ start = stop
83
+ figs = [
84
+ _cube(
85
+ _pick(dims, g),
86
+ _pick(shape, g),
87
+ _pick(chunks, g),
88
+ _pick(shards, g) if shards else None,
89
+ )
90
+ for g in groups
91
+ ]
92
+ height = max(f.h + f.d + 12 for f in figs)
93
+ parts, spots, x = [], [], 0
94
+ for f in figs:
95
+ ox, oy = x + 10, height - (f.h + f.d + 10)
96
+ spots.append((ox, oy))
97
+ parts.append(f'<g transform="translate({ox} {oy})">{f.body}</g>')
98
+ x += f.w + f.d + 12 + GAP
99
+ for (ox, oy), f, (nx, ny), nxt in zip(spots, figs, spots[1:], figs[1:]):
100
+ cx, cy, cw, ch = (f.cell[0] + ox, f.cell[1] + oy, *f.cell[2:])
101
+ parts.append(
102
+ f'<rect x="{cx}" y="{cy}" width="{cw}" height="{ch}" fill="{ZOOM}"/>'
103
+ )
104
+ parts += [
105
+ f'<line x1="{cx + cw}" y1="{cy + dy}" x2="{nx}" y2="{ny + nxt.d + ty}" '
106
+ f'stroke="{ZOOM}" stroke-width="0.5" stroke-dasharray="2 2"/>'
107
+ for dy, ty in ((0, 0), (ch, nxt.h))
108
+ ]
109
+ width = x - GAP
110
+ return (
111
+ f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
112
+ f'width="{width * SCALE}" height="{height * SCALE}" shape-rendering="crispEdges" '
113
+ f'overflow="visible" stroke="{LINE}" stroke-width="1">{"".join(parts)}</svg>'
114
+ )
115
+
116
+
117
+ def _pick[T](values: tuple[T, ...], axes: range) -> tuple[T, ...]:
118
+ return tuple(values[i] for i in axes)
119
+
120
+
121
+ def _labels(items: list[tuple[str, int, int, int]], anchor: str = "middle") -> str:
122
+ """(text, x, y, rotation) in units."""
123
+ texts = "".join(
124
+ f'<text x="{x}" y="{y}" transform="rotate({r} {x} {y})">{html.escape(t)}</text>'
125
+ for t, x, y, r in items
126
+ )
127
+ return f'<g stroke="none" fill="{LABEL}" font-size="5" text-anchor="{anchor}">{texts}</g>'
128
+
129
+
130
+ def _cube(
131
+ dims: tuple[str, ...],
132
+ shape: tuple[int, ...],
133
+ chunks: tuple[int, ...],
134
+ shards: tuple[int, ...] | None,
135
+ ) -> _Fig:
136
+ """Axes are (depth, down, across); fewer axes draw flatter."""
137
+ nd = len(shape)
138
+
139
+ def last3(v: tuple[int, ...]) -> tuple[int, int, int]:
140
+ z, y, x = (1,) * (3 - nd) + tuple(v[-nd:])
141
+ return z, y, x
142
+
143
+ nz, ny, nx = n3 = last3(shape)
144
+ biggest = max(n3)
145
+ w = _edge(nx, biggest)
146
+ h = _edge(ny, biggest) if nd >= 2 else 6
147
+ d = _edge(nz, biggest) // 2 if nd == 3 else 0
148
+
149
+ def grid(
150
+ steps: tuple[int, int, int],
151
+ cls: str,
152
+ outer: tuple[int, int, int] = (0, 0, 0),
153
+ inner: tuple[int, int, int] = (0, 0, 0),
154
+ ) -> str:
155
+ (sz, sy, sx), (oz, oy, ox), (iz, iy, ix) = steps, outer, inner
156
+ lines = []
157
+ for x in _cuts(nx, sx, w, ox, ix):
158
+ lines += [(x, d, x, d + h), (x, d, x + d, 0)]
159
+ for y in _cuts(ny, sy, h, oy, iy):
160
+ lines += [(0, d + y, w, d + y), (w, d + y, w + d, y)]
161
+ for z in _cuts(nz, sz, d, oz, iz):
162
+ lines += [(z, d - z, w + z, d - z), (w + z, d - z, w + z, d - z + h)]
163
+ marks = "".join(
164
+ f'<line x1="{a}" y1="{b}" x2="{c}" y2="{e}"/>' for a, b, c, e in lines
165
+ )
166
+ return f'<g class="{cls}" stroke-width="0.5">{marks}</g>'
167
+
168
+ front = [(0, d), (w, d), (w, d + h), (0, d + h)]
169
+ top = [(0, d), (w, d), (w + d, 0), (d, 0)]
170
+ side = [(w, d), (w + d, 0), (w + d, h), (w, d + h)]
171
+ body = [
172
+ _poly(front, FRONT),
173
+ _poly(top, TOP),
174
+ _poly(side, SIDE),
175
+ # REPORT_CSS shows one of the two; "show shards" swaps them
176
+ grid(last3(chunks), "st-chunk", outer=last3(shards) if shards else (0, 0, 0)),
177
+ grid(last3(shards), "st-shard", inner=last3(chunks)) if shards else "",
178
+ _poly(front, "none"),
179
+ _poly(top, "none"),
180
+ _poly(side, "none"),
181
+ ]
182
+ # axis names: across under the front face, down beside it, depth along the top edge
183
+ spots = [
184
+ (w // 2, d + h + 7, 0),
185
+ (-3, d + h // 2, -90),
186
+ (d // 2 - 3, d // 2 - 3, -45),
187
+ ]
188
+ body.append(_labels([(name, *at) for name, at in zip(reversed(dims), spots)]))
189
+ _, cy, cx = last3(chunks)
190
+ xs, ys = _cuts(nx, cx, w), _cuts(ny, cy, h)
191
+ # rightmost full-width chunk in the top row; the last one can be a sliver
192
+ edges = [0, *xs, w]
193
+ if len(edges) > 2 and edges[-1] - edges[-2] < edges[1]:
194
+ edges.pop()
195
+ cell = (edges[-2], d, edges[-1] - edges[-2], ys[0] if ys else h)
196
+ return _Fig("".join(body), w, h, d, cell)
spacetimer/bitround.py ADDED
@@ -0,0 +1,184 @@
1
+ from __future__ import annotations
2
+
3
+ import warnings
4
+ from collections.abc import Mapping
5
+
6
+ import numpy as np
7
+ import xarray as xr
8
+
9
+ from spacetimer.core import _PKG, Data, VarSpec, _specs
10
+
11
+ # keep_mantissa_bits by CF standard_name across dynamical.org reformatters'
12
+ # template configs (commit cb7d15b): the most common value, ties to the higher
13
+ KEEPBITS: dict[str, int] = {
14
+ **dict.fromkeys(
15
+ (
16
+ "eastward_wind",
17
+ "northward_wind",
18
+ "x_wind",
19
+ "y_wind",
20
+ "wind_speed",
21
+ "wind_speed_of_gust",
22
+ ),
23
+ 6,
24
+ ),
25
+ **dict.fromkeys(
26
+ (
27
+ "air_temperature",
28
+ "dew_point_temperature",
29
+ "sea_surface_temperature",
30
+ "soil_temperature",
31
+ "surface_temperature",
32
+ "precipitation_flux",
33
+ "runoff_flux",
34
+ "surface_runoff_flux",
35
+ "relative_humidity",
36
+ "specific_humidity",
37
+ "cloud_area_fraction",
38
+ "cloud_area_fraction_in_atmosphere_layer",
39
+ "sea_ice_area_fraction",
40
+ "surface_snow_area_fraction",
41
+ "surface_snow_density",
42
+ "surface_snow_thickness",
43
+ "lwe_thickness_of_surface_snow_amount",
44
+ "volume_fraction_of_condensed_water_in_soil",
45
+ "atmosphere_mass_content_of_water",
46
+ "atmosphere_mass_content_of_water_vapor",
47
+ "atmosphere_convective_available_potential_energy",
48
+ "lagrangian_tendency_of_air_pressure",
49
+ "surface_downward_eastward_stress",
50
+ "surface_downward_northward_stress",
51
+ "surface_downwelling_shortwave_flux_in_air",
52
+ "surface_downwelling_longwave_flux_in_air",
53
+ "surface_diffuse_downwelling_shortwave_flux_in_air",
54
+ "surface_direct_downwelling_shortwave_flux_in_air",
55
+ "surface_downward_latent_heat_flux",
56
+ "surface_downward_sensible_heat_flux",
57
+ "surface_net_downward_longwave_flux",
58
+ "surface_net_downward_shortwave_flux",
59
+ "toa_net_downward_longwave_flux",
60
+ "equivalent_reflectivity_factor",
61
+ ),
62
+ 7,
63
+ ),
64
+ **dict.fromkeys(
65
+ (
66
+ "convective_precipitation_flux",
67
+ "snowfall_flux",
68
+ "normalized_difference_vegetation_index",
69
+ ),
70
+ 8,
71
+ ),
72
+ "air_pressure": 10,
73
+ "surface_air_pressure": 11,
74
+ "air_pressure_at_mean_sea_level": 11,
75
+ "geopotential_height": 11,
76
+ "wind_from_direction": 12,
77
+ }
78
+ # their temperatures are in degC; bits are relative, so K needs about 5 more
79
+ CELSIUS_ONLY = frozenset(n for n in KEEPBITS if n.endswith("temperature"))
80
+ CELSIUS = frozenset({"degree_Celsius", "degrees_Celsius", "degC", "celsius", "°C"})
81
+ # bits are relative precision, so any pressure unit takes the same value
82
+ PRESSURE = frozenset({"Pa", "pascal", "pascals", "hPa", "kPa", "mbar", "millibar"})
83
+
84
+
85
+ def round_mantissa(values: np.ndarray, *, keepbits: int) -> np.ndarray:
86
+ """Round floats to ``keepbits`` mantissa bits, half to even. NaN is kept.
87
+
88
+ Same arithmetic as numcodecs BitRound, applied to the values before writing
89
+ so the store needs no extra codec (JS readers can't decode BitRound).
90
+ """
91
+ nmant = _nmant(values.dtype)
92
+ if not 0 <= keepbits <= nmant:
93
+ raise ValueError(f"keepbits must be in [0, {nmant}], got {keepbits}")
94
+ # the bit view below assumes native byte order (zarr v2 can return >f4)
95
+ values = values.astype(values.dtype.newbyteorder("="), copy=False)
96
+ if keepbits == nmant:
97
+ return values.copy()
98
+ uint = np.dtype(f"u{values.dtype.itemsize}").type
99
+ drop = nmant - keepbits
100
+ bits = np.ascontiguousarray(values).view(uint)
101
+ half = uint((1 << (drop - 1)) - 1)
102
+ mask = ~uint((1 << drop) - 1)
103
+ rounded = ((bits + ((bits >> uint(drop)) & uint(1)) + half) & mask).view(
104
+ values.dtype
105
+ )
106
+ return np.where(np.isnan(values), values, rounded)
107
+
108
+
109
+ def apply_keepbits(ds: xr.Dataset, *, keepbits: Mapping[str, int]) -> xr.Dataset:
110
+ """Return ``ds`` with each named variable rounded; lazy for dask-backed data."""
111
+ for name, k in keepbits.items():
112
+ if name not in ds.data_vars:
113
+ raise KeyError(f"keepbits names unknown variable {name!r}")
114
+ nmant = _nmant(ds[name].dtype)
115
+ if not 0 <= k <= nmant:
116
+ raise ValueError(f"keepbits for {name!r} must be in [0, {nmant}], got {k}")
117
+ return ds.assign(
118
+ {
119
+ name: xr.apply_ufunc(
120
+ round_mantissa,
121
+ ds[name],
122
+ kwargs={"keepbits": k},
123
+ dask="parallelized",
124
+ output_dtypes=[ds[name].dtype],
125
+ keep_attrs=True,
126
+ )
127
+ for name, k in keepbits.items()
128
+ }
129
+ )
130
+
131
+
132
+ def convention_keepbits(data: Data) -> dict[str, int]:
133
+ """Mantissa bits from dynamical.org's per-variable choices (``KEEPBITS``).
134
+
135
+ Matched on CF ``standard_name``, then on "wind", "precip", or "direction" in
136
+ the name or ``long_name``, or pressure ``units``. Temperatures match only in
137
+ degC: mantissa bits are relative precision, so 7 bits moves 288.15 K to
138
+ 288.0. Unmatched floats are left out and listed in a warning.
139
+ """
140
+ out: dict[str, int] = {}
141
+ unmatched: list[str] = []
142
+ for s in _specs(data):
143
+ if not np.issubdtype(s.dtype, np.floating):
144
+ continue
145
+ bits = _convention(s)
146
+ if bits is None:
147
+ unmatched.append(s.name)
148
+ else:
149
+ out[s.name] = min(bits, _nmant(s.dtype))
150
+ if unmatched:
151
+ warnings.warn(
152
+ f"no keepbits convention for {unmatched}; they are left unrounded "
153
+ "unless you add them to the dict",
154
+ skip_file_prefixes=_PKG,
155
+ )
156
+ return out
157
+
158
+
159
+ def _convention(spec: VarSpec) -> int | None:
160
+ # str(): zarr attrs can hold any JSON value
161
+ units, sn = (str(spec.attrs.get(k, "")) for k in ("units", "standard_name"))
162
+ if sn in KEEPBITS:
163
+ if sn in CELSIUS_ONLY and units not in CELSIUS:
164
+ return None
165
+ return KEEPBITS[sn]
166
+ # no known standard_name: match on names, at the table's values
167
+ text = " ".join(
168
+ str(s).lower() for s in (spec.name, sn, spec.attrs.get("long_name")) if s
169
+ )
170
+ if "direction" in text:
171
+ return KEEPBITS["wind_from_direction"]
172
+ if "wind" in text:
173
+ return KEEPBITS["eastward_wind"]
174
+ if "precip" in text:
175
+ return KEEPBITS["precipitation_flux"]
176
+ if units in PRESSURE:
177
+ return KEEPBITS["surface_air_pressure"]
178
+ return None
179
+
180
+
181
+ def _nmant(dtype: np.dtype) -> int:
182
+ if not np.issubdtype(dtype, np.floating):
183
+ raise TypeError(f"keepbits needs a float dtype, got {dtype}")
184
+ return int(np.finfo(dtype).nmant)