Metadata-Version: 2.4
Name: morph-jax
Version: 0.1.0
Summary: Morph probability density approximation and sampling with JAX
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: jax>=0.4.35
Requires-Dist: numpy>=1.24
Requires-Dist: tqdm>=4.66
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Requires-Dist: scipy>=1.11; extra == "test"
Requires-Dist: ruff>=0.8; extra == "test"
Provides-Extra: benchmark
Requires-Dist: scipy>=1.11; extra == "benchmark"
Requires-Dist: matplotlib>=3.8; extra == "benchmark"
Requires-Dist: corner>=2.2; extra == "benchmark"
Provides-Extra: cuda
Requires-Dist: jax[cuda12]==0.4.35; sys_platform == "linux" and extra == "cuda"
Requires-Dist: nvidia-cudnn-cu12==9.1.1.17; sys_platform == "linux" and extra == "cuda"

# Morph-JAX

Morph-JAX fits a normalized probability density to samples. Use it to evaluate
log densities and their gradients with JAX or generate independent draws from
the fitted approximation.

Morph represents the joint density as a product of kernel density estimates
over disjoint blocks of parameters. It selects blocks using estimates of total
correlation and Seeded Greedy Maximization (SGM). The method follows
[Zahraoui et al., Phys. Rev. D 113, 083014 (2026)](https://doi.org/10.1103/1554-y6ns).

## Installation

Morph-JAX requires Python 3.10 or newer. Install from this checkout with:

```bash
python -m pip install .
```

When the PyPI release is available, install it with `python -m pip install morph-jax`.

The default JAX installation uses CPU. For accelerators, install the appropriate
JAX build using the [official installation guide](https://docs.jax.dev/en/latest/installation.html).
For Linux environments managed with uv, see the
[CPU and CUDA setup guide](docs/local-setup.md).

## Density approximation

Input arrays use rows for draws: `(n_samples, n_parameters)`.

```python
import jax
import jax.numpy as jnp

from morph_jax import fit, log_prob, sample

training_draws = jax.random.multivariate_normal(
    jax.random.key(0),
    jnp.zeros(2),
    jnp.array([[1.0, 0.8], [0.8, 1.0]]),
    shape=(500,),
)
fitted = fit(training_draws, order=2)
state = fitted.state
draws = sample(jax.random.key(1), state, n=1000)
log_densities = log_prob(state, draws)
gradient = jax.grad(lambda point: log_prob(state, point))(draws[0])
print(state.blocks)
print(fitted.diagnostics.retained_total_correlation)
```

`fit(samples, weights=...)` accepts nonnegative weights. Silverman's bandwidth
is the default. `order=2` fits pairs and any residual singleton; `order=1` fits
independent marginals. Factors must have fewer than ten dimensions. All candidate
blocks are enumerated and scored without a candidate-count limit.
SGM is a heuristic, not an exact matching algorithm.
It tries five seeds by default. Set `n_seeds` to override the count, or
`n_seeds=None` to try every candidate.
`sgm_early_stop=True` enables an equivalent early-exit scan; benchmark it on your
device before enabling it, since it is not consistently faster across JAX versions.

For cheaper block scoring, explicitly set `max_tc_samples=256` and provide a
`key`. This uses a reproducible subset for total correlation only; the selected
KDE factors still use all fitting samples. It can change the selected partition.

Set `candidate_progress_every=100` to show a live `tqdm` bar while scoring
candidates, including completion counts, elapsed time, and scoring rate.

## Bayesian evidence estimation with MorphZ

Morph-JAX also includes a MorphZ workflow for estimating marginal likelihoods
from posterior draws. It fits a Morph density on one subset of the chain and
uses draws from that density as proposals for bridge sampling on a held-out
subset. Enable 64-bit precision before constructing the arrays used for evidence
estimation.

```python
import jax

from morph_jax import estimate_evidence

jax.config.update("jax_enable_x64", True)


def log_density(theta):
    return log_likelihood(theta) + log_prior(theta)


result = estimate_evidence(
    posterior_samples,
    log_density,
    jax.random.key(2),
    order=2,
    n_proposal=2000,
)
print(result.bridge.log_evidence)
print(result.bridge.relative_error)
print(result.bridge.converged)
```

The [Gaussian evidence example](examples/gaussian_evidence.py) checks the estimate
against an analytical result.

The callback must be JAX-compatible, return a scalar, and include all likelihood
and proper-prior normalization constants. This workflow requires equal-weight
posterior draws. It splits consecutive rows into disjoint fitting and bridge
batches. It estimates autocorrelation from the ordered held-out bridge sequence;
use `posterior_iat=1` for independent draws. For multiple chains, supply a suitable
IAT explicitly rather than treating a concatenated array as one chain.

Provide `posterior_log_density` with one cached value per original row to reduce
additional target evaluations to the number of proposal draws. Bounded-prior
proposals outside the support must return `-inf`; those draws are retained.

For non-JAX likelihoods, evaluate densities externally and call `bridge_sampling`
with the four log-density vectors. See [the numerical method](docs/method.md).

Both APIs default to `geometric_restart=True`: after every 1,000 unconverged
bridge updates, restart at the midpoint of the last two log-Z values (their
geometric mean on the Z scale). Set `restart_interval=N` (at least 2) to change
the cycle length, or `geometric_restart=False` to recover standard uninterrupted
bridge iteration. `max_iterations` remains a total cap across all cycles.
The final averaging window uses only updates since the latest restart.
This repeats the restart remedy of
[Gronau, Heathcote and Matzke (2020)](https://doi.org/10.3758/s13428-019-01290-6);
the bridge equation and convergence tolerance are unchanged.

## Validation and implementation records

```bash
python -m pip install -e '.[test,benchmark]'
pytest -q
ruff check .
ruff format --check .
python examples/gaussian_evidence.py
python benchmarks/sgm.py --dimension 50 --seeds 128
```

- [Method and equations](docs/method.md): mathematical conventions and scope.
- [JAX execution enhancements](docs/jax-optimizations.md): changes, compatibility, and measurements.
- [Implementation record](docs/implementation.md): modules, optimizations, deviations,
  diagnostics, and limitations.
- [Validation record](docs/validation.md): checks and execution results.
- [Changelog](CHANGELOG.md): versioned changes.

## Research benchmarks

- [Block recovery and density accuracy](docs/block-benchmarks.md)
- [CPU and GPU total-correlation benchmarks](docs/tc-benchmark.md)
- [NANOGrav evidence with IRN, CURN, and HD models](docs/nanograv-evidence.md)
- [NANOGrav flow comparisons](docs/nanograv-flow-comparison.md)

Benchmark scripts save generated results and plots under `benchmark-results/`.
