"""Tests for bimodal.py. Run: python -m pytest -q""" import numpy as np import pytest from bimodal import fit_mixture, fit_mse, gap_fraction, make_data @pytest.fixture(scope="module") def data() -> tuple[np.ndarray, np.ndarray]: return make_data(n=400, noise=0.05, seed=0) def test_no_demonstration_goes_through_the_middle(data) -> None: _, y = data assert gap_fraction(y) == 0.0 def test_mse_regression_averages_the_modes(data) -> None: x, y = data grid = np.linspace(0, 1, 21) pred = fit_mse(x, y)(grid) assert np.all(np.abs(pred) < 0.15) assert gap_fraction(pred) == 1.0 def test_mixture_recovers_both_modes(data) -> None: x, y = data mix = fit_mixture(x, y) order = np.argsort(mix.b) assert mix.a[order] == pytest.approx([-0.5, 0.5], abs=0.05) assert mix.b[order] == pytest.approx([-0.5, 0.5], abs=0.05) assert mix.pi == pytest.approx([0.5, 0.5], abs=0.06) assert np.all(mix.sigma < 0.07) def test_mixture_fits_better_than_one_gaussian(data) -> None: x, y = data one = fit_mixture(x, y, n_components=1) two = fit_mixture(x, y, n_components=2) assert two.log_likelihood(x, y) > one.log_likelihood(x, y) + 100 def test_mixture_samples_stay_in_the_modes(data) -> None: x, y = data mix = fit_mixture(x, y) samples = mix.sample(np.repeat(np.linspace(0, 1, 11), 100), np.random.default_rng(1)) assert gap_fraction(samples) < 0.01 assert 0.4 < np.mean(samples > 0) < 0.6 # both sides are used