# ruff: noqa: E501
"""Prototype measurements for the GeoStack missing-operators design (NumPy, float64).

Each block prints one row of the design's numerics table (section 5).
"""

import numpy as np


rng = np.random.default_rng(0)


def mirror_index(i, n):
    # SciPy "mirror": (d c b | a b c d | c b a)
    period = 2 * n - 2
    i = np.mod(i, period)
    return np.where(i < n, i, period - i)


def reflect_index(i, n):
    # SciPy "reflect": (d c b a | a b c d | d c b a)
    period = 2 * n
    i = np.mod(i, period)
    return np.where(i < n, i, period - 1 - i)


def gaussian_taps(sigma, truncate=4.0):
    half = int(truncate * sigma + 0.5)
    offsets = np.arange(-half, half + 1)
    taps = np.exp(-0.5 * (offsets / sigma) ** 2)
    return offsets, taps / taps.sum()


def filter_matrix(n, sigma, mode):
    offsets, taps = gaussian_taps(sigma)
    matrix = np.zeros((n, n))
    for row in range(n):
        idx = row + offsets
        if mode == "reflect":
            idx = reflect_index(idx, n)
        elif mode == "mirror":
            idx = mirror_index(idx, n)
        elif mode == "nearest":
            idx = np.clip(idx, 0, n - 1)
        elif mode == "wrap":
            idx = np.mod(idx, n)
        elif mode == "constant":
            ok = (idx >= 0) & (idx < n)
            idx, taps_row = idx[ok], taps[ok]
            np.add.at(matrix[row], idx, taps_row)
            continue
        np.add.at(matrix[row], idx, taps)
    return matrix


def filter_apply(x, sigma, mode):
    # B f = R_Ω (k ⋆ E f): gather through the boundary index map
    n = x.shape[0]
    offsets, taps = gaussian_taps(sigma)
    rows = np.arange(n)[:, None] + offsets[None, :]
    idx = reflect_index(rows, n) if mode == "reflect" else np.mod(rows, n)
    return (x[idx] * taps).sum(axis=1)


def filter_adjoint(r, sigma, mode):
    # Bᵀ g: scatter-add back through the same index map
    n = r.shape[0]
    offsets, taps = gaussian_taps(sigma)
    rows = np.arange(n)[:, None] + offsets[None, :]
    idx = reflect_index(rows, n) if mode == "reflect" else np.mod(rows, n)
    out = np.zeros(n)
    np.add.at(out, idx, r[:, None] * taps)
    return out


print("== F1 filters")
n, sigma = 200, 3.0
for mode in ["reflect", "wrap", "mirror", "nearest", "constant"]:
    b = filter_matrix(n, sigma, mode)
    asym = np.linalg.norm(b - b.T) / np.linalg.norm(b)
    print(f"{mode}: ||B - B^T|| / ||B|| = {asym:.3e}")
for mode in ["reflect", "wrap"]:
    x, r = rng.normal(size=n), rng.normal(size=n)
    lhs = filter_apply(x, sigma, mode) @ r
    rhs = x @ filter_adjoint(r, sigma, mode)
    print(f"{mode}: scatter adjoint dot test rel = {abs(lhs - rhs) / abs(lhs):.1e}")
for mode in ["nearest", "mirror"]:
    b = filter_matrix(n, sigma, mode)
    r = rng.normal(size=n)
    diff = np.abs(b @ r - b.T @ r)
    edge = diff[: int(4 * sigma) + 1].sum() + diff[-(int(4 * sigma) + 1) :].sum()
    print(
        f"{mode}, B r used for B^T r: rel error {np.linalg.norm(diff) / np.linalg.norm(b.T @ r):.2e}, share in the 13 edge cells per side {edge / diff.sum():.2f}"
    )
# masked normalised convolution
mask = rng.random(n) > 0.3
den = filter_apply(mask.astype(float), sigma, "reflect")
fwd = lambda f: filter_apply(mask * f, sigma, "reflect") / den
adj = lambda g: mask * filter_adjoint(g / den, sigma, "reflect")
x, r = rng.normal(size=n), rng.normal(size=n)
print(
    f"masked normalised convolution, dot test rel = {abs(fwd(x) @ r - x @ adj(r)) / abs(fwd(x) @ r):.1e}"
)
bm = np.stack([fwd(e) for e in np.eye(n)], 1)
print(
    f"masked normalised convolution, ||B_m - B_m^T|| / ||B_m|| = {np.linalg.norm(bm - bm.T) / np.linalg.norm(bm):.2f}"
)

print("\n== F2 grid transfer (1-D vertex nesting, n_f = 2 n_c - 1)")
nc = 33
nf = 2 * nc - 1
p = np.zeros((nf, nc))
for j in range(nc):
    p[2 * j, j] = 1.0
    if j < nc - 1:
        p[2 * j + 1, j] = 0.5
        p[2 * j + 1, j + 1] = 0.5
h = 1.0 / (nf - 1)
lap = (
    np.diag(2 * np.ones(nf))
    - np.diag(np.ones(nf - 1), 1)
    - np.diag(np.ones(nf - 1), -1)
) / h**2
lap[0, :] = 0
lap[-1, :] = 0
lap[0, 0] = lap[-1, -1] = 1.0
res = rng.normal(size=nf)
for c in [1.0, 0.5]:
    r_op = c * p.T
    a_c = r_op @ lap @ p
    corr = p @ np.linalg.solve(a_c, r_op @ res)
    if c == 1.0:
        corr_ref = corr
    else:
        print(
            f"coarse correction, c = 1 vs c = 1/2: max diff {np.max(np.abs(corr - corr_ref)):.1e}"
        )
const = np.ones(nf)
interior = slice(1, -1)
print(
    f"restriction of a constant, interior values: c = 1 gives {np.mean((p.T @ const)[interior]):.3f}, c = 1/2 gives {np.mean((0.5 * p.T @ const)[interior]):.3f}"
)
# conservative cell restriction R = k^(-D) P^T in 2-D, P copying each coarse cell
# into its k x k fine cells
# (its own generator; the 64 draws keep the shared stream, and so every simulated
# number below, as published)
rng.normal(size=64)
block_rng = np.random.default_rng(1)
for k in [2, 3]:
    nc2 = 12
    p1 = np.kron(np.eye(nc2), np.ones((k, 1)))  # 1-D copy, (k nc2, nc2)
    p2 = np.kron(p1, p1)  # 2-D copy, (k^2 nc2^2, nc2^2)
    r2 = p2.T / k**2
    fine = block_rng.normal(size=p2.shape[0])
    mass_err = abs((r2 @ fine).sum() * k**2 - fine.sum())
    const = r2 @ np.ones(p2.shape[0])
    wrong = (p2.T / 4) @ np.ones(p2.shape[0])
    print(
        f"conservative {k}:1 restriction in 2-D, mass error {mass_err:.1e}; constant restricts to {const.mean():.3f}; with 2^(-D) P^T to {wrong.mean():.3f}"
    )
# nonuniform rectilinear cells: R = M_H^-1 P^T M_h keeps the integral, (1/2) P^T does not
fine_edges = np.array([0.0, 1.0, 3.0, 6.0, 10.0])
coarse_edges = np.array([0.0, 3.0, 10.0])
m_h, m_hc = np.diff(fine_edges), np.diff(coarse_edges)
p_nu = np.array([[1.0, 0.0], [1.0, 0.0], [0.0, 1.0], [0.0, 1.0]])
fine_values = np.array([1.0, 0.0, 0.0, 0.0])
weighted = (p_nu.T @ (m_h * fine_values)) / m_hc
halved = 0.5 * p_nu.T @ fine_values
print(
    f"nonuniform conservative restriction: fine integral {m_h @ fine_values:.3f}; M_H^-1 P^T M_h gives {m_hc @ weighted:.3f}; (1/2) P^T gives {m_hc @ halved:.3f}"
)

print("\n== F3 trace and I3 plume: transect flux of a Gaussian plume column")
q = 1000.0 / 3600.0  # 1000 kg/h in kg/s
u = 3.0
a_par, b_par = 0.22, 0.9
dx = 20.0
xs = np.arange(-1000.0, 4000.0, dx) + dx / 2
ys = np.arange(-1500.0, 1500.0, dx) + dx / 2
xx, yy = np.meshgrid(xs, ys, indexing="ij")
sig = a_par * np.clip(xx, 1e-6, None) ** b_par
col = np.where(
    xx > 0, q / (np.sqrt(2 * np.pi) * u * sig) * np.exp(-(yy**2) / (2 * sig**2)), 0.0
)
mass_cell = col.sum() * dx * dx
for dist in [200.0, 500.0, 2000.0]:
    # trace by bilinear interpolation onto 400 nodes across the wind, midpoint rule
    ny = 400
    yq = np.linspace(-1500.0, 1500.0, ny + 1)
    ym = 0.5 * (yq[1:] + yq[:-1])
    w = np.diff(yq)
    ix = (dist - xs[0]) / dx
    i0 = int(np.floor(ix))
    fx = ix - i0
    jy = (ym - ys[0]) / dx
    j0 = np.clip(np.floor(jy).astype(int), 0, len(ys) - 2)
    fy = jy - j0
    v = (1 - fx) * ((1 - fy) * col[i0, j0] + fy * col[i0, j0 + 1]) + fx * (
        (1 - fy) * col[i0 + 1, j0] + fy * col[i0 + 1, j0 + 1]
    )
    flux_trace = (w * v * u).sum()
    # a one-pixel strip across the wind, the stand-in for a strip flux method
    flux_strip = col[int((dist - xs[0]) // dx)].sum() * dx * u
    print(
        f"{dist:6.0f} m: trace flux / Q = {flux_trace / q:.4f}; one-pixel strip / Q = {flux_strip / q:.4f}; sigma_y = {a_par * dist**b_par:.1f} m"
    )

print("oblique wind, 30 degrees off the x axis, transect 500 m downwind")
theta = np.deg2rad(30.0)
along = xx * np.cos(theta) + yy * np.sin(theta)
cross = -xx * np.sin(theta) + yy * np.cos(theta)
sig_o = a_par * np.clip(along, 1e-6, None) ** b_par
col_o = np.where(
    along > 0,
    q / (np.sqrt(2 * np.pi) * u * sig_o) * np.exp(-(cross**2) / (2 * sig_o**2)),
    0.0,
)
for dist in [200.0, 500.0]:
    strip = np.abs(along - dist) <= dx / 2
    flux_strip = col_o[strip].sum() * dx * u
    tq = np.linspace(-800.0, 800.0, 801)
    tm = 0.5 * (tq[1:] + tq[:-1])
    w = np.diff(tq)
    px = dist * np.cos(theta) - tm * np.sin(theta)
    py = dist * np.sin(theta) + tm * np.cos(theta)
    ix = (px - xs[0]) / dx
    i0 = np.floor(ix).astype(int)
    fx = ix - i0
    jy = (py - ys[0]) / dx
    j0 = np.floor(jy).astype(int)
    fy = jy - j0
    v = (1 - fx) * ((1 - fy) * col_o[i0, j0] + fy * col_o[i0, j0 + 1]) + fx * (
        (1 - fy) * col_o[i0 + 1, j0] + fy * col_o[i0 + 1, j0 + 1]
    )
    print(
        f"{dist:6.0f} m: trace flux / Q = {(w * v * u).sum() / q:.4f}; one-pixel strip / Q = {flux_strip / q:.4f}"
    )

print("\n== I1 and I4: quadrature (Nyström) method")


def gauss_legendre_01(n):
    x, w = np.polynomial.legendre.leggauss(n)
    return 0.5 * (x + 1), 0.5 * w


def trapezoid_01(n):
    x = np.linspace(0, 1, n)
    w = np.full(n, 1.0 / (n - 1))
    w[[0, -1]] *= 0.5
    return x, w


kern = lambda x, s: np.exp(-((x[:, None] - s[None, :]) ** 2))
rhs = lambda x: np.cos(np.pi * x)
lam = 0.5


def solve(rule, n):
    s, w = rule(n)
    a = np.eye(n) - lam * kern(s, s) * w[None, :]
    u = np.linalg.solve(a, rhs(s))
    return lambda x: rhs(x) + lam * (kern(x, s) * w[None, :]) @ u


xe = np.linspace(0, 1, 101)
ref = solve(gauss_legendre_01, 64)(xe)
for n in [4, 8, 16]:
    e_gl = np.max(np.abs(solve(gauss_legendre_01, n)(xe) - ref))
    e_tr = np.max(np.abs(solve(trapezoid_01, n)(xe) - ref))
    print(f"N = {n:2d}: Gauss-Legendre err {e_gl:.1e}; trapezoid err {e_tr:.1e}")
s, w = gauss_legendre_01(8)
u_rank1 = np.linalg.solve(np.eye(8) - 1.0 * np.outer(s, s) * w[None, :], s)
print(
    f"rank-one kernel x s, lambda = 1: max |u - 1.5 x| at nodes = {np.max(np.abs(u_rank1 - 1.5 * s)):.1e}"
)
# kernel mean of an RBF under U[0,1]: dense quadrature vs closed form
from math import erf, pi, sqrt


ell = 0.2
t = np.linspace(0, 1, 50)
s, w = gauss_legendre_01(32)
km = (np.exp(-((t[:, None] - s[None, :]) ** 2) / (2 * ell**2)) * w).sum(1)
exact = np.array(
    [
        ell
        * sqrt(pi / 2)
        * (erf((1 - ti) / (sqrt(2) * ell)) + erf(ti / (sqrt(2) * ell)))
        for ti in t
    ]
)
print(
    f"kernel mean = K 1 by a 32-node rule vs closed form: max err {np.max(np.abs(km - exact)):.1e}"
)

print("\n== I2 spectral response sparsity")
nu = np.arange(4000.0, 5000.0, 0.01)  # cm^-1, about 2000 to 2500 nm
wq = np.full(nu.size, 0.01)
for name, centre_nm, fwhm_nm in [
    ("Sentinel-2 B12-like", 2190.0, 180.0),
    ("EMIT-like", 2300.0, 8.5),
]:
    centre = 1e7 / centre_nm
    fwhm = 1e7 / (centre_nm - fwhm_nm / 2) - 1e7 / (centre_nm + fwhm_nm / 2)
    resp = np.exp(-0.5 * ((nu - centre) / (fwhm / 2.3548)) ** 2)
    row = resp * wq
    keep = row > 1e-6 * row.max()
    row = np.where(keep, row, 0.0)
    row /= row.sum()
    print(
        f"{name}: FWHM {fwhm:.1f} cm^-1, nonzeros {keep.sum()} of {nu.size}, row sum {row.sum():.12f}"
    )

print("\n== persistence: thinning, missing mass, duty cycle")
T = 365.0
lam_rate = 0.5  # events per day
n_sim = 4000
mu, s_ln = np.log(300.0), 1.0  # lognormal marks, kg/h
pod = lambda qq: 1 / (1 + np.exp(-(qq - 400.0) / 80.0))
revisit = 5.0  # days; an event is visible if an overpass falls in it
dur = 0.25  # event duration in days
cloud = 0.4
n_ev = n_det = 0
mass_all = mass_det = sum_q = sum_qdet = 0.0
for _ in range(n_sim // 10):
    k = rng.poisson(lam_rate * T)
    t_ev = rng.uniform(0, T, k)
    qq = rng.lognormal(mu, s_ln, k)
    phase = rng.uniform(0, revisit)
    seen = (
        np.floor((t_ev + dur - phase) / revisit) > np.floor((t_ev - phase) / revisit)
    ) & (rng.random(k) > cloud)
    det = seen & (rng.random(k) < pod(qq))
    n_ev += k
    n_det += det.sum()
    sum_q += qq.sum()
    sum_qdet += qq[det].sum()
    vis = seen.sum()
p_schedule = dur / revisit * (1 - cloud)
qs = rng.lognormal(mu, s_ln, 200000)
print(
    f"detected fraction {n_det / n_ev:.4f} ({n_det} of {n_ev} events); schedule x cloud x E[P_d] = {p_schedule * pod(qs).mean():.4f}"
)
print(
    f"detected mean rate / true mean rate {(sum_qdet / n_det) / (sum_q / n_ev):.2f}; E[P_d] alone {pod(qs).mean():.3f}; mass seen / mass emitted {sum_qdet / sum_q:.4f}"
)
# duty cycle: on-off source with mean on 2 d, off 18 d, emitting events at rate 5/d while on
on_mean, off_mean, rate_on = 2.0, 18.0, 5.0
mean_rate = rate_on * on_mean / (on_mean + off_mean)
horizon = 7.0
hits = 0
trials = 20000
for _ in range(trials):
    # stationary start
    state_on = rng.random() < on_mean / (on_mean + off_mean)
    t, got = 0.0, False
    while t < horizon and not got:
        stay = rng.exponential(on_mean if state_on else off_mean)
        if state_on:
            span = min(stay, horizon - t)
            if rng.random() < 1 - np.exp(-rate_on * span):
                got = True
        t += stay
        state_on = not state_on
    hits += got
# MMPP closed form of section 4.9: 1 - pi exp(tau (G - Lambda)) 1, stationary pi
switch_on, switch_off = 1 / off_mean, 1 / on_mean
generator = np.array([[-switch_on, switch_on], [switch_off, -switch_off]])
rates = np.diag([0.0, rate_on])
pi_stat = np.array([switch_off, switch_on]) / (switch_on + switch_off)
eigval, eigvec = np.linalg.eig(horizon * (generator - rates))
propagator = (eigvec * np.exp(eigval)) @ np.linalg.inv(eigvec)
p_closed = 1 - float(np.real(pi_stat @ propagator @ np.ones(2)))
print(
    f"P(event in next {horizon:.0f} d): on-off simulated {hits / trials:.3f}; MMPP closed form {p_closed:.3f}; Poisson with the same mean rate {1 - np.exp(-mean_rate * horizon):.3f}"
)
