import matplotlib.pyplot as plt
import numpy as np
from clocks import (
ClockArray, InferenceConfig, MassConfig, NoiseConfig,
PriorConfig, SimulationConfig, infer, simulate,
)
from clocks.viz import THEMES, show, style
clock_array = ClockArray(
positions=np.array([[-6.0], [-3.0], [0.0], [3.0], [6.0]]), track_offset=1.0
)
truth = MassConfig(positions=np.array([[-2.0], [3.0]]), masses=np.array([0.045, 0.030]))
sim = simulate(SimulationConfig(
clock_array=clock_array, ground_truth=truth,
noise=NoiseConfig(observation_std=0.005), n_observations=25, seed=42,
))
result = infer(sim.observations, InferenceConfig(
clock_array=clock_array, noise=NoiseConfig(observation_std=0.005),
prior=PriorConfig(position_range=(-8.0, 8.0), mass_range=(0.005, 0.15)),
n_particles=400, n_masses=(1, 2, 3),
ess_target=0.8, rejuvenation_steps=2, proposal_scale=2.38, seed=42,
))
print(f"Posterior over K: { {k: round(v, 3) for k, v in result.posterior_by_model.items()} }")
print(f"Best model: K = {result.best_model}")
steps = np.arange(1, len(result.history) + 1)
models = sorted(result.posterior_by_model)
posteriors = [np.array([h[k] for h in result.history]) for k in models]
labels = [
f"K = {k} (true model)" if k == len(truth.masses) else f"K = {k}"
for k in models
]
for theme in THEMES:
with style(theme) as colors:
fig, ax = plt.subplots()
for label, posterior, color in zip(labels, posteriors, colors.ordered):
ax.plot(steps, posterior, color=color)
ax.annotate(
label, xy=(steps[-1], posterior[-1]),
xytext=(6, 0), textcoords="offset points",
ha="left", va="center", color=color,
bbox={"facecolor": colors.background, "linewidth": 0, "pad": 1.5},
)
ax.set_xlabel("observation #")
ax.set_ylabel("posterior probability")
ax.set_ylim(-0.05, 1.05)
ax.set_xlim(right=steps[-1] + 6.5)
ax.set_xticks(np.arange(0, steps[-1] + 1, 5))
show(fig)