"""Small time-series toolkit for Lecture 9 (figures and notebook)."""
import numpy as np
from scipy import optimize


# ------------------------------------------------------------------ red noise (Timmer & Koenig 1995)
def tk95(N, dt, psd, rng, over=10, mean=0.0, rms=None):
    """Light curve of N points (spacing dt) whose power spectrum has the shape psd(f).
    Simulates over*N points and cuts a random segment (avoids red-noise leak and periodicity)."""
    n = N * over
    f = np.fft.rfftfreq(n, dt)[1:]
    S = psd(f)
    re = rng.normal(size=f.size) * np.sqrt(S / 2)
    im = rng.normal(size=f.size) * np.sqrt(S / 2)
    if n % 2 == 0:
        im[-1] = 0.0                       # Nyquist term must be real
    x = np.fft.irfft(np.r_[0.0, re + 1j * im], n)
    s = rng.integers(0, n - N)
    x = x[s:s + N]
    x = x - x.mean()
    if rms is not None:
        x = x / x.std() * rms
    return mean + x


# ------------------------------------------------------------------ power spectra of binned light curves
def periodogram_rms(counts, dt):
    """rms-normalised periodogram (Miyamoto et al. 1991), units (rms/mean)^2 / Hz:
    P_j = 2 dt / (N <x>^2) |X_j|^2 with x = counts/dt the rate. Poisson level = 2/<x>."""
    N = counts.size
    x = counts / dt
    X = np.fft.rfft(x - x.mean())
    f = np.fft.rfftfreq(N, dt)
    P = 2.0 * dt / (N * x.mean()**2) * np.abs(X)**2
    return f[1:], P[1:]


def periodogram_leahy(counts):
    """Leahy normalisation: 2|a_j|^2 / N_ph ; Poisson noise ~ chi2_2 with mean 2."""
    F = np.fft.rfft(counts)
    return 2.0 * np.abs(F[1:])**2 / counts.sum()


def whittle_nll(P, S):
    """-ln L for a raw periodogram P given the model S (each P_j ~ S_j chi2_2 / 2)."""
    return np.sum(np.log(S) + P / S)


# ------------------------------------------------------------------ photon statistics
def rayleigh(t, f):
    """Rayleigh power S/N = |sum exp(2 pi i f t)|^2 / N ; under H0 ~ Exp(1)."""
    return np.abs(np.exp(2j * np.pi * f * t).sum())**2 / t.size


# ------------------------------------------------------------------ Fourier-series model selection
def fourier_design(t, f, K):
    cols = [np.ones_like(t)]
    for k in range(1, K + 1):
        cols += [np.cos(2 * np.pi * k * f * t), np.sin(2 * np.pi * k * f * t)]
    return np.vstack(cols).T


def fourier_evidence(t, y, dy, f, K, s=1.0):
    """Exact log evidence of y = X beta + noise, beta_k ~ N(0, s^2) (mean coefficient: broad N(0, 10^2 s^2)),
    noise N(0, dy^2). Also returns chi2_min and BIC."""
    X = fourier_design(t, f, K)
    pri = np.full(X.shape[1], s**2); pri[0] = (10 * s)**2
    C = np.diag(dy**2) + (X * pri) @ X.T
    sign, logdet = np.linalg.slogdet(C)
    ym = y.copy()
    lnZ = -0.5 * (ym @ np.linalg.solve(C, ym) + logdet + y.size * np.log(2 * np.pi))
    W = 1 / dy**2
    beta = np.linalg.lstsq(X * np.sqrt(W)[:, None], y * np.sqrt(W), rcond=None)[0]
    chi2 = np.sum(W * (y - X @ beta)**2)
    k = X.shape[1]
    return dict(lnZ=lnZ, chi2=chi2, bic=chi2 + k * np.log(y.size), beta=beta, k=k)
