"""Signals and autocorrelation estimates for the drawings of this page.

    python acf.py      writes the .dat files the .tex drawings read

N = 200 samples, as in the exam figures. The sinusoid has a period of 20 samples (whole cycles, so its sample power is exactly 0.5)
and the noise is drawn with a fixed seed, so the files come out the same every run.
"""
import numpy as np

N = 200
n = np.arange(N)
rng = np.random.default_rng(1)
s = np.sin(2 * np.pi * n / 20)


def noise(power):
    """Gaussian noise with sample mean 0, sample power `power`, uncorrelated with the sinusoid."""
    w = rng.standard_normal(N)
    w -= w.mean()
    w -= s * (w @ s) / (s @ s)                         # uncorrelated with the sinusoid
    return w * np.sqrt(power / np.mean(w**2))


signals = {
    "sine": s,                                         # amplitude 1, zero mean
    "noise": noise(7),      # power 7, zero mean
    "sine1": s + 1,                                    # sinusoid + 1
    "noise4": noise(1) + 4,              # power 1 noise + 4
    "sinenoise": s + noise(1.5),  # sinusoid + noise of power 1.5
}
k = np.arange(-(N - 1), N)
for name, x in signals.items():
    r = np.correlate(x, x, mode="full")                # sum over n of x[n] x[n+k]
    biased, unbiased = r / N, r / (N - np.abs(k))
    np.savetxt(f"{name}.dat", np.column_stack([n, x]), fmt="%.5g", header="n x", comments="")
    np.savetxt(f"{name}-acf.dat", np.column_stack([k, k + N - 1, biased, unbiased]),
               fmt="%.5g", header="k lag biased unbiased", comments="")
