cosmonuts 0.0.1__tar.gz

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.
Files changed (44) hide show
  1. cosmonuts-0.0.1/PKG-INFO +29 -0
  2. cosmonuts-0.0.1/README.md +0 -0
  3. cosmonuts-0.0.1/pyproject.toml +78 -0
  4. cosmonuts-0.0.1/pyproject.toml.orig +55 -0
  5. cosmonuts-0.0.1/src/cosmonuts/__init__.py +60 -0
  6. cosmonuts-0.0.1/src/cosmonuts/_report.py +48 -0
  7. cosmonuts-0.0.1/src/cosmonuts/cli/__init__.py +49 -0
  8. cosmonuts-0.0.1/src/cosmonuts/cli/_console.py +74 -0
  9. cosmonuts-0.0.1/src/cosmonuts/cli/info.py +72 -0
  10. cosmonuts-0.0.1/src/cosmonuts/cli/install.py +61 -0
  11. cosmonuts-0.0.1/src/cosmonuts/cli/maximize.py +45 -0
  12. cosmonuts-0.0.1/src/cosmonuts/cli/plot.py +178 -0
  13. cosmonuts-0.0.1/src/cosmonuts/cli/sample.py +116 -0
  14. cosmonuts-0.0.1/src/cosmonuts/config.py +694 -0
  15. cosmonuts-0.0.1/src/cosmonuts/external.py +150 -0
  16. cosmonuts-0.0.1/src/cosmonuts/installer/__init__.py +71 -0
  17. cosmonuts-0.0.1/src/cosmonuts/installer/download.py +77 -0
  18. cosmonuts-0.0.1/src/cosmonuts/installer/paths.py +41 -0
  19. cosmonuts-0.0.1/src/cosmonuts/installer/registry.py +48 -0
  20. cosmonuts-0.0.1/src/cosmonuts/likelihood.py +242 -0
  21. cosmonuts-0.0.1/src/cosmonuts/likelihoods/__init__.py +20 -0
  22. cosmonuts-0.0.1/src/cosmonuts/likelihoods/des.py +59 -0
  23. cosmonuts-0.0.1/src/cosmonuts/likelihoods/desi.py +394 -0
  24. cosmonuts-0.0.1/src/cosmonuts/likelihoods/planck.py +83 -0
  25. cosmonuts-0.0.1/src/cosmonuts/likelihoods/planck_clik.py +206 -0
  26. cosmonuts-0.0.1/src/cosmonuts/likelihoods/sn.py +313 -0
  27. cosmonuts-0.0.1/src/cosmonuts/model.py +326 -0
  28. cosmonuts-0.0.1/src/cosmonuts/output.py +685 -0
  29. cosmonuts-0.0.1/src/cosmonuts/params.py +160 -0
  30. cosmonuts-0.0.1/src/cosmonuts/plotting.py +145 -0
  31. cosmonuts-0.0.1/src/cosmonuts/primordial.py +88 -0
  32. cosmonuts-0.0.1/src/cosmonuts/registry.py +85 -0
  33. cosmonuts-0.0.1/src/cosmonuts/samplers/__init__.py +16 -0
  34. cosmonuts-0.0.1/src/cosmonuts/samplers/base.py +138 -0
  35. cosmonuts-0.0.1/src/cosmonuts/samplers/hmc.py +80 -0
  36. cosmonuts-0.0.1/src/cosmonuts/samplers/nested.py +195 -0
  37. cosmonuts-0.0.1/src/cosmonuts/samplers/nuts.py +80 -0
  38. cosmonuts-0.0.1/src/cosmonuts/sampling.py +1258 -0
  39. cosmonuts-0.0.1/src/cosmonuts/theories/__init__.py +15 -0
  40. cosmonuts-0.0.1/src/cosmonuts/theories/classe.py +179 -0
  41. cosmonuts-0.0.1/src/cosmonuts/theories/combined.py +185 -0
  42. cosmonuts-0.0.1/src/cosmonuts/theories/eft4py.py +365 -0
  43. cosmonuts-0.0.1/src/cosmonuts/theories/w0wa.py +294 -0
  44. cosmonuts-0.0.1/src/cosmonuts/theory.py +152 -0
@@ -0,0 +1,29 @@
1
+ Metadata-Version: 2.3
2
+ Name: cosmonuts
3
+ Version: 0.0.1
4
+ Summary: Differentiable cosmological inference in JAX: plug-in theories and likelihoods, sampled with BlackJAX
5
+ Author: Rodrigo Calderon
6
+ Author-email: Rodrigo Calderon <calderon.cosmology@gmail.com>
7
+ Requires-Dist: jax>=0.4.30
8
+ Requires-Dist: equinox>=0.11
9
+ Requires-Dist: optax>=0.2.3
10
+ Requires-Dist: blackjax>=1.7.1
11
+ Requires-Dist: numpy>=1.24
12
+ Requires-Dist: typer>=0.12
13
+ Requires-Dist: rich>=13
14
+ Requires-Dist: marimo>=0.25.0
15
+ Requires-Dist: matplotlib>=3.11.2
16
+ Requires-Dist: pyyaml>=6
17
+ Requires-Dist: class-e[jax] ; extra == 'classe'
18
+ Requires-Dist: clipy-like ; extra == 'clipy'
19
+ Requires-Dist: h5py>=3.8 ; extra == 'desi'
20
+ Requires-Dist: eft4py[jax] ; extra == 'eft4py'
21
+ Requires-Dist: jax[cuda12] ; sys_platform == 'linux' and extra == 'gpu'
22
+ Requires-Python: >=3.12
23
+ Provides-Extra: classe
24
+ Provides-Extra: clipy
25
+ Provides-Extra: desi
26
+ Provides-Extra: eft4py
27
+ Provides-Extra: gpu
28
+ Description-Content-Type: text/markdown
29
+
File without changes
@@ -0,0 +1,78 @@
1
+ [project]
2
+ name = "cosmonuts"
3
+ version = "0.0.1"
4
+ description = "Differentiable cosmological inference in JAX: plug-in theories and likelihoods, sampled with BlackJAX"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = [
8
+ "jax>=0.4.30",
9
+ "equinox>=0.11",
10
+ "optax>=0.2.3",
11
+ "blackjax>=1.7.1",
12
+ "numpy>=1.24",
13
+ "typer>=0.12",
14
+ "rich>=13",
15
+ "marimo>=0.25.0",
16
+ "matplotlib>=3.11.2",
17
+ "pyyaml>=6",
18
+ ]
19
+
20
+ [[project.authors]]
21
+ name = "Rodrigo Calderon"
22
+ email = "calderon.cosmology@gmail.com"
23
+
24
+ [project.optional-dependencies]
25
+ eft4py = ["eft4py[jax]"]
26
+ desi = ["h5py>=3.8"]
27
+ classe = ["class-e[jax]"]
28
+ clipy = ["clipy-like"]
29
+ gpu = ["jax[cuda12]; sys_platform == 'linux'"]
30
+
31
+ [project.scripts]
32
+ cosmonuts = "cosmonuts.cli:app"
33
+
34
+ [dependency-groups]
35
+ dev = [
36
+ "pytest>=7.4",
37
+ "ruff>=0.5",
38
+ ]
39
+ plots = [
40
+ "cplots[matplotlib,getdist]",
41
+ "cosmochains",
42
+ ]
43
+
44
+ [tool.uv.sources.eft4py]
45
+ path = "../eft4py"
46
+ editable = true
47
+
48
+ [tool.uv.sources.class-e]
49
+ path = "../../github/class-e"
50
+ editable = true
51
+
52
+ [tool.uv.sources.cplots]
53
+ path = "../../github/cplots"
54
+ editable = true
55
+
56
+ [tool.uv.sources.cosmochains]
57
+ path = "../../github/cosmochains"
58
+ editable = true
59
+
60
+ [tool.pytest.ini_options]
61
+ testpaths = ["tests"]
62
+
63
+ [tool.ruff]
64
+ line-length = 110
65
+
66
+ [tool.ruff.lint]
67
+ select = [
68
+ "E",
69
+ "F",
70
+ "I",
71
+ "B",
72
+ "UP",
73
+ ]
74
+ ignore = ["E501"]
75
+
76
+ [build-system]
77
+ requires = ["uv_build>=0.9.9,<0.10.0"]
78
+ build-backend = "uv_build"
@@ -0,0 +1,55 @@
1
+ [project]
2
+ name = "cosmonuts"
3
+ version = "0.0.1"
4
+ description = "Differentiable cosmological inference in JAX: plug-in theories and likelihoods, sampled with BlackJAX"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Rodrigo Calderon", email = "calderon.cosmology@gmail.com" }
8
+ ]
9
+ requires-python = ">=3.12"
10
+ dependencies = [
11
+ "jax>=0.4.30",
12
+ "equinox>=0.11",
13
+ "optax>=0.2.3",
14
+ "blackjax>=1.7.1",
15
+ "numpy>=1.24",
16
+ "typer>=0.12",
17
+ "rich>=13",
18
+ "marimo>=0.25.0",
19
+ "matplotlib>=3.11.2",
20
+ "pyyaml>=6",
21
+ ]
22
+
23
+ [project.optional-dependencies]
24
+ eft4py = ["eft4py[jax]"]
25
+ desi = ["h5py>=3.8"]
26
+ classe = ["class-e[jax]"] # class-e emulators (ClassETheory)
27
+ clipy = ["clipy-like"] # Planck clik likelihoods in JAX
28
+ gpu = ["jax[cuda12]; sys_platform == 'linux'"] # NVIDIA GPUs (Linux)
29
+
30
+ [project.scripts]
31
+ cosmonuts = "cosmonuts.cli:app"
32
+
33
+ [dependency-groups]
34
+ dev = ["pytest>=7.4", "ruff>=0.5"]
35
+ plots = ["cplots[matplotlib,getdist]", "cosmochains"]
36
+
37
+ [tool.uv.sources]
38
+ eft4py = { path = "../eft4py", editable = true }
39
+ class-e = { path = "../../github/class-e", editable = true }
40
+ cplots = { path = "../../github/cplots", editable = true }
41
+ cosmochains = { path = "../../github/cosmochains", editable = true }
42
+
43
+ [tool.pytest.ini_options]
44
+ testpaths = ["tests"]
45
+
46
+ [build-system]
47
+ requires = ["uv_build>=0.9.9,<0.10.0"]
48
+ build-backend = "uv_build"
49
+
50
+ [tool.ruff]
51
+ line-length = 110
52
+
53
+ [tool.ruff.lint]
54
+ select = ["E", "F", "I", "B", "UP"]
55
+ ignore = ["E501"] # long data file names and URLs
@@ -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
+ ]
@@ -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"]
@@ -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"]
@@ -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"]