import os
from pathlib import Path

# --8<-- [start:code]
"""Conditional flow matching: train a velocity, march it as an ODE

The target is a two-arm spiral galaxy: a bright core and two logarithmic arms whose density falls off outward.
It fails *loudly* in two independent ways: a collapsed velocity loses the arms (the angle no longer winds with
the radius), and a mode-dropping one empties one arm.

Lipman et al., "Flow Matching for Generative Modeling", ICLR 2023 (§3, the conditional objective).
"""

import foundax
import jax
import numpy as np
import optax

import jno

run = jno.setup(__file__)
KEY, D, N, EPOCHS, POINTS = jax.random.PRNGKey(0), 2, 16384, 12000, 2048  # POINTS: the point axis, not the sample axis

# Two logarithmic arms r = R0 exp(B phi), phi in [0, PHI] (the angle along the arm, density falling outward),
# a thicker scatter outward, and a bright Gaussian core.
rng = np.random.default_rng(0)
R0, B, PHI = 0.12, 0.35, 9.5
phi = PHI * rng.beta(1.0, 1.3, N)  # the position along the arm
r = R0 * np.exp(B * phi)
theta = phi + np.pi * rng.integers(0, 2, N)  # arm 0 or arm 1
arms = np.stack([np.cos(theta), np.sin(theta)], -1) * r[:, None] + (0.04 + 0.06 * r)[:, None] * rng.normal(size=(N, D))
core = 0.28 * rng.normal(size=(N, D))
data = np.where((rng.random(N) < 0.2)[:, None], core, arms).astype(np.float32)

domain = jno.domain.from_array({"data": data})
d0, d1, _ = domain.variable("data")
x1 = jno.np.concatenate([d0, d1])  # the data sample

# The probability path as the formula it is. `like=` takes the draw's shape from the expression, so the prior
# tracks solve(points=...); a shape written down by hand would go stale and fail by broadcasting.
x0 = jno.noise.gaussian(std=1.0, like=x1)  # prior draw
t = jno.noise.uniform(low=0.0, high=1.0, like=d0)  # path time, one per point
x_t = (1 - t) * x0 + t * x1  # the linear (optimal-transport) path
target = x1 - x0  # its velocity, constant along the path

v = jno.nn(foundax.mlp(D + 1, output_dim=D, hidden_dims=256, num_layers=4, activation=jax.nn.swish, key=KEY))
v.optimizer(optax.adam(3e-3))

crux = jno.core([(v(x_t, t) - target).mse])  # the whole objective
stats = crux.solve(epochs=EPOCHS, points=POINTS)
final_loss = float(stats.training_logs[-1]["total_loss"][-1])
print(f"final CFM loss: {final_loss:.4f}   (an O(1) plateau is correct: the objective is irreducible)")

# Sample: march the trained velocity from Gaussian draws, state first and time second, 120 Heun steps.
z = jax.random.normal(jax.random.PRNGKey(1), (6000, D))
path = np.asarray(v.flow(z, time=(0.0, 1.0, 121), save=True))  # (121, 6000, D)
samples = path[-1]


# Check: the angle of a sample against the arm law theta = ln(r / R0) / B (mod pi), and the radial density.
def off_arm(p):
    r, theta = np.linalg.norm(p, axis=-1), np.arctan2(p[:, 1], p[:, 0])
    sel = (r > 0.5) & (r < 3.0)  # outside the core, inside the outer cut-off
    off = (theta - np.log(r / R0) / B)[sel] % np.pi
    return np.minimum(off, np.pi - off)  # distance to the nearest arm in angle, rad


on_arm = np.mean(off_arm(samples) < 0.4)  # a uniform angle would give 0.4 * 2 / pi = 25 %
on_arm_data = np.mean(off_arm(data) < 0.4)
hist = lambda p: np.histogram(np.linalg.norm(p, axis=-1), bins=8, range=(0, 4), density=True)[0]
radial_gap = np.abs(hist(samples) - hist(data)).max()
print(f"samples within 0.4 rad of an arm: {on_arm:.2f}   (data: {on_arm_data:.2f}, uniform angle: 0.25)")
print(f"max radial-density gap, samples against data: {radial_gap:.3f}")
assert on_arm > 0.85 * on_arm_data and radial_gap < 0.1
# --8<-- [end:code]

# ---- data for the figures (tools/tutorial_figures/flow_matching_galaxy.py), only when asked ----
if out := os.environ.get("JNO_FIGURE_DATA"):
    np.savez_compressed(Path(out) / "flow_matching_galaxy.npz", path=path.astype(np.float32), data=data[:6000])
