cosmonuts 0.0.1__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.
- cosmonuts/__init__.py +60 -0
- cosmonuts/_report.py +48 -0
- cosmonuts/cli/__init__.py +49 -0
- cosmonuts/cli/_console.py +74 -0
- cosmonuts/cli/info.py +72 -0
- cosmonuts/cli/install.py +61 -0
- cosmonuts/cli/maximize.py +45 -0
- cosmonuts/cli/plot.py +178 -0
- cosmonuts/cli/sample.py +116 -0
- cosmonuts/config.py +694 -0
- cosmonuts/external.py +150 -0
- cosmonuts/installer/__init__.py +71 -0
- cosmonuts/installer/download.py +77 -0
- cosmonuts/installer/paths.py +41 -0
- cosmonuts/installer/registry.py +48 -0
- cosmonuts/likelihood.py +242 -0
- cosmonuts/likelihoods/__init__.py +20 -0
- cosmonuts/likelihoods/des.py +59 -0
- cosmonuts/likelihoods/desi.py +394 -0
- cosmonuts/likelihoods/planck.py +83 -0
- cosmonuts/likelihoods/planck_clik.py +206 -0
- cosmonuts/likelihoods/sn.py +313 -0
- cosmonuts/model.py +326 -0
- cosmonuts/output.py +685 -0
- cosmonuts/params.py +160 -0
- cosmonuts/plotting.py +145 -0
- cosmonuts/primordial.py +88 -0
- cosmonuts/registry.py +85 -0
- cosmonuts/samplers/__init__.py +16 -0
- cosmonuts/samplers/base.py +138 -0
- cosmonuts/samplers/hmc.py +80 -0
- cosmonuts/samplers/nested.py +195 -0
- cosmonuts/samplers/nuts.py +80 -0
- cosmonuts/sampling.py +1258 -0
- cosmonuts/theories/__init__.py +15 -0
- cosmonuts/theories/classe.py +179 -0
- cosmonuts/theories/combined.py +185 -0
- cosmonuts/theories/eft4py.py +365 -0
- cosmonuts/theories/w0wa.py +294 -0
- cosmonuts/theory.py +152 -0
- cosmonuts-0.0.1.dist-info/METADATA +29 -0
- cosmonuts-0.0.1.dist-info/RECORD +44 -0
- cosmonuts-0.0.1.dist-info/WHEEL +4 -0
- cosmonuts-0.0.1.dist-info/entry_points.txt +3 -0
cosmonuts/__init__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
r"""cosmonuts: differentiable cosmological inference in JAX.
|
|
2
|
+
|
|
3
|
+
A [`Theory`][cosmonuts.theory.Theory] turns parameters into a provider of
|
|
4
|
+
quantities ($H(z)$, distances, $r_d$, $f(z)$, $P(k, z)$, ...);
|
|
5
|
+
[`Likelihood`][cosmonuts.likelihood.Likelihood]s score the provider; a
|
|
6
|
+
[`Model`][cosmonuts.model.Model] adds priors and exposes one differentiable log
|
|
7
|
+
density, which [`nuts`][cosmonuts.sampling.nuts] samples with BlackJAX (or
|
|
8
|
+
[`nested`][cosmonuts.sampling.nested], for the evidence too; [`sample`][cosmonuts.sampling.sample]
|
|
9
|
+
picks the method and the device, CPU or GPU) and [`maximize`][cosmonuts.sampling.maximize]
|
|
10
|
+
optimises with optax;
|
|
11
|
+
[`save_chains`][cosmonuts.output.save_chains] writes chains GetDist can load. Theories and
|
|
12
|
+
likelihoods are Equinox modules: subclass them to plug in any differentiable
|
|
13
|
+
code or data.
|
|
14
|
+
|
|
15
|
+
Examples:
|
|
16
|
+
```python
|
|
17
|
+
import jax
|
|
18
|
+
jax.config.update("jax_enable_x64", True)
|
|
19
|
+
from cosmonuts import Model, Uniform, Fixed, nuts
|
|
20
|
+
from cosmonuts.theories import W0WaCDM
|
|
21
|
+
from cosmonuts.likelihoods import DESIDR2BAO # cosmonuts install desi_dr2_bao
|
|
22
|
+
|
|
23
|
+
model = Model(W0WaCDM(rdrag="param"), [DESIDR2BAO()], {
|
|
24
|
+
"h": Fixed(0.7), "omega_b": Fixed(0.0224), "omega_cdm": Uniform(0.05, 0.2),
|
|
25
|
+
"w0": Uniform(-2.0, 0.0), "wa": Uniform(-3.0, 2.0), "rdrag": Uniform(120.0, 170.0)})
|
|
26
|
+
result = nuts(model, jax.random.PRNGKey(0))
|
|
27
|
+
```
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from .likelihood import DataNotFoundError, GaussianLikelihood, Likelihood
|
|
31
|
+
from .model import Model
|
|
32
|
+
from .output import save_chains
|
|
33
|
+
from .params import Defined, Fixed, Normal, Prior, Uniform
|
|
34
|
+
from .sampling import HMCResult, MaximizeResult, NestedResult, NUTSResult, hmc, maximize, nested, nuts, sample
|
|
35
|
+
from .theory import QUANTITIES, Provider, Theory
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"QUANTITIES",
|
|
39
|
+
"DataNotFoundError",
|
|
40
|
+
"Defined",
|
|
41
|
+
"Fixed",
|
|
42
|
+
"GaussianLikelihood",
|
|
43
|
+
"Likelihood",
|
|
44
|
+
"HMCResult",
|
|
45
|
+
"MaximizeResult",
|
|
46
|
+
"Model",
|
|
47
|
+
"NestedResult",
|
|
48
|
+
"NUTSResult",
|
|
49
|
+
"Normal",
|
|
50
|
+
"Prior",
|
|
51
|
+
"Provider",
|
|
52
|
+
"Theory",
|
|
53
|
+
"Uniform",
|
|
54
|
+
"hmc",
|
|
55
|
+
"maximize",
|
|
56
|
+
"nested",
|
|
57
|
+
"nuts",
|
|
58
|
+
"sample",
|
|
59
|
+
"save_chains",
|
|
60
|
+
]
|
cosmonuts/_report.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Host-side progress callbacks that compiled code can reach without capturing them.
|
|
2
|
+
|
|
3
|
+
A compiled function that called a run's reporter directly would hold that reporter as a
|
|
4
|
+
constant: it would have to be recompiled for every run, or keep calling the first run's.
|
|
5
|
+
Compiled code instead calls `dispatch` with a fixed slot name, and each run puts its reporter
|
|
6
|
+
in that slot for as long as it runs (`reporting`).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from collections.abc import Callable, Iterator
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from functools import partial
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import jax
|
|
15
|
+
|
|
16
|
+
_ACTIVE: dict[str, Callable] = {}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def dispatch(slot: str, *args: Any) -> None:
|
|
20
|
+
"""Forward `args` to the reporter in `slot`, if any."""
|
|
21
|
+
report = _ACTIVE.get(slot)
|
|
22
|
+
if report is not None:
|
|
23
|
+
report(*args)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def callback(slot: str) -> Callable:
|
|
27
|
+
"""What compiled code passes to `jax.debug.callback`: `dispatch` bound to `slot`."""
|
|
28
|
+
return partial(dispatch, slot)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@contextmanager
|
|
32
|
+
def reporting(**reporters: Callable | None) -> Iterator[None]:
|
|
33
|
+
"""Put each reporter in its slot (`slot=reporter`; `None` leaves a slot empty) for the block.
|
|
34
|
+
|
|
35
|
+
On exit it waits for the callbacks still queued (they run asynchronously), so that none
|
|
36
|
+
reaches the slot after its reporter has left.
|
|
37
|
+
"""
|
|
38
|
+
previous = {slot: _ACTIVE.get(slot) for slot in reporters}
|
|
39
|
+
_ACTIVE.update({slot: r for slot, r in reporters.items() if r is not None})
|
|
40
|
+
try:
|
|
41
|
+
yield
|
|
42
|
+
finally:
|
|
43
|
+
jax.effects_barrier()
|
|
44
|
+
for slot, r in previous.items():
|
|
45
|
+
if r is None:
|
|
46
|
+
_ACTIVE.pop(slot, None)
|
|
47
|
+
else:
|
|
48
|
+
_ACTIVE[slot] = r
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""The `cosmonuts` command line.
|
|
2
|
+
|
|
3
|
+
One typer app per command module, composed here. A sub-app added without a name has its
|
|
4
|
+
commands merged into the root (`cosmonuts install`, `cosmonuts sample`); with a name it is a
|
|
5
|
+
group (`cosmonuts info theories`).
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
9
|
+
from typing import Annotated
|
|
10
|
+
|
|
11
|
+
import typer
|
|
12
|
+
|
|
13
|
+
from . import info, install, maximize, plot, sample
|
|
14
|
+
from ._console import console
|
|
15
|
+
|
|
16
|
+
app = typer.Typer(
|
|
17
|
+
name="cosmonuts",
|
|
18
|
+
no_args_is_help=True,
|
|
19
|
+
add_completion=False,
|
|
20
|
+
rich_markup_mode="rich",
|
|
21
|
+
pretty_exceptions_enable=False,
|
|
22
|
+
)
|
|
23
|
+
app.add_typer(install.app)
|
|
24
|
+
app.add_typer(sample.app)
|
|
25
|
+
app.add_typer(maximize.app)
|
|
26
|
+
app.add_typer(plot.app, name="plot", help="Triangle plots, traces and constraints of saved chains "
|
|
27
|
+
"(needs `uv run --group plots`).")
|
|
28
|
+
app.add_typer(info.app, name="info", help="What a run file can name and set: theories, likelihoods, samplers.")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _version(value: bool) -> None:
|
|
32
|
+
if value:
|
|
33
|
+
try:
|
|
34
|
+
console.print(f"cosmonuts {version('cosmonuts')}")
|
|
35
|
+
except PackageNotFoundError:
|
|
36
|
+
console.print("cosmonuts (not installed)")
|
|
37
|
+
raise typer.Exit()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@app.callback()
|
|
41
|
+
def main(
|
|
42
|
+
_: Annotated[bool, typer.Option("--version", "-V", callback=_version, is_eager=True,
|
|
43
|
+
help="Show the version and exit.")] = False,
|
|
44
|
+
) -> None:
|
|
45
|
+
"""Differentiable cosmological inference in JAX: install likelihood data, then sample and fit models
|
|
46
|
+
described by YAML run files."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
__all__ = ["app"]
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Shared output of the command line: rich consoles, error panels and tables."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
from collections.abc import Iterator, Mapping
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
from rich.markup import escape
|
|
10
|
+
from rich.panel import Panel
|
|
11
|
+
from rich.table import Table
|
|
12
|
+
|
|
13
|
+
console = Console()
|
|
14
|
+
err_console = Console(stderr=True)
|
|
15
|
+
|
|
16
|
+
_EXPECTED = (ValueError, TypeError, ImportError, KeyError, AttributeError, RuntimeError, OSError)
|
|
17
|
+
"""Errors shown as a short panel (a bad run file, missing data, existing chains, ...)."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@contextlib.contextmanager
|
|
21
|
+
def reporting_errors(debug: bool = False) -> Iterator[None]:
|
|
22
|
+
"""Show expected errors as a red panel and exit with status 1; with `debug`, raise them."""
|
|
23
|
+
try:
|
|
24
|
+
yield
|
|
25
|
+
except (typer.Exit, typer.Abort): # RuntimeErrors too, but typer's own control flow
|
|
26
|
+
raise
|
|
27
|
+
except _EXPECTED as e:
|
|
28
|
+
if debug:
|
|
29
|
+
raise
|
|
30
|
+
message = e.args[0] if isinstance(e, KeyError) and e.args else str(e)
|
|
31
|
+
err_console.print(Panel(escape(str(message)), title=type(e).__name__, title_align="left",
|
|
32
|
+
border_style="red"))
|
|
33
|
+
err_console.print("[dim]Run again with --debug for the traceback.[/]")
|
|
34
|
+
raise typer.Exit(1) from None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def model_table(model: Any, title: str) -> Table:
|
|
38
|
+
"""The theory, likelihoods and parameters of a model."""
|
|
39
|
+
table = Table(title=title, title_justify="left", show_header=False, box=None, pad_edge=False)
|
|
40
|
+
table.add_column(style="bold")
|
|
41
|
+
table.add_column()
|
|
42
|
+
from ..output import _likelihood_names
|
|
43
|
+
|
|
44
|
+
theory = model.theory
|
|
45
|
+
table.add_row("theory", getattr(theory, "name", None) or type(theory).__name__)
|
|
46
|
+
table.add_row("likelihoods", ", ".join(_likelihood_names(model)))
|
|
47
|
+
for kind in ("sampled", "fixed", "defined"):
|
|
48
|
+
names = getattr(model, kind)
|
|
49
|
+
if names:
|
|
50
|
+
table.add_row(kind, ", ".join(names))
|
|
51
|
+
return table
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def settings_table(settings: Mapping[str, Any], title: str) -> Table:
|
|
55
|
+
"""Key-value settings, `None` ones left out."""
|
|
56
|
+
table = Table(title=title, title_justify="left", show_header=False, box=None, pad_edge=False)
|
|
57
|
+
table.add_column(style="bold")
|
|
58
|
+
table.add_column()
|
|
59
|
+
for key, value in settings.items():
|
|
60
|
+
if value is not None:
|
|
61
|
+
table.add_row(key, escape(str(value)))
|
|
62
|
+
return table
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def values_table(values: Mapping[str, float], columns: tuple[str, str], title: str | None = None) -> Table:
|
|
66
|
+
"""A two-column table of named numbers."""
|
|
67
|
+
table = Table(*columns, title=title, title_justify="left")
|
|
68
|
+
table.columns[1].justify = "right"
|
|
69
|
+
for name, value in values.items():
|
|
70
|
+
table.add_row(escape(name), f"{value:.6g}")
|
|
71
|
+
return table
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
__all__ = ["console", "err_console", "model_table", "reporting_errors", "settings_table", "values_table"]
|
cosmonuts/cli/info.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""`cosmonuts info`: what a run file can name (theories, likelihoods) and set (sampler options)."""
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
from rich.markup import escape
|
|
8
|
+
from rich.table import Table
|
|
9
|
+
|
|
10
|
+
from .. import registry
|
|
11
|
+
from ..installer import REGISTRY
|
|
12
|
+
from ._console import console
|
|
13
|
+
|
|
14
|
+
app = typer.Typer(no_args_is_help=True)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _summary(target: str) -> str:
|
|
18
|
+
"""First line of the docstring of the object at `target`, or why it cannot be imported."""
|
|
19
|
+
try:
|
|
20
|
+
obj = registry.load_object(target)
|
|
21
|
+
except Exception as e: # noqa: BLE001 - e.g. an optional dependency (eft4py) not installed
|
|
22
|
+
return f"[yellow]unavailable: {escape(str(e).splitlines()[0])}[/]"
|
|
23
|
+
return escape((inspect.getdoc(obj) or "").split("\n")[0])
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _names(kind: registry.Kind, title: str, extra: dict[str, str] | None = None) -> None:
|
|
27
|
+
table = Table("name", *(extra and ["dataset"] or []), "description", title=title, title_justify="left")
|
|
28
|
+
for name, target in registry.available(kind).items():
|
|
29
|
+
cells = [f"[bold]{name}[/]", *([extra.get(name, "")] if extra else []), _summary(target)]
|
|
30
|
+
table.add_row(*cells)
|
|
31
|
+
console.print(table)
|
|
32
|
+
console.print("[dim]Your own: give the import path, module:Class (or a factory function), as the key "
|
|
33
|
+
"or as `module:`.[/]")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@app.command("theories")
|
|
37
|
+
def theories() -> None:
|
|
38
|
+
"""The bundled theories, for a run file's theory block."""
|
|
39
|
+
_names("theory", "Theories")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@app.command("likelihoods")
|
|
43
|
+
def likelihoods() -> None:
|
|
44
|
+
"""The bundled likelihoods, with the dataset `cosmonuts install` downloads for each."""
|
|
45
|
+
datasets = {target.rpartition(":")[2]: name for name, targets in REGISTRY.items() for target in targets}
|
|
46
|
+
_names("likelihood", "Likelihoods", datasets)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _default(param: inspect.Parameter) -> str:
|
|
50
|
+
return "required" if param.default is inspect.Parameter.empty else escape(repr(param.default))
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@app.command("samplers")
|
|
54
|
+
def samplers() -> None:
|
|
55
|
+
"""The samplers of a run file's sampler block and the maximize block, with their options."""
|
|
56
|
+
from ..config import _RESERVED
|
|
57
|
+
from ..sampling import maximize, options
|
|
58
|
+
|
|
59
|
+
blocks: dict[str, Any] = {f"sampler.{m}": options(m) for m in ("nuts", "hmc", "nested")}
|
|
60
|
+
blocks["maximize"] = {n: p for n, p in inspect.signature(maximize).parameters.items()
|
|
61
|
+
if n not in ("model", "initial", "key", "progress")}
|
|
62
|
+
for title, params in blocks.items():
|
|
63
|
+
table = Table("option", "default", title=title, title_justify="left")
|
|
64
|
+
for name, param in params.items():
|
|
65
|
+
if name not in _RESERVED:
|
|
66
|
+
table.add_row(name, _default(param))
|
|
67
|
+
console.print(table)
|
|
68
|
+
console.print("[dim]output, resume, force (overwrite), seed and device are top-level keys of the run "
|
|
69
|
+
"file; initial comes from the params' ref.[/]")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
__all__ = ["app"]
|
cosmonuts/cli/install.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""`cosmonuts install`: download likelihood data into the packages path."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Annotated
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
from rich.markup import escape
|
|
8
|
+
|
|
9
|
+
from ..installer import REGISTRY, is_installed, packages_path
|
|
10
|
+
from ..installer import install as install_dataset
|
|
11
|
+
from ._console import console, reporting_errors
|
|
12
|
+
|
|
13
|
+
app = typer.Typer()
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _status_epilog() -> str:
|
|
17
|
+
"""The packages path and each dataset's status, for `cosmonuts install --help`.
|
|
18
|
+
|
|
19
|
+
Built when the command line starts (typer's help text is static), so checking a dataset
|
|
20
|
+
imports its likelihood classes. Paragraphs are separated by blank lines, as typer's rich
|
|
21
|
+
help joins single line breaks.
|
|
22
|
+
"""
|
|
23
|
+
lines = [f"[bold]Packages path[/]: {escape(str(packages_path()))} "
|
|
24
|
+
"(set by --path or $COSMONUTS_PACKAGES_PATH)", "[bold]Datasets[/]:"]
|
|
25
|
+
for name in sorted(REGISTRY):
|
|
26
|
+
users = ", ".join(target.rpartition(":")[2] for target in REGISTRY[name])
|
|
27
|
+
try:
|
|
28
|
+
mark = "[green]✓ installed[/]" if is_installed(name) else "[red]✗ missing[/]"
|
|
29
|
+
except Exception as e: # noqa: BLE001 - an optional dependency missing must not break --help
|
|
30
|
+
mark = f"[yellow]? {escape(type(e).__name__)}[/]"
|
|
31
|
+
lines.append(f" {mark} [bold]{name}[/] [dim]({escape(users)})[/]")
|
|
32
|
+
return "\n\n".join(lines)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@app.command("install", epilog=_status_epilog(), no_args_is_help=True)
|
|
36
|
+
def install(
|
|
37
|
+
names: Annotated[list[str] | None, typer.Argument(help="Datasets to install (listed below).",
|
|
38
|
+
show_default=False)] = None,
|
|
39
|
+
all_: Annotated[bool, typer.Option("--all", help="Install every bundled dataset.")] = False,
|
|
40
|
+
path: Annotated[Path | None, typer.Option("--path", "-p", help="Packages path (default: "
|
|
41
|
+
"$COSMONUTS_PACKAGES_PATH or the user data directory).",
|
|
42
|
+
show_default=False)] = None,
|
|
43
|
+
force: Annotated[bool, typer.Option("--force", "-f", help="Download again.")] = False,
|
|
44
|
+
debug: Annotated[bool, typer.Option("--debug", "-d", help="Show tracebacks.")] = False,
|
|
45
|
+
) -> None:
|
|
46
|
+
"""Download likelihood data into the packages path."""
|
|
47
|
+
selected = sorted(REGISTRY) if all_ else (names or [])
|
|
48
|
+
if not selected:
|
|
49
|
+
raise typer.BadParameter("give dataset names or --all (see cosmonuts install --help).")
|
|
50
|
+
unknown = [n for n in selected if n not in REGISTRY]
|
|
51
|
+
if unknown:
|
|
52
|
+
raise typer.BadParameter(f"Unknown {unknown}; choose from {sorted(REGISTRY)}.")
|
|
53
|
+
with reporting_errors(debug):
|
|
54
|
+
for name in selected:
|
|
55
|
+
with console.status(f"Installing [bold]{name}[/]..."):
|
|
56
|
+
directory = install_dataset(name, path, force=force,
|
|
57
|
+
log=lambda m: console.print(f" [dim]{escape(m)}[/]"))
|
|
58
|
+
console.print(f"[green]✓[/] [bold]{name}[/] in {escape(str(directory))}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
__all__ = ["app"]
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""`cosmonuts maximize run.yaml`: the best fit of the model a run file describes."""
|
|
2
|
+
|
|
3
|
+
from typing import Annotated
|
|
4
|
+
|
|
5
|
+
import typer
|
|
6
|
+
from rich.markup import escape
|
|
7
|
+
|
|
8
|
+
from .. import config
|
|
9
|
+
from ._console import console, model_table, reporting_errors, settings_table, values_table
|
|
10
|
+
from .sample import Debug, Device, Force, Output, Progress, RunArgs, Seed, split_args
|
|
11
|
+
|
|
12
|
+
app = typer.Typer()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@app.command("maximize", no_args_is_help=True)
|
|
16
|
+
def maximize(
|
|
17
|
+
args: RunArgs,
|
|
18
|
+
output: Output = None,
|
|
19
|
+
force: Force = False,
|
|
20
|
+
seed: Seed = None,
|
|
21
|
+
device: Device = None,
|
|
22
|
+
ignore_prior: Annotated[bool, typer.Option("--ignore-prior", help="Maximise the likelihood only.")] = False,
|
|
23
|
+
progress: Progress = True,
|
|
24
|
+
debug: Debug = False,
|
|
25
|
+
) -> None:
|
|
26
|
+
"""Best fit (MAP, or maximum likelihood) by L-BFGS, with the run file's maximize options.
|
|
27
|
+
|
|
28
|
+
Writes OUTPUT.bestfit.yaml when the run file or --output gives an output root.
|
|
29
|
+
"""
|
|
30
|
+
files, overrides = split_args(args, output=output, force=force, seed=seed, device=device)
|
|
31
|
+
if ignore_prior:
|
|
32
|
+
overrides.append("maximize.ignore_prior=true")
|
|
33
|
+
with reporting_errors(debug):
|
|
34
|
+
info = config.load_info(*files, overrides=overrides)
|
|
35
|
+
with console.status("Building the model..."):
|
|
36
|
+
model = config.build_model(info)
|
|
37
|
+
console.print(model_table(model, "Model"))
|
|
38
|
+
result, path = config.maximize_model(model, info, progress=progress)
|
|
39
|
+
console.print(values_table(result.params, ("parameter", "best fit"), "Best fit"))
|
|
40
|
+
console.print(settings_table({"objective": f"{result.value:.6g}", "chi2": f"{result.chi2:.6g}",
|
|
41
|
+
"converged": result.converged,
|
|
42
|
+
"written": None if path is None else escape(str(path))}, "Summary"))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
__all__ = ["app"]
|
cosmonuts/cli/plot.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""`cosmonuts plot`: triangle plots, traces and marginalised constraints of saved chains."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Annotated, Any
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
from rich.markup import escape
|
|
8
|
+
from rich.table import Table
|
|
9
|
+
|
|
10
|
+
from ._console import console, reporting_errors
|
|
11
|
+
|
|
12
|
+
app = typer.Typer(no_args_is_help=True)
|
|
13
|
+
|
|
14
|
+
Runs = Annotated[list[str], typer.Argument(
|
|
15
|
+
metavar="RUN...", show_default=False,
|
|
16
|
+
help="Runs: chains' path roots (chains/w0wa), chain files, or the run files (.yaml) that wrote them.")]
|
|
17
|
+
Labels = Annotated[list[str] | None, typer.Option(
|
|
18
|
+
"--label", "-l", show_default=False, help="Name of each run, in order (default: its root's name).")]
|
|
19
|
+
Params = Annotated[list[str] | None, typer.Option(
|
|
20
|
+
"--params", "-p", show_default=False,
|
|
21
|
+
help="Parameters: names or globs (omega_*), comma-separated or repeated (default: the first run's "
|
|
22
|
+
"sampled ones).")]
|
|
23
|
+
Derived = Annotated[bool, typer.Option("--derived", help="With no --params, include derived parameters.")]
|
|
24
|
+
BurnIn = Annotated[float, typer.Option("--burn-in", min=0.0, max=0.99,
|
|
25
|
+
help="Fraction of each chain to drop (none needed for NUTS).")]
|
|
26
|
+
Out = Annotated[str | None, typer.Option("--out", "-o", show_default=False,
|
|
27
|
+
help="Figure path, without extension (default: next to the first run).")]
|
|
28
|
+
Formats = Annotated[str, typer.Option("--format", "-f", help="Comma-separated file formats.")]
|
|
29
|
+
Show = Annotated[bool, typer.Option("--show", help="Also open the figure in a window.")]
|
|
30
|
+
Debug = Annotated[bool, typer.Option("--debug", "-d", help="Show tracebacks.")]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _truth(text: str) -> tuple[str, float]:
|
|
34
|
+
name, sep, value = text.partition("=")
|
|
35
|
+
try:
|
|
36
|
+
if not sep or not name:
|
|
37
|
+
raise ValueError
|
|
38
|
+
return name.strip(), float(value)
|
|
39
|
+
except ValueError:
|
|
40
|
+
raise typer.BadParameter(f"expected NAME=VALUE, got {text!r}.") from None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _load(runs: list[str], labels: list[str] | None, burn_in: float) -> dict[str, Any]:
|
|
44
|
+
from ..plotting import load_run, run_root
|
|
45
|
+
|
|
46
|
+
if labels and len(labels) != len(runs):
|
|
47
|
+
raise typer.BadParameter(f"got {len(labels)} --label for {len(runs)} runs.")
|
|
48
|
+
names = labels or [run_root(r).name for r in runs]
|
|
49
|
+
if len(set(names)) != len(names):
|
|
50
|
+
raise typer.BadParameter(f"runs need distinct names, got {names}; give them with --label.")
|
|
51
|
+
loaded = {}
|
|
52
|
+
with console.status("Reading chains..."):
|
|
53
|
+
for name, source in zip(names, runs, strict=True):
|
|
54
|
+
loaded[name] = load_run(source, burn_in=burn_in)
|
|
55
|
+
return loaded
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _stats_table(runs: dict[str, Any], params: list[str], *, limits: bool = False) -> Table:
|
|
59
|
+
from ..plotting import _require
|
|
60
|
+
|
|
61
|
+
marginal_stats = _require("cosmochains").marginal_stats
|
|
62
|
+
table = Table("parameter", *runs, title="Marginalised constraints (mean ± std)", title_justify="left")
|
|
63
|
+
stats = {name: marginal_stats(run, [p for p in params if p in run.parameter_names])
|
|
64
|
+
for name, run in runs.items()}
|
|
65
|
+
for p in params:
|
|
66
|
+
cells = []
|
|
67
|
+
for name in runs:
|
|
68
|
+
s = stats[name].get(p)
|
|
69
|
+
if s is None:
|
|
70
|
+
cells.append("[dim]—[/]")
|
|
71
|
+
continue
|
|
72
|
+
cell = f"{s.mean:.5g} ± {s.std:.2g}"
|
|
73
|
+
if limits:
|
|
74
|
+
cell += (f"\n[dim]68%: [{s.lower68:.5g}, {s.upper68:.5g}]\n"
|
|
75
|
+
f"95%: [{s.lower95:.5g}, {s.upper95:.5g}]\nbest: {s.best:.5g}[/]")
|
|
76
|
+
cells.append(cell)
|
|
77
|
+
table.add_row(escape(p), *cells)
|
|
78
|
+
if not limits:
|
|
79
|
+
table.caption = "--limits adds the 68%/95% intervals and the best sample."
|
|
80
|
+
return table
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _output(out: str | None, runs: list[str], suffix: str) -> str:
|
|
84
|
+
from ..plotting import run_root
|
|
85
|
+
|
|
86
|
+
return out or f"{run_root(runs[0])}_{suffix}"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _save(figure: Any, out: str, formats: str, show: bool) -> None:
|
|
90
|
+
from ..plotting import save
|
|
91
|
+
|
|
92
|
+
paths = save(figure, out, [f.strip() for f in formats.split(",") if f.strip()])
|
|
93
|
+
console.print("[green]✓[/] wrote " + ", ".join(escape(str(p)) for p in paths))
|
|
94
|
+
if show:
|
|
95
|
+
figure.show()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@app.command("triangle", no_args_is_help=True)
|
|
99
|
+
def triangle(
|
|
100
|
+
runs: Runs,
|
|
101
|
+
label: Labels = None,
|
|
102
|
+
params: Params = None,
|
|
103
|
+
derived: Derived = False,
|
|
104
|
+
truth: Annotated[list[str] | None, typer.Option(
|
|
105
|
+
"--truth", "-t", show_default=False, help="Reference value NAME=VALUE to mark; repeatable.")] = None,
|
|
106
|
+
truths_from: Annotated[Path | None, typer.Option(
|
|
107
|
+
"--truths-from", show_default=False, help="Mark the best fit a `cosmonuts maximize` wrote "
|
|
108
|
+
"(OUTPUT.bestfit.yaml).")] = None,
|
|
109
|
+
burn_in: BurnIn = 0.0,
|
|
110
|
+
out: Out = None,
|
|
111
|
+
formats: Formats = "png,pdf",
|
|
112
|
+
title: Annotated[str, typer.Option("--title", help="Figure title.")] = "",
|
|
113
|
+
paper: Annotated[str | None, typer.Option("--paper", show_default=False,
|
|
114
|
+
help="Journal sizing: PRD, PRD-2col, MNRAS or A4.")] = None,
|
|
115
|
+
engine: Annotated[str, typer.Option("--engine", help="cplots triangle engine.")] = "getdist",
|
|
116
|
+
stats: Annotated[bool, typer.Option("--stats/--no-stats", help="Print the constraints.")] = True,
|
|
117
|
+
show: Show = False,
|
|
118
|
+
debug: Debug = False,
|
|
119
|
+
) -> None:
|
|
120
|
+
"""Triangle plot of one or more runs, overlaid; a run lacking a parameter skips its panels."""
|
|
121
|
+
from .. import plotting
|
|
122
|
+
|
|
123
|
+
marks = dict(_truth(t) for t in truth or [])
|
|
124
|
+
with reporting_errors(debug):
|
|
125
|
+
if truths_from is not None:
|
|
126
|
+
marks = {**plotting.truths_from(truths_from), **marks}
|
|
127
|
+
loaded = _load(runs, label, burn_in)
|
|
128
|
+
names = plotting.select_params(list(loaded.values()), params, derived=derived)
|
|
129
|
+
if stats:
|
|
130
|
+
console.print(_stats_table(loaded, names))
|
|
131
|
+
figure = plotting.triangle(loaded, names, truths={k: v for k, v in marks.items() if k in names},
|
|
132
|
+
title=title, paper=paper, engine=engine)
|
|
133
|
+
_save(figure, _output(out, runs, "triangle"), formats, show)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@app.command("trace", no_args_is_help=True)
|
|
137
|
+
def trace(
|
|
138
|
+
run: Annotated[str, typer.Argument(metavar="RUN", show_default=False,
|
|
139
|
+
help="A run: chains' path root, chain file or run file.")],
|
|
140
|
+
params: Params = None,
|
|
141
|
+
derived: Derived = False,
|
|
142
|
+
burn_in: BurnIn = 0.0,
|
|
143
|
+
out: Out = None,
|
|
144
|
+
formats: Formats = "png,pdf",
|
|
145
|
+
show: Show = False,
|
|
146
|
+
debug: Debug = False,
|
|
147
|
+
) -> None:
|
|
148
|
+
"""Each parameter against draw number, one line per chain: mixing and warm-up at a glance."""
|
|
149
|
+
from .. import plotting
|
|
150
|
+
|
|
151
|
+
with reporting_errors(debug):
|
|
152
|
+
loaded = _load([run], None, burn_in)
|
|
153
|
+
chain = next(iter(loaded.values()))
|
|
154
|
+
names = plotting.select_params([chain], params, derived=derived)
|
|
155
|
+
console.print(f"{len(chain.parts())} chain(s), {len(chain.weights)} draws in all.")
|
|
156
|
+
_save(plotting.trace(chain, names), _output(out, [run], "trace"), formats, show)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@app.command("stats", no_args_is_help=True)
|
|
160
|
+
def stats(
|
|
161
|
+
runs: Runs,
|
|
162
|
+
label: Labels = None,
|
|
163
|
+
params: Params = None,
|
|
164
|
+
derived: Derived = False,
|
|
165
|
+
burn_in: BurnIn = 0.0,
|
|
166
|
+
limits: Annotated[bool, typer.Option("--limits", help="Add the 68%/95% intervals and the best sample.")] = False,
|
|
167
|
+
debug: Debug = False,
|
|
168
|
+
) -> None:
|
|
169
|
+
"""Marginalised constraints of one or more runs, side by side; no figure."""
|
|
170
|
+
from .. import plotting
|
|
171
|
+
|
|
172
|
+
with reporting_errors(debug):
|
|
173
|
+
loaded = _load(runs, label, burn_in)
|
|
174
|
+
names = plotting.select_params(list(loaded.values()), params, derived=derived)
|
|
175
|
+
console.print(_stats_table(loaded, names, limits=limits))
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
__all__ = ["app"]
|