unxts.interop.numpyro 2.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.
@@ -0,0 +1,14 @@
1
+ """NumPyro integration for unxt.
2
+
3
+ This is the canonical package (unxts.interop.numpyro).
4
+ """
5
+
6
+ from ._src import patches as _patches
7
+ from ._src.handler import unitful
8
+ from ._src.rules import UnitfulError
9
+ from ._src.samples import attach_units
10
+ from ._version import version as __version__ # noqa: F401
11
+
12
+ _patches.install()
13
+
14
+ __all__ = ("UnitfulError", "attach_units", "unitful")
@@ -0,0 +1,3 @@
1
+ """Private implementation modules."""
2
+
3
+ __all__ = ()
@@ -0,0 +1,684 @@
1
+ """The `unitful` NumPyro handler."""
2
+
3
+ __all__ = ("unitful",)
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from types import MappingProxyType
7
+ from typing import Any
8
+
9
+ import jax
10
+ import numpy as np
11
+ import numpyro.distributions as dist
12
+ import numpyro.primitives as prim
13
+ from numpyro import handlers
14
+ from numpyro.contrib.control_flow.cond import cond_wrapper
15
+ from numpyro.contrib.control_flow.scan import scan_wrapper
16
+ from numpyro.distributions.util import lazy_property
17
+ from numpyro.primitives import Messenger
18
+ from plum import NotFoundLookupError
19
+
20
+ import unxt as u
21
+ from .rules import (
22
+ UnitfulError,
23
+ _dimensioned,
24
+ _has_quantity,
25
+ _is_q,
26
+ carrying_params,
27
+ leaf_path,
28
+ site_dimension,
29
+ strip_powers,
30
+ unwrap,
31
+ )
32
+
33
+ # Key in `msg["infer"]` holding ``(usys, unit)`` of the `unitful` that ran a
34
+ # sample site, with the unit the site was stripped in. `replay` copies a guide's
35
+ # `infer` into the model's message.
36
+ _TAG_KEY = "_unitful_site"
37
+
38
+
39
+ def _check_container(name: str, v: Any) -> None:
40
+ """Raise if `v` is a container that holds Quantities."""
41
+ if not _is_q(v) and any(_is_q(x) for x in jax.tree.leaves(v, is_leaf=_is_q)):
42
+ err = (
43
+ f"Site '{name}': the value is a container that holds Quantities. "
44
+ "unitful strips a value only when it is a Quantity itself; give "
45
+ "each Quantity a site of its own, or pass one Quantity array."
46
+ )
47
+ raise UnitfulError(err)
48
+
49
+
50
+ def _dimensionless(name: str, what: str, v: Any) -> Any:
51
+ """Strip a dimensionless Quantity; raise if `v` has a dimension."""
52
+ if u.dimension_of(v) != u.dimension("dimensionless"):
53
+ err = (
54
+ f"Site '{name}': {what} has dimension {u.dimension_of(v)}, "
55
+ "expected dimensionless."
56
+ )
57
+ raise UnitfulError(err)
58
+ return u.ustrip("", v)
59
+
60
+
61
+ def _is_unit_free(x: object) -> bool:
62
+ """Whether `x` is concrete and every element is zero or infinite."""
63
+ if isinstance(x, jax.core.Tracer):
64
+ return False
65
+ a = np.asarray(x)
66
+ return bool(np.all((a == 0) | np.isinf(a)))
67
+
68
+
69
+ def _check_bare(
70
+ name: str, fn: Any, carrying: list[tuple[str, Any, int]], *, in_body: bool
71
+ ) -> None:
72
+ """Raise if a parameter that carries the site dimension is bare, not 0 or ±inf.
73
+
74
+ `in_body` says the site is in a scan or cond body, where a bare tracer is
75
+ often a carry that started bare.
76
+ """
77
+ has_q = any(_is_q(v) for _, v, _ in carrying)
78
+ for path, v, _ in carrying:
79
+ if _is_q(v) or _is_unit_free(v):
80
+ continue
81
+ k = path.rsplit(".", 1)[-1]
82
+ if has_q:
83
+ err = (
84
+ f"Site '{name}': parameter '{k}' is bare next to Quantity "
85
+ "parameters; give it units."
86
+ )
87
+ else:
88
+ err = (
89
+ f"Site '{name}': parameter '{k}' is bare, and "
90
+ f"{type(unwrap(fn)).__name__} has a unit rule; give its "
91
+ "parameters units instead of using units=."
92
+ )
93
+ # Inside a body every bare value is a tracer, even a concrete 0.0
94
+ # start value, so the concrete-zero hint would not apply there.
95
+ if isinstance(v, jax.core.Tracer) and in_body:
96
+ err += (
97
+ " Inside a scan or cond body, a value passed in bare stays "
98
+ "bare: pass the scan's start value as a Quantity in the "
99
+ "usys unit, or the cond's operand as a Quantity, or pass "
100
+ "rewrap=False and add the units in the body."
101
+ )
102
+ elif isinstance(v, jax.core.Tracer):
103
+ err += (
104
+ " If it is a zero or an infinity, write it as a concrete 0.0 "
105
+ "or np.zeros(...), not jnp.zeros(...) inside the model."
106
+ )
107
+ raise UnitfulError(err)
108
+
109
+
110
+ def _restore(old: Any, new: Any) -> None:
111
+ """Copy onto `new` the state that NumPyro's pytree round trip drops from `old`.
112
+
113
+ Unflattening sets ``_validate_args`` from the instance dict, so it is None
114
+ when validation comes from the class default, and log_prob then skips the
115
+ support check. It also drops attributes that ``__init__`` sets outside the
116
+ pytree fields, such as ``Independent.reparametrized_params``. Cached lazy
117
+ properties stay dropped, since they hold the unstripped values.
118
+ """
119
+ if isinstance(old, dist.Distribution):
120
+ new._validate_args = old._validate_args # noqa: SLF001
121
+ for k, v in vars(old).items():
122
+ cached = isinstance(getattr(type(old), k, None), lazy_property)
123
+ if k not in vars(new) and not cached and not _has_quantity(v):
124
+ setattr(new, k, v)
125
+
126
+ def parts(t: Any) -> list[Any]: # the leaves, stopping at sub-distributions
127
+ def leaf(x: Any) -> bool:
128
+ return (x is not t and isinstance(x, dist.Distribution)) or _is_q(x)
129
+
130
+ return jax.tree.leaves(t, is_leaf=leaf)
131
+
132
+ for a, b in zip(parts(old), parts(new), strict=True):
133
+ if isinstance(a, dist.Distribution):
134
+ _restore(a, b)
135
+
136
+
137
+ def _rebuild(fn: Any, f: Callable[[tuple[Any, ...], Any], Any]) -> Any:
138
+ """Map `f` over the leaves of `fn`, keeping the state the rebuild drops."""
139
+ new = jax.tree_util.tree_map_with_path(f, fn, is_leaf=_is_q)
140
+ _restore(fn, new)
141
+ return new
142
+
143
+
144
+ def _strip_params(name: str, fn: Any, unit: Any) -> Any:
145
+ """Strip every Quantity in `fn`; return `fn` itself if it holds none.
146
+
147
+ A parameter that carries the dimension is stripped in `unit` to its power.
148
+ Any other Quantity is a shape parameter and must be dimensionless. Which is
149
+ which goes by the leaf's path, since NumPyro may reshape a parameter into a
150
+ new object while its support keeps the original.
151
+ """
152
+ if not _has_quantity(fn):
153
+ return fn
154
+ powers = strip_powers(fn) if unit is not None else {}
155
+
156
+ def strip(kp: tuple[Any, ...], v: Any) -> Any:
157
+ if not _is_q(v):
158
+ return v
159
+ path = leaf_path(fn, kp)
160
+ if path in powers:
161
+ return u.ustrip(unit ** powers[path], v)
162
+ if u.dimension_of(v) != u.dimension("dimensionless"):
163
+ err = (
164
+ f"Site '{name}': shape parameter '{path.rsplit('.', 1)[-1]}' has "
165
+ f"dimension {u.dimension_of(v)}; it must be dimensionless."
166
+ )
167
+ raise UnitfulError(err)
168
+ return u.ustrip("", v)
169
+
170
+ return _rebuild(fn, strip)
171
+
172
+
173
+ def _strip_scale(msg: dict[str, Any]) -> None:
174
+ """Strip a dimensionless Quantity scale, as `handlers.scale` sets; raise if not."""
175
+ name = msg["name"]
176
+ if _is_q(msg.get("scale")):
177
+ msg["scale"] = _dimensionless(name, "the scale", msg["scale"])
178
+ pts = msg.get("plate_to_scale") or {}
179
+ for k, sc in pts.items():
180
+ if _is_q(sc):
181
+ pts[k] = _dimensionless(name, "the scale", sc)
182
+
183
+
184
+ class _OuterStripper(Messenger):
185
+ """Strip a Quantity value that a handler outside `unitful` set.
186
+
187
+ Sits below every other handler on the stack, and just above every
188
+ `handlers.block`, so it processes after the handlers that may set a value
189
+ and post-processes before them: it strips the value before an outer
190
+ `trace` stores it.
191
+ """
192
+
193
+ def __init__(self, owner: "unitful") -> None:
194
+ self.owner = owner
195
+ super().__init__(None)
196
+
197
+ def process_message(self, msg: dict[str, Any]) -> None:
198
+ if msg["type"] not in ("sample", "deterministic", "param"):
199
+ return
200
+ v, name = msg["value"], msg["name"]
201
+ if msg["type"] == "sample":
202
+ _strip_scale(msg)
203
+ _check_container(name, v)
204
+ if not _is_q(v):
205
+ return
206
+ # By message, not name: an outer `scope` may have renamed the site.
207
+ unit = self.owner._msg_units.get(id(msg)) # noqa: SLF001
208
+ if unit is None and u.dimension_of(v) == u.dimension("dimensionless"):
209
+ msg["value"] = u.ustrip("", v)
210
+ return
211
+ if unit is None:
212
+ err = f"Site '{name}': a Quantity value was set at a site with no unit."
213
+ if msg["type"] == "param":
214
+ err += (
215
+ " If a callable init returns it, return a bare value in the "
216
+ "unit of usys, or pass the Quantity as the init value."
217
+ )
218
+ raise UnitfulError(err)
219
+ if u.dimension_of(v) != u.dimension_of(unit):
220
+ err = (
221
+ f"Site '{name}': value has dimension {u.dimension_of(v)}, "
222
+ f"expected {u.dimension_of(unit)}."
223
+ )
224
+ raise UnitfulError(err)
225
+ msg["value"] = u.ustrip(unit, v)
226
+
227
+ # The post-process pass checks values set while the site ran. A callable
228
+ # `param` init that returns a Quantity is one: `unitful` saw only the
229
+ # callable, recorded no unit, and this raises instead of letting the
230
+ # Quantity reach the trace.
231
+ postprocess_message = process_message
232
+
233
+
234
+ class unitful(Messenger): # noqa: N801 (NumPyro handler naming)
235
+ """Run a model whose distributions take Quantity parameters.
236
+
237
+ At each sample site the parameters and any observed value are stripped in
238
+ `usys`, so NumPyro computes on bare numbers and log p is per `usys` unit.
239
+ The sampled value goes back to the model as a Quantity in the `usys` unit of
240
+ the site's dimension (bare when ``rewrap=False``). ``units={"site": unit}``
241
+ sets the dimension of a site whose family has no rule; the site is still
242
+ expressed in `usys`. A ``units=`` value is a dimension (``"length"``) or
243
+ the `usys` unit of one, because bare parameters are read in `usys` units.
244
+ A key that names no sample site of the model raises `UnitfulError` when the
245
+ model returns. VonMises sites are always in radians. The body of a
246
+ `numpyro.contrib.control_flow.scan` and the branches of a
247
+ `numpyro.contrib.control_flow.cond` run under a `unitful` of their own with
248
+ the same `usys` and `rewrap`, so their sites are handled the same way.
249
+ A custom SVI guide needs a `unitful` with the same `usys`, as in
250
+ ``unitful(guide, model_handler.usys)``; a guide value replayed from another
251
+ `usys`, or from a site in another unit, raises `UnitfulError`. `usys` may
252
+ also be the name of a unit system, such as ``"galactic"``. A latent whose
253
+ parameters are all `unxt.Angle` comes back as an `unxt.Angle`.
254
+
255
+ Examples
256
+ --------
257
+ >>> import numpyro, numpyro.distributions as dist
258
+ >>> from numpyro import handlers
259
+ >>> import unxt as u
260
+ >>> from unxts.interop.numpyro import unitful
261
+
262
+ >>> def model():
263
+ ... return numpyro.sample("m", dist.Normal(u.Q(0.0, "pc"), u.Q(3.0, "pc")))
264
+
265
+ >>> m = handlers.seed(unitful(model, u.unitsystems.galactic), 0)()
266
+ >>> m.unit
267
+ Unit("kpc")
268
+
269
+ """
270
+
271
+ def __init__(
272
+ self,
273
+ fn: Callable[..., Any] | None,
274
+ usys: u.AbstractUnitSystem | str,
275
+ *,
276
+ rewrap: bool = True,
277
+ units: Mapping[str, Any] | None = None,
278
+ ) -> None:
279
+ if fn is None:
280
+ msg = "unitful needs a model: wrap it as unitful(model, usys)."
281
+ raise TypeError(msg)
282
+ if isinstance(usys, str):
283
+ usys = u.unitsystem(usys)
284
+ if not isinstance(usys, u.AbstractUnitSystem):
285
+ msg = (
286
+ "unitful needs a unit system, such as u.unitsystems.galactic "
287
+ f"or 'galactic', got {usys!r}."
288
+ )
289
+ raise TypeError(msg)
290
+ self.usys = usys
291
+ self.rewrap = rewrap
292
+ self._overrides = {
293
+ k: self._override_dimension(k, v) for k, v in (units or {}).items()
294
+ }
295
+ self._site_units: dict[str, Any] = {} # static units only
296
+ # Sample-site names as `unitful` sees them, before any outer rename.
297
+ self._seen: set[str] = set()
298
+ # Unit of each message between process and postprocess, keyed by
299
+ # id(msg): outer handlers such as `scope` may rename the site.
300
+ self._msg_units: dict[int, Any] = {}
301
+ # The tagged `infer` dict of each sample message, to see if `replay` swaps it.
302
+ self._msg_infer: dict[int, Any] = {}
303
+ # The Quantity type a sample site gives back, such as `u.Angle`.
304
+ self._msg_cls: dict[int, type] = {}
305
+ self._calls = 0 # depth of calls through `__call__`, not `with unitful(...)`
306
+ self._strippers: list[list[_OuterStripper]] = [] # per active entry
307
+ self._ran = False # whether any message reached the handler
308
+ self._in_body = False # whether this runs a scan or cond body
309
+ # The mark this handler leaves on a message. Bodies take their parent's,
310
+ # since `cond` needs both branches to leave the same trace metadata.
311
+ self._token = id(self)
312
+ super().__init__(fn)
313
+
314
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
315
+ """Run the model under this handler."""
316
+ self._calls += 1
317
+ try:
318
+ return super().__call__(*args, **kwargs)
319
+ finally:
320
+ self._calls -= 1
321
+
322
+ def __enter__(self) -> None:
323
+ stack = prim._PYRO_STACK # noqa: SLF001
324
+ # A stripper at the bottom of the stack, and one just above every
325
+ # `handlers.block`, since a block stops a message before it reaches the
326
+ # handlers below it. Stripping is idempotent. NumPyro processes from
327
+ # the top of the stack down and post-processes from the bottom up, so
328
+ # each stripper goes above the strippers of enclosing `unitful`s: the
329
+ # innermost one processes first and post-processes last. A scan or cond
330
+ # body runs under its own block, so its only stripper goes just above
331
+ # the innermost block, where the body's handlers start.
332
+ blocks = [i + 1 for i, h in enumerate(stack) if isinstance(h, handlers.block)]
333
+ floors = blocks[-1:] if self._in_body else [0, *blocks]
334
+ new = []
335
+ for floor in reversed(floors): # top first, so lower indices hold
336
+ i = next(
337
+ (
338
+ i
339
+ for i, h in enumerate(stack)
340
+ if i >= floor and not isinstance(h, _OuterStripper)
341
+ ),
342
+ len(stack),
343
+ )
344
+ s = _OuterStripper(self)
345
+ stack.insert(i, s)
346
+ new.append(s)
347
+ self._strippers.append(new)
348
+ super().__enter__()
349
+
350
+ def __exit__(self, *exc: object) -> None:
351
+ new = self._strippers.pop()
352
+ if not self._strippers:
353
+ self._msg_units.clear() # entries left by a site that raised
354
+ self._msg_infer.clear()
355
+ self._msg_cls.clear()
356
+ try:
357
+ super().__exit__(*exc)
358
+ finally:
359
+ stack = prim._PYRO_STACK # noqa: SLF001
360
+ stack[:] = [h for h in stack if not any(h is s for s in new)]
361
+ missing = sorted(self._overrides.keys() - self._seen)
362
+ if exc[0] is None and missing and not self._in_body:
363
+ renamed = [k for k in missing if k in self._site_units]
364
+ if renamed:
365
+ msg = (
366
+ f"units= names {renamed}, which are site names after a handler "
367
+ "outside unitful renamed them. Key units= by the name inside "
368
+ "unitful, or put the scope inside unitful."
369
+ )
370
+ else:
371
+ msg = (
372
+ f"units= names {missing}, which no call of the model has "
373
+ "reached yet."
374
+ )
375
+ raise UnitfulError(msg)
376
+
377
+ @property
378
+ def site_units(self) -> Mapping[str, Any]:
379
+ """Read-only map of site name to unit; None marks a unitless site."""
380
+ return MappingProxyType(self._site_units)
381
+
382
+ def _override_dimension(self, name: str, v: Any) -> Any:
383
+ """Return the dimension a ``units=`` value gives; a unit must be in `usys`."""
384
+ if isinstance(v, u.AbstractDimension):
385
+ return v
386
+ if isinstance(v, str):
387
+ try:
388
+ return u.dimension(v)
389
+ except ValueError:
390
+ pass
391
+ try:
392
+ unit = u.unit(v)
393
+ except (NotFoundLookupError, TypeError, ValueError) as e:
394
+ msg = (
395
+ f"Site '{name}': units= takes a dimension or a unit, such as "
396
+ f"'length' or 'kpc', got {v!r}."
397
+ )
398
+ raise UnitfulError(msg) from e
399
+ dim = u.dimension_of(unit)
400
+ want = self._unit(dim, name)
401
+ if unit != want:
402
+ msg = (
403
+ f"Site '{name}': units= gives {unit}, but bare parameters are read "
404
+ f"in the unit of usys; pass units={{'{name}': '{want}'}}."
405
+ )
406
+ raise UnitfulError(msg)
407
+ return dim
408
+
409
+ def _dimension(self, fn: Any, name: str) -> Any:
410
+ if name not in self._overrides:
411
+ return site_dimension(fn, name, self.usys)
412
+ dim = self._overrides[name]
413
+ if not carrying_params(fn) and _dimensioned(fn):
414
+ msg = (
415
+ f"Site '{name}': units= needs bare parameters, but the "
416
+ "distribution has Quantity parameters with dimensions and no "
417
+ "unit rule."
418
+ )
419
+ raise UnitfulError(msg)
420
+ rule = site_dimension(fn, name, self.usys) if carrying_params(fn) else None
421
+ if rule is not None and rule != dim:
422
+ msg = f"Site '{name}': units= gives {dim}, the distribution gives {rule}."
423
+ raise UnitfulError(msg)
424
+ return dim
425
+
426
+ def _unit(self, dim: Any, name: str) -> Any:
427
+ if dim is None:
428
+ return None
429
+ try:
430
+ return self.usys[dim]
431
+ except (KeyError, ValueError) as e:
432
+ msg = f"Site '{name}': the unit system has no unit for {dim}."
433
+ raise UnitfulError(msg) from e
434
+
435
+ def _record(self, name: str, unit: Any) -> None:
436
+ if self._site_units.setdefault(name, unit) != unit:
437
+ prev = self._site_units[name]
438
+ err = (
439
+ f"Site '{name}': has unit {prev} in one place and {unit} in "
440
+ "another. A site needs one unit in every call and in both "
441
+ "branches of a cond."
442
+ )
443
+ raise UnitfulError(err)
444
+
445
+ def _mark(self, msg: dict[str, Any], unit: Any) -> None:
446
+ """Record the unit of `msg` by site name and by message."""
447
+ self._record(msg["name"], unit)
448
+ self._msg_units[id(msg)] = unit
449
+
450
+ def _strip_value(self, msg: dict[str, Any], v: Any) -> Any:
451
+ """Strip a Quantity in `usys`, recording the site's unit; bare passes."""
452
+ _check_container(msg["name"], v)
453
+ if not _is_q(v):
454
+ self._mark(msg, None)
455
+ return v
456
+ unit = self._unit(u.dimension_of(v), msg["name"])
457
+ self._mark(msg, unit)
458
+ return u.ustrip(self.usys, v)
459
+
460
+ def _no_override(self, name: str, kind: str) -> None:
461
+ if name in self._overrides:
462
+ msg = f"Site '{name}': units= applies to sample sites, not {kind} sites."
463
+ raise UnitfulError(msg)
464
+
465
+ def _process_factor(self, msg: dict[str, Any]) -> None:
466
+ # `plate` and `mask` wrap the `Unit` distribution, so look underneath.
467
+ self._no_override(msg["name"], "factor")
468
+ name = msg["name"]
469
+ lf = unwrap(msg["fn"]).log_factor
470
+ if not _is_q(lf):
471
+ return
472
+ _dimensionless(name, "log_factor", lf)
473
+ msg["fn"] = _rebuild(
474
+ msg["fn"],
475
+ lambda _, v: _dimensionless(name, "log_factor", v) if _is_q(v) else v,
476
+ )
477
+
478
+ def process_message(self, msg: dict[str, Any]) -> None:
479
+ """Strip the units of a site and record the site's unit."""
480
+ self._ran = True
481
+ if msg["type"] == "control_flow":
482
+ self._process_control_flow(msg)
483
+ return
484
+ if msg.get("_control_flow_done", False) and "_unitful" in msg:
485
+ return # a scan or cond site that a body handler already stripped
486
+ if msg["type"] in ("sample", "deterministic", "param"):
487
+ # dict.copy keeps the mark, so a handler outside that re-sends a
488
+ # copy of a processed message is caught here.
489
+ if self._token in msg.get("_unitful", ()):
490
+ err = (
491
+ f"Site '{msg['name']}': this unitful already stripped the "
492
+ "site. Either the model calls the same unitful instance "
493
+ "again (make a new unitful, or call the bare model), or a "
494
+ "handler outside sent the site again, as handlers.do does "
495
+ "(put it inside: unitful(handlers.do(model, ...), usys))."
496
+ )
497
+ raise UnitfulError(err)
498
+ msg["_unitful"] = (*msg.get("_unitful", ()), self._token)
499
+ if msg["type"] == "deterministic":
500
+ self._no_override(msg["name"], "deterministic")
501
+ msg["value"] = self._strip_value(msg, msg["value"])
502
+ return
503
+ if msg["type"] == "param":
504
+ self._process_param(msg)
505
+ return
506
+ if msg["type"] != "sample":
507
+ return
508
+ _strip_scale(msg) # from handlers.scale inside unitful
509
+ if isinstance(unwrap(msg["fn"]), dist.Unit):
510
+ self._process_factor(msg)
511
+ else:
512
+ self._process_sample(msg)
513
+
514
+ def _process_param(self, msg: dict[str, Any]) -> None:
515
+ """Strip a param's init value, and its constraint's bounds in the same unit."""
516
+ name = msg["name"]
517
+ self._no_override(name, "param")
518
+ if msg["args"]:
519
+ msg["args"] = (self._strip_value(msg, msg["args"][0]),)
520
+ else:
521
+ self._mark(msg, None) # a callable init
522
+ con = msg["kwargs"].get("constraint")
523
+ if not any(_is_q(x) for x in jax.tree.leaves(con, is_leaf=_is_q)):
524
+ return
525
+ unit = self._msg_units[id(msg)]
526
+ if unit is None:
527
+ err = (
528
+ f"Site '{name}': the constraint has Quantity bounds, but the init "
529
+ "value is bare; pass the init value as a Quantity."
530
+ )
531
+ raise UnitfulError(err)
532
+
533
+ def strip(v: Any) -> Any:
534
+ if not _is_q(v):
535
+ return v
536
+ if u.dimension_of(v) != u.dimension_of(unit):
537
+ err = (
538
+ f"Site '{name}': a constraint bound has dimension "
539
+ f"{u.dimension_of(v)}, expected {u.dimension_of(unit)}."
540
+ )
541
+ raise UnitfulError(err)
542
+ return u.ustrip(unit, v)
543
+
544
+ con = jax.tree.map(strip, con, is_leaf=_is_q)
545
+ msg["kwargs"] = {**msg["kwargs"], "constraint": con}
546
+
547
+ def _process_control_flow(self, msg: dict[str, Any]) -> None:
548
+ """Run the body of a `scan` or the branches of a `cond` under a `unitful`.
549
+
550
+ Both run their functions under `handlers.block`, so this handler never
551
+ sees those sites while they run, and replay them afterwards with the
552
+ values already set. A handler inside the block strips them as they run.
553
+ """
554
+ if msg["fn"] is scan_wrapper:
555
+ msg["args"] = (self._body(msg["args"][0]), *msg["args"][1:])
556
+ elif msg["fn"] is cond_wrapper:
557
+ pred, t, f, *rest = msg["args"]
558
+ msg["args"] = (pred, self._body(t), self._body(f), *rest)
559
+
560
+ def _body(self, fn: Callable[..., Any]) -> "unitful":
561
+ body = unitful(fn, self.usys, rewrap=self.rewrap)
562
+ # Share the records, so units= and `site_units` cover the body's sites.
563
+ body._overrides = self._overrides
564
+ body._site_units = self._site_units
565
+ body._seen = self._seen
566
+ body._in_body = True
567
+ body._token = self._token
568
+ return body
569
+
570
+ def _process_sample(self, msg: dict[str, Any]) -> None:
571
+ name, fn = msg["name"], msg["fn"]
572
+ self._seen.add(name)
573
+ dim = self._dimension(fn, name)
574
+ # VonMises works in radians whatever the usys angle unit is.
575
+ if dim is not None and isinstance(unwrap(fn), dist.VonMises):
576
+ unit = u.unit("rad")
577
+ else:
578
+ unit = self._unit(dim, name)
579
+ # Tag the site, so a guide in another usys or unit is caught when
580
+ # replayed here. The innermost unitful's tag stays: nested ones keep
581
+ # the same dict.
582
+ infer = msg.get("infer", {})
583
+ if _TAG_KEY not in infer:
584
+ msg["infer"] = {**infer, _TAG_KEY: (self.usys, unit)}
585
+ self._msg_infer[id(msg)] = msg["infer"]
586
+
587
+ # A dimensionless site is unambiguous, so bare numbers there are fine.
588
+ none = u.dimension("dimensionless")
589
+ checked = dim is not None and dim != none
590
+ _check_bare(
591
+ name, fn, carrying_params(fn) if checked else [], in_body=self._in_body
592
+ )
593
+
594
+ # Any value here comes from obs= or an inner handler: inference handlers
595
+ # sit outside `unitful` and set the value after this runs.
596
+ value = msg["value"]
597
+ _check_container(name, value)
598
+ if _is_q(value):
599
+ expected = dim if dim is not None else none
600
+ if u.dimension_of(value) != expected:
601
+ err = (
602
+ f"Site '{name}': value has dimension {u.dimension_of(value)}, "
603
+ f"expected {expected}."
604
+ )
605
+ raise UnitfulError(err)
606
+ elif checked and value is not None:
607
+ # VonMises is read in radians whatever the usys angle unit is.
608
+ vm = isinstance(unwrap(fn), dist.VonMises)
609
+ of_usys = "" if vm else ", the unit of usys"
610
+ err = (
611
+ f"Site '{name}': value is bare. A bare value would be read in "
612
+ f"{unit}{of_usys}; wrap the data in its own unit, as in "
613
+ "u.Q(value, <your unit>)."
614
+ )
615
+ if not self._calls:
616
+ err += (
617
+ " unitful is in use as a context manager, so handlers such as "
618
+ "log_density's substitute run inside it and set bare values. "
619
+ "Wrap the model instead: log_density(unitful(model, usys), ...)."
620
+ )
621
+ raise UnitfulError(err)
622
+
623
+ self._mark(msg, unit)
624
+ qs = [v for _, v, _ in carrying_params(fn) if _is_q(v)]
625
+ if qs and all(isinstance(v, u.Angle) for v in qs):
626
+ self._msg_cls[id(msg)] = u.Angle
627
+
628
+ msg["fn"] = _strip_params(name, fn, unit)
629
+ if _is_q(value):
630
+ msg["value"] = u.ustrip("" if unit is None else unit, value)
631
+
632
+ def _check_replayed(self, msg: dict[str, Any], unit: Any) -> None:
633
+ """Raise if `replay` brought this site a value made in another usys or unit.
634
+
635
+ A bare site, in the guide or here, has no unit to compare.
636
+ """
637
+ infer = self._msg_infer.pop(id(msg), None)
638
+ new = msg.get("infer", {}) # `reparam` drops the key
639
+ if infer is None or new is infer or _TAG_KEY not in new:
640
+ return
641
+ other, other_unit = new[_TAG_KEY]
642
+ if other != self.usys:
643
+ err = (
644
+ f"Site '{msg['name']}': the replayed value (for example from an "
645
+ f"SVI guide) was made under unitful with usys {other}, but the "
646
+ f"model runs under {self.usys}. Bare values are read in the usys "
647
+ "unit, so both must share one usys: unitful(guide, "
648
+ "model_handler.usys)."
649
+ )
650
+ raise UnitfulError(err)
651
+ if None not in (unit, other_unit) and other_unit != unit:
652
+ err = (
653
+ f"Site '{msg['name']}': the replayed value (for example from an "
654
+ f"SVI guide) is in {other_unit}, but the model reads this site "
655
+ f"in {unit}. "
656
+ )
657
+ if u.dimension_of(unit) != u.dimension_of(other_unit):
658
+ err += f"Give the guide's site the dimension {u.dimension_of(unit)}."
659
+ else:
660
+ err += (
661
+ "A VonMises site is always in rad, so the guide and the "
662
+ "model need a VonMises at this site in both, or a usys "
663
+ "whose angle unit is rad."
664
+ )
665
+ raise UnitfulError(err)
666
+
667
+ def postprocess_message(self, msg: dict[str, Any]) -> None:
668
+ """Give a site's value back to the model as a Quantity."""
669
+ if id(msg) not in self._msg_units:
670
+ return
671
+ unit = self._msg_units.pop(id(msg))
672
+ cls = self._msg_cls.pop(id(msg), u.Q)
673
+ self._check_replayed(msg, unit)
674
+ # An outer `scope` may have renamed the site since `process_message`.
675
+ self._record(msg["name"], unit)
676
+ if _is_q(msg["value"]):
677
+ err = (
678
+ f"Site '{msg['name']}': a Quantity value set outside unitful "
679
+ "reached the site unstripped. Put the handler that set it "
680
+ "inside unitful, as unitful(handler(model, ...), usys)."
681
+ )
682
+ raise UnitfulError(err)
683
+ if unit is not None and self.rewrap:
684
+ msg["value"] = cls(msg["value"], unit)
@@ -0,0 +1,106 @@
1
+ """Patches for two NumPyro bugs that break `unxt.Quantity` distribution parameters.
2
+
3
+ `install` is idempotent and runs when the package is imported. Each patch is
4
+ applied only if a feature test shows the installed NumPyro still has the bug.
5
+ The patched functions behave like the originals except for a pytree that holds
6
+ a tracer (even a one-leaf container) and an array-like with its own
7
+ ``reshape``.
8
+ """
9
+
10
+ __all__ = ("NOT_JAX_TRACER_PATCHED", "RESHAPE_PATCHED", "install")
11
+
12
+ import sys
13
+ from typing import Any
14
+
15
+ import jax
16
+ import jax.numpy as jnp
17
+ import numpy as np
18
+ import numpyro.distributions # noqa: F401 (load the modules whose copies we patch)
19
+ import numpyro.distributions.util as ndu
20
+ import numpyro.util as nu
21
+
22
+ import unxt as u
23
+
24
+ NOT_JAX_TRACER_PATCHED: bool = False
25
+ RESHAPE_PATCHED: bool = False
26
+
27
+ # Looked up defensively: a NumPyro release that renames or removes one of
28
+ # these skips that patch instead of breaking import.
29
+ _original_not_jax_tracer = getattr(nu, "not_jax_tracer", None)
30
+ _original_reshape = getattr(ndu, "_reshape", None)
31
+
32
+
33
+ def _not_jax_tracer(x: Any) -> bool:
34
+ """Return True if no leaf of the pytree `x` is a JAX tracer."""
35
+ return not any(isinstance(leaf, jax.core.Tracer) for leaf in jax.tree.leaves(x))
36
+
37
+
38
+ def _reshape(x: Any, shape: Any) -> Any:
39
+ """Reshape `x`, using its own ``reshape`` for array-likes such as Quantity."""
40
+ if isinstance(x, (int, float, np.ndarray, np.generic)):
41
+ return np.reshape(x, shape)
42
+ if hasattr(x, "reshape"):
43
+ return x.reshape(shape)
44
+ return jnp.reshape(x, shape)
45
+
46
+
47
+ # The feature tests only trace, so importing the package does not start the JAX
48
+ # backend (which would make `numpyro.set_host_device_count` a no-op).
49
+ _ABSTRACT_SCALAR = jax.ShapeDtypeStruct((), np.float32)
50
+
51
+
52
+ def _not_jax_tracer_is_broken() -> bool:
53
+ """Whether the installed `not_jax_tracer` misses tracers inside a Quantity."""
54
+ seen = []
55
+ try:
56
+ jax.make_jaxpr(lambda x: seen.append(nu.not_jax_tracer(u.Q(x, "m"))) or x)(
57
+ _ABSTRACT_SCALAR
58
+ )
59
+ # A probe that fails cannot tell, so skip the patch; it must not break import.
60
+ except Exception: # noqa: BLE001 # pylint: disable=broad-exception-caught
61
+ return False
62
+ return seen[0] is not False
63
+
64
+
65
+ def _reshape_is_broken() -> bool:
66
+ """Whether the installed `_reshape` rejects a Quantity."""
67
+ try:
68
+ jax.make_jaxpr(lambda x: ndu._reshape(u.Q(x, "m"), (1,)).value)( # noqa: SLF001
69
+ _ABSTRACT_SCALAR
70
+ )
71
+ # Any failure means the patch is needed; an unexpected kind must not break import.
72
+ except Exception: # noqa: BLE001 # pylint: disable=broad-exception-caught
73
+ return True
74
+ return False
75
+
76
+
77
+ def _rebind(attr: str, original: Any, patched: Any) -> None:
78
+ """Replace `original` with `patched` in every loaded numpyro module."""
79
+ for name, mod in list(sys.modules.items()):
80
+ if (name == "numpyro" or name.startswith("numpyro.")) and (
81
+ getattr(mod, attr, None) is original
82
+ ):
83
+ setattr(mod, attr, patched)
84
+
85
+
86
+ def install() -> None:
87
+ """Install the patches that the installed NumPyro still needs."""
88
+ # pylint: disable-next=global-statement
89
+ global NOT_JAX_TRACER_PATCHED, RESHAPE_PATCHED # noqa: PLW0603
90
+
91
+ # ponytail: delete when the numpyro floor includes pyro-ppl/numpyro#2428
92
+ if (
93
+ not NOT_JAX_TRACER_PATCHED
94
+ and _original_not_jax_tracer is not None
95
+ and _not_jax_tracer_is_broken()
96
+ ):
97
+ # numpyro.util first, so modules imported later bind the patched copy.
98
+ nu.not_jax_tracer = _not_jax_tracer
99
+ _rebind("not_jax_tracer", _original_not_jax_tracer, _not_jax_tracer)
100
+ NOT_JAX_TRACER_PATCHED = True
101
+
102
+ # ponytail: delete when the numpyro floor includes pyro-ppl/numpyro#2429
103
+ if not RESHAPE_PATCHED and _original_reshape is not None and _reshape_is_broken():
104
+ ndu._reshape = _reshape # noqa: SLF001
105
+ _rebind("_reshape", _original_reshape, _reshape)
106
+ RESHAPE_PATCHED = True
@@ -0,0 +1,302 @@
1
+ """Per-family rules for the physical dimension of a NumPyro sample site."""
2
+
3
+ __all__ = (
4
+ "UnitfulError",
5
+ "carrying_params",
6
+ "dimension_params",
7
+ "leaf_path",
8
+ "site_dimension",
9
+ "strip_powers",
10
+ "unwrap",
11
+ )
12
+
13
+ import contextlib
14
+ from typing import Any
15
+
16
+ import jax
17
+ import numpyro.distributions as dist
18
+ from numpyro.distributions import transforms as tfm
19
+ from plum import Dispatcher
20
+
21
+ import unxt as u
22
+
23
+ # Private, so the package's methods never mix with other `plum.dispatch` users.
24
+ dispatch = Dispatcher()
25
+
26
+ # Wrappers whose ``base_dist`` carries the parameters.
27
+ _BASE_WRAPPERS = (
28
+ dist.Independent,
29
+ dist.ExpandedDistribution,
30
+ dist.MaskedDistribution,
31
+ dist.LeftTruncatedDistribution,
32
+ dist.RightTruncatedDistribution,
33
+ dist.TwoSidedTruncatedDistribution,
34
+ )
35
+
36
+
37
+ class UnitfulError(ValueError):
38
+ """A sample site's units are missing, inconsistent or unsupported.
39
+
40
+ Examples
41
+ --------
42
+ >>> import numpyro, numpyro.distributions as dist
43
+ >>> from numpyro import handlers
44
+ >>> import unxt as u
45
+ >>> from unxts.interop.numpyro import UnitfulError, unitful
46
+
47
+ >>> def model():
48
+ ... numpyro.sample("m", dist.Normal(1.0, u.Q(3.0, "kpc")))
49
+
50
+ >>> try:
51
+ ... handlers.seed(unitful(model, u.unitsystems.galactic), 0)()
52
+ ... except UnitfulError as e:
53
+ ... print(e)
54
+ Site 'm': parameter 'loc' is bare next to Quantity parameters; give it units.
55
+
56
+ """
57
+
58
+
59
+ UnitfulError.__module__ = "unxts.interop.numpyro" # the public path, for tracebacks
60
+
61
+
62
+ @dispatch
63
+ def dimension_params(d: dist.Distribution) -> dict[str, int]:
64
+ """Map parameter name to its power of the site dimension (none: unregistered)."""
65
+ return {}
66
+
67
+
68
+ @dispatch
69
+ def dimension_params(
70
+ d: dist.Normal
71
+ | dist.Cauchy
72
+ | dist.StudentT
73
+ | dist.Laplace
74
+ | dist.Logistic
75
+ | dist.Gumbel,
76
+ ) -> dict[str, int]:
77
+ return {"loc": 1, "scale": 1}
78
+
79
+
80
+ @dispatch
81
+ def dimension_params(d: dist.VonMises) -> dict[str, int]:
82
+ return {"loc": 1}
83
+
84
+
85
+ @dispatch
86
+ def dimension_params(d: dist.HalfNormal | dist.HalfCauchy) -> dict[str, int]:
87
+ return {"scale": 1}
88
+
89
+
90
+ @dispatch
91
+ def dimension_params(
92
+ d: dist.Uniform | dist.TwoSidedTruncatedDistribution,
93
+ ) -> dict[str, int]:
94
+ return {"low": 1, "high": 1}
95
+
96
+
97
+ @dispatch
98
+ def dimension_params(d: dist.LeftTruncatedDistribution) -> dict[str, int]:
99
+ return {"low": 1}
100
+
101
+
102
+ @dispatch
103
+ def dimension_params(d: dist.RightTruncatedDistribution) -> dict[str, int]:
104
+ return {"high": 1}
105
+
106
+
107
+ @dispatch
108
+ def dimension_params(d: dist.Exponential | dist.Gamma) -> dict[str, int]:
109
+ return {"rate": -1}
110
+
111
+
112
+ @dispatch
113
+ def dimension_params(d: dist.Chi2) -> dict[str, int]:
114
+ # `Chi2` is a `Gamma`, but its only parameter, `df`, is a shape parameter.
115
+ return {}
116
+
117
+
118
+ @dispatch
119
+ def dimension_params(d: dist.Delta) -> dict[str, int]:
120
+ return {"v": 1}
121
+
122
+
123
+ def unwrap(d: dist.Distribution) -> dist.Distribution:
124
+ """Follow wrappers and mixtures down to the distribution that has the units."""
125
+ while True:
126
+ if isinstance(d, _BASE_WRAPPERS):
127
+ d = d.base_dist
128
+ elif isinstance(d, dist.MixtureSameFamily):
129
+ d = d.component_distribution
130
+ else:
131
+ return d
132
+
133
+
134
+ def _is_q(x: object) -> bool:
135
+ return isinstance(x, u.quantity.AbstractQuantity)
136
+
137
+
138
+ def _children(d: dist.Distribution) -> list[tuple[str, dist.Distribution]]:
139
+ """Return ``(attribute, distribution)`` for each distribution directly in `d`."""
140
+ if isinstance(d, (*_BASE_WRAPPERS, dist.TransformedDistribution)):
141
+ return [("base_dist", d.base_dist)]
142
+ if isinstance(d, dist.MixtureSameFamily):
143
+ return [("component_distribution", d.component_distribution)]
144
+ return []
145
+
146
+
147
+ def _has_quantity(d: dist.Distribution) -> bool:
148
+ """Whether any leaf of `d`, at any depth, is a Quantity.
149
+
150
+ Distributions and transforms are pytrees, so this also sees composites
151
+ without a unit rule (`MixtureGeneral`, the censored distributions,
152
+ `ComposeTransform` parts).
153
+ """
154
+ return any(_is_q(x) for x in jax.tree.leaves(d, is_leaf=_is_q))
155
+
156
+
157
+ def _dimensioned(d: dist.Distribution) -> bool:
158
+ """Whether any leaf of `d`, at any depth, is a Quantity with a dimension."""
159
+ none = u.dimension("dimensionless")
160
+ leaves = jax.tree.leaves(d, is_leaf=_is_q)
161
+ return any(_is_q(x) and u.dimension_of(x) != none for x in leaves)
162
+
163
+
164
+ # A support constraint holds the bounds it was built from.
165
+ _BOUNDS = {"_support.lower_bound": "low", "_support.upper_bound": "high"}
166
+
167
+
168
+ def leaf_path(tree: Any, path: tuple[Any, ...]) -> str:
169
+ """Return the dotted attribute path of the leaf at the JAX key `path`.
170
+
171
+ NumPyro distributions, constraints and transforms flatten to unnamed
172
+ children, so the names come from their ``tree_flatten`` field lists. A
173
+ support bound is named after the parameter it comes from, so the upper
174
+ bound of a `Uniform` support is ``"high"``.
175
+ """
176
+ names = []
177
+ for key in path:
178
+ if isinstance(key, jax.tree_util.FlattenedIndexKey):
179
+ children, aux = tree.tree_flatten()
180
+ fields = (
181
+ type(tree).gather_pytree_data_fields()
182
+ if isinstance(tree, dist.Distribution)
183
+ else aux[0]
184
+ )
185
+ names.append(fields[key.key])
186
+ tree = children[key.key]
187
+ elif isinstance(key, jax.tree_util.SequenceKey):
188
+ names.append(str(key.idx))
189
+ tree = tree[key.idx]
190
+ elif isinstance(key, jax.tree_util.DictKey):
191
+ names.append(str(key.key))
192
+ tree = tree[key.key]
193
+ else: # GetAttrKey
194
+ names.append(key.name)
195
+ tree = getattr(tree, key.name)
196
+ out = ".".join(names)
197
+ for b, p in _BOUNDS.items():
198
+ if out == b or out.endswith("." + b):
199
+ out = out[: -len(b)] + p
200
+ return out
201
+
202
+
203
+ def carrying_params(d: dist.Distribution) -> list[tuple[str, Any, int]]:
204
+ """Return ``(path, value, power)`` for every parameter carrying the site dimension.
205
+
206
+ The path is the dotted attribute path from `d`, as `leaf_path` gives it.
207
+ The walk goes through wrappers (including truncation bounds), mixtures and a
208
+ single `AffineTransform` over a unitless base. Values may be bare or Quantity.
209
+ Other transformed distributions give an empty list.
210
+ """
211
+ if isinstance(d, dist.TransformedDistribution):
212
+ (t,) = d.transforms if len(d.transforms) == 1 else (None,)
213
+ if isinstance(t, tfm.AffineTransform) and not _has_quantity(d.base_dist):
214
+ return [("transforms.0.loc", t.loc, 1), ("transforms.0.scale", t.scale, 1)]
215
+ return []
216
+ own = [(k, getattr(d, k), p) for k, p in dimension_params(d).items()]
217
+ return own + [
218
+ (f"{a}.{k}", v, p) for a, c in _children(d) for k, v, p in carrying_params(c)
219
+ ]
220
+
221
+
222
+ def strip_powers(d: dist.Distribution) -> dict[str, int]:
223
+ """Map the path of every leaf that carries the site dimension to its power.
224
+
225
+ Like `carrying_params`, but it also follows a family's internal
226
+ distributions, such as the ``_cauchy`` that `HalfCauchy` builds from its
227
+ ``scale``, so their copies of the parameters are stripped the same way.
228
+ """
229
+ if isinstance(d, dist.TransformedDistribution):
230
+ return {k: p for k, _, p in carrying_params(d)}
231
+ out = dict(dimension_params(d))
232
+ for f in type(d).gather_pytree_data_fields():
233
+ c = d.__dict__.get(f)
234
+ if isinstance(c, dist.Distribution):
235
+ out |= {f"{f}.{k}": p for k, p in strip_powers(c).items()}
236
+ return out
237
+
238
+
239
+ def _no_rule_hint(d: dist.Distribution, name: str, usys: Any) -> str:
240
+ """Say what to do with dimensioned Quantities in a family with no unit rule."""
241
+ support = getattr(type(unwrap(d)), "support", None)
242
+ try:
243
+ count = isinstance(support, dist.constraints.Constraint) and support.is_discrete
244
+ except NotImplementedError: # a support that depends on the parameters
245
+ count = False
246
+ if count:
247
+ return "its samples are counts, so its parameters must be dimensionless."
248
+ none = u.dimension("dimensionless")
249
+ leaves = jax.tree.leaves(d, is_leaf=_is_q)
250
+ dims = {u.dimension_of(x) for x in leaves if _is_q(x)} - {none}
251
+ hint = "<the site's dimension>"
252
+ if len(dims) == 1:
253
+ (dim,) = dims
254
+ hint = repr(str(dim))
255
+ with contextlib.suppress(KeyError, ValueError, TypeError):
256
+ hint = repr(str(usys[dim]))
257
+ return (
258
+ "give it bare parameters in the units of usys and pass "
259
+ f"units={{'{name}': {hint}}} to unitful."
260
+ )
261
+
262
+
263
+ def site_dimension(
264
+ d: dist.Distribution, name: str, usys: Any = None
265
+ ) -> u.AbstractDimension | None:
266
+ """Return the dimension of the support of `d`, or None for a unitless site.
267
+
268
+ A site is unitless when none of the parameters that carry its dimension is
269
+ a Quantity and no Quantity anywhere in `d` has a dimension. A site whose
270
+ carrying Quantities are dimensionless has dimension ``dimensionless``. Raises
271
+ `UnitfulError` naming the site `name` when the dimensioned parameters
272
+ disagree, when a Quantity with a dimension is in a family with no rule or
273
+ next to bare dimension-carrying parameters, or when a VonMises site is not
274
+ an angle. `usys`, if given, names the unit to suggest in the error.
275
+ """
276
+ entries = carrying_params(d)
277
+ dims = [u.dimension_of(v) ** p for _, v, p in entries if _is_q(v)]
278
+ if not dims:
279
+ # A dimensionless Quantity says nothing about the site's dimension.
280
+ if not _dimensioned(d):
281
+ return None
282
+ fam = type(unwrap(d)).__name__
283
+ if entries:
284
+ bare = ", ".join(f"'{k.rsplit('.', 1)[-1]}'" for k, _, _ in entries)
285
+ msg = (
286
+ f"Site '{name}': {fam} has Quantity parameters, but the parameters "
287
+ f"that carry the site's dimension ({bare}) are bare; give them units."
288
+ )
289
+ else:
290
+ msg = (
291
+ f"Site '{name}': {fam} has Quantity parameters with dimensions but "
292
+ f"no unit rule; {_no_rule_hint(d, name, usys)}"
293
+ )
294
+ raise UnitfulError(msg)
295
+ if any(dm != dims[0] for dm in dims):
296
+ names = ", ".join(sorted({str(dm) for dm in dims}))
297
+ msg = f"Site '{name}': parameters have different dimensions: {names}."
298
+ raise UnitfulError(msg)
299
+ if isinstance(unwrap(d), dist.VonMises) and dims[0] != u.dimension("angle"):
300
+ msg = f"Site '{name}': VonMises needs an angle, got {dims[0]}."
301
+ raise UnitfulError(msg)
302
+ return dims[0]
@@ -0,0 +1,49 @@
1
+ """Give units back to samples."""
2
+
3
+ __all__ = ("attach_units",)
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+ import unxt as u
9
+ from .handler import unitful
10
+ from .rules import UnitfulError, _is_q
11
+
12
+
13
+ def attach_units(samples: Mapping[str, Any], handler: unitful, /) -> dict[str, Any]:
14
+ """Wrap the samples of each site `handler` recorded in that site's unit.
15
+
16
+ Quantities and keys the handler never saw (for example ``_sig_log_det``
17
+ from MCMC) pass through unchanged. Batched values are wrapped as they are.
18
+
19
+ `samples` are site values, as from `MCMC.get_samples`, `Predictive` or SVI
20
+ params. The output of `numpyro.infer.log_likelihood` is log densities, not
21
+ site values, so it does not go through here. `handler` must be the one that
22
+ produced the samples: the values are bare numbers in its `usys`, so another
23
+ handler's units would be wrong without any error.
24
+
25
+ Examples
26
+ --------
27
+ >>> import jax
28
+ >>> import numpyro, numpyro.distributions as dist
29
+ >>> from numpyro.infer import Predictive
30
+ >>> import unxt as u
31
+ >>> from unxts.interop.numpyro import attach_units, unitful
32
+
33
+ >>> def model():
34
+ ... numpyro.sample("m", dist.Normal(u.Q(0.0, "pc"), u.Q(3.0, "pc")))
35
+
36
+ >>> M = unitful(model, u.unitsystems.galactic)
37
+ >>> s = Predictive(M, num_samples=3)(jax.random.PRNGKey(0))
38
+ >>> attach_units(s, M)["m"].unit
39
+ Unit("kpc")
40
+
41
+ """
42
+ units = handler.site_units
43
+ if not handler._ran: # noqa: SLF001
44
+ msg = "The handler has no recorded sites: run the model first."
45
+ raise UnitfulError(msg)
46
+ return {
47
+ k: u.Q(v, units[k]) if units.get(k) is not None and not _is_q(v) else v
48
+ for k, v in samples.items()
49
+ }
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '2.2.0'
22
+ __version_tuple__ = version_tuple = (2, 2, 0)
23
+
24
+ __commit_id__ = commit_id = None
File without changes
@@ -0,0 +1,63 @@
1
+ Metadata-Version: 2.5
2
+ Name: unxts.interop.numpyro
3
+ Version: 2.2.0
4
+ Summary: NumPyro integration for unxt (canonical: unxts.interop.numpyro)
5
+ Project-URL: Bug Tracker, https://github.com/GalacticDynamics/unxt/issues
6
+ Project-URL: Homepage, https://github.com/GalacticDynamics/unxt
7
+ Author-email: GalacticDynamics <nstarman@users.noreply.github.com>, Nathaniel Starkman <nstarman@users.noreply.github.com>
8
+ License-Expression: BSD-3-Clause
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Scientific/Engineering
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Requires-Dist: numpyro>=0.22.0
24
+ Requires-Dist: plum-dispatch>=2.7.0
25
+ Requires-Dist: unxt>=2.1.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # unxts.interop.numpyro
29
+
30
+ NumPyro integration for [unxt](https://github.com/GalacticDynamics/unxt).
31
+
32
+ The `unitful` handler lets NumPyro models take `unxt` quantities. It converts them to plain numbers in a unit system you choose before NumPyro sees them. The model gets its sampled values back as quantities, and `attach_units` puts the units on the posterior samples.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install unxts.interop.numpyro
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ```python
43
+ import jax
44
+ import numpyro
45
+ import numpyro.distributions as dist
46
+ import unxt as u
47
+ from numpyro.infer import MCMC, NUTS
48
+ from unxts.interop.numpyro import attach_units, unitful
49
+
50
+
51
+ def model(x=None):
52
+ m = numpyro.sample("m", dist.Normal(u.Q(0.0, "kpc"), u.Q(3.0, "kpc")))
53
+ s = numpyro.sample("s", dist.HalfNormal(u.Q(1.0, "kpc")))
54
+ with numpyro.plate("n", 200):
55
+ numpyro.sample("x", dist.Normal(m, s), obs=x)
56
+
57
+
58
+ x = u.Q(1.0 + 0.2 * jax.random.normal(jax.random.PRNGKey(1), (200,)), "kpc")
59
+ M = unitful(model, u.unitsystems.galactic)
60
+ mcmc = MCMC(NUTS(M), num_warmup=200, num_samples=200, progress_bar=False)
61
+ mcmc.run(jax.random.PRNGKey(0), x)
62
+ samples = attach_units(mcmc.get_samples(), M) # samples["m"] is a Quantity in kpc
63
+ ```
@@ -0,0 +1,12 @@
1
+ unxts/interop/numpyro/__init__.py,sha256=N31KYQGxl3essP-_KEQSwQ-mzpmbmBD8By6g-7ZFS_0,376
2
+ unxts/interop/numpyro/_version.py,sha256=hr28JFSw-8QN1uunsHJx1LBz0QF7sJ_ntX0tGWncjFk,520
3
+ unxts/interop/numpyro/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ unxts/interop/numpyro/_src/__init__.py,sha256=epZvSPKJv-bt7vVYEdq8YZdOh2jQeNY7rziqCPeFvZE,52
5
+ unxts/interop/numpyro/_src/handler.py,sha256=bDArQeVsjbeJc48R6bWmRPhfGoSwDMxC46pAyQqzsGM,28872
6
+ unxts/interop/numpyro/_src/patches.py,sha256=2NyLH375K4l-joWmcZTfdzi01DoXa8LNPOrFFN01FMs,4006
7
+ unxts/interop/numpyro/_src/rules.py,sha256=0WY3uYyOCk3HLSEyP8kCw_DnmXn8VXbOCh9TfVKmk1s,10472
8
+ unxts/interop/numpyro/_src/samples.py,sha256=MPtPn7LLKUZZ1HkgD-QsGc8ms940mBffJjhk-bk1zyI,1724
9
+ unxts_interop_numpyro-2.2.0.dist-info/METADATA,sha256=Ozf2j417VpJ6Yg209ZLQw4QI0CtMA6xIhXhfX9p9F0U,2354
10
+ unxts_interop_numpyro-2.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ unxts_interop_numpyro-2.2.0.dist-info/licenses/LICENSE,sha256=dZw7glr5UgpWO9a1jlC004HhtLTytJbcQO9pQVMLk7g,1519
12
+ unxts_interop_numpyro-2.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2023, Nathaniel Starkman.
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.