{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e43e6d9a",
   "metadata": {},
   "source": [
    "# Lecture 9 — Hands-on: periods in practice\n",
    "\n",
    "| part | topic |\n",
    "|---|---|\n",
    "| A | Lomb–Scargle normalisations, null distributions, Bayesian LS |\n",
    "| B | Broad-band variability: rms power spectrum, Whittle fit, QPO |\n",
    "| C | X-ray photons: event file → FFT → EF / Z² / Gregory–Loredo → bootstrap (`period_search.py`, `psearch.py`) |\n",
    "| D | Write your own Gregory–Loredo |\n",
    "| E | Optical light curves: cadence, aliases, harmonics, GL for magnitudes, trends; real OGLE data |\n",
    "| F | Monte Carlo false alarms with red noise (Timmer & König) |\n",
    "| G | Werewolves: the power of a test |\n",
    "| H | Homework |\n",
    "\n",
    "Files needed in this folder: `period_search.py`, `psearch.py`, `psplot.py`, `ts_tools.py`, `sim_data.py`, `gl_gauss.py`, `fig9_extra_sim.py`.\n",
    "Install: `pip install astropy scipy matplotlib`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40cc3694",
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import numpy as np, matplotlib.pyplot as plt, warnings\n",
    "from scipy import optimize, stats\n",
    "from scipy.special import gammaln, logsumexp\n",
    "from astropy.timeseries import LombScargle\n",
    "import period_search as ps, ts_tools as T, sim_data as sd\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "plt.rcParams.update({\"figure.dpi\": 110, \"axes.spines.top\": False, \"axes.spines.right\": False})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e4b2cab",
   "metadata": {},
   "source": [
    "## A. Lomb–Scargle normalisations\n",
    "\n",
    "$$P_{\\rm psd}=\\tfrac12[\\chi^2_0-\\chi^2(f)],\\quad P_{\\rm std}=1-\\frac{\\chi^2(f)}{\\chi^2_0},\\quad P_{\\rm model}=\\frac{\\chi^2_0}{\\chi^2(f)}-1,\\quad P_{\\rm log}=\\ln\\frac{\\chi^2_0}{\\chi^2(f)}$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6954a11a",
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(21)\n",
    "N = 40\n",
    "t = np.sort(rng.uniform(0, 60, N)); dy = np.full(N, 0.5)\n",
    "y = 3.0 + 0.45 * np.sin(2 * np.pi * t / 4.3) + rng.normal(0, 0.5, N)\n",
    "f = np.linspace(0.01, 1.2, 6000)\n",
    "ls = LombScargle(t, y, dy)\n",
    "P = {n: ls.power(f, normalization=n) for n in (\"psd\", \"standard\", \"model\", \"log\")}\n",
    "ib = P[\"psd\"].argmax()\n",
    "print(\"best f =\", f[ib], \" (true\", 1/4.3, \")\")\n",
    "for n, v in P.items():\n",
    "    print(f\"{n:9s} peak = {v[ib]:.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92ee54b6",
   "metadata": {},
   "source": [
    "**A1.** Compute $\\chi^2_0$ and $\\chi^2(f_{\\rm best})$ yourself (weighted least squares with $c+a\\cos+b\\sin$) and verify all four numbers."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e0864207",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ed0a527",
   "metadata": {},
   "source": [
    "**A2.** Simulate 4000 noise-only light curves with the same times and errors. At one fixed frequency, compare the distribution of $P_{\\rm psd}$ with $e^{-z}$ and of $P_{\\rm std}$ with $\\Pr(P>z)=(1-z)^{(N-3)/2}$. What happens to $P_{\\rm psd}$ if you underestimate the errors by 30%?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24b0ec7e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dec3a03e",
   "metadata": {},
   "source": [
    "**A3.** Bayesian Lomb–Scargle: plot $p(f|D)\\propto e^{P_{\\rm psd}}$ and $\\propto(1-P_{\\rm std})^{-(N-3)/2}$. What fraction of the posterior lies within $\\pm0.05\\,{\\rm d^{-1}}$ of the peak? Compare with the periodogram."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "76e880a6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "edbf64ed",
   "metadata": {},
   "source": [
    "## B. When the signal is the noise: fitting the power spectrum\n",
    "\n",
    "Raw periodogram powers scatter as $P_j\\sim S(f_j)\\,\\chi^2_2/2$, so the likelihood is Whittle's:\n",
    "$-\\ln L=\\sum_j[\\ln S(f_j)+P_j/S(f_j)]$. We simulate an X-ray light curve with red noise and a QPO (Timmer & König) and fit it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1a52f98a",
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(4)\n",
    "dt, Nb, rate = 0.25, 2**15, 60.0\n",
    "def bpl(f, A, fb, a1, a2):\n",
    "    return A * (f / fb)**(-a1) / (1 + (f / fb)**(a2 - a1))\n",
    "def lor(f, R, nu0, Q):\n",
    "    D = nu0 / (2 * Q); return R * D / np.pi / (D**2 + (f - nu0)**2)\n",
    "shape = lambda f: bpl(f, 1.0, 0.01, 1.0, 2.2) + 0.012 * lor(f, 1.0, 0.12, 6.0)\n",
    "x = np.clip(T.tk95(Nb, dt, shape, rng, over=4, mean=rate, rms=0.25 * rate), 0, None)\n",
    "cts = rng.poisson(x * dt).astype(float)\n",
    "fr, Pr = T.periodogram_rms(cts, dt)\n",
    "pois = 2 / (cts.sum() / (Nb * dt))\n",
    "print(f\"mean rate {cts.sum()/(Nb*dt):.1f} cts/s, Poisson level 2/<x> = {pois:.4f}, mean of P at f > 1 Hz = {Pr[fr > 1].mean():.4f}\")\n",
    "plt.loglog(fr, Pr * fr, lw=0.3, color=\"gray\"); plt.xlabel(\"f [Hz]\"); plt.ylabel(\"f P(f)\");"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b99b45b",
   "metadata": {},
   "source": [
    "**B1.** Fit `bending PL + Lorentzian + Poisson` and `bending PL + Poisson` with the Whittle likelihood (several starting points!). Report $\\nu_0$, $Q$ and the likelihood-ratio statistic."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93d3deb8",
   "metadata": {},
   "outputs": [],
   "source": [
    "def model(p, f):\n",
    "    lA, lfb, a1, a2, lR, nu0, lQ = p\n",
    "    return bpl(f, 10**lA, 10**lfb, a1, a2) + lor(f, 10**lR, nu0, 10**lQ) + pois\n",
    "def model0(p, f):\n",
    "    lA, lfb, a1, a2 = p\n",
    "    return bpl(f, 10**lA, 10**lfb, a1, a2) + pois\n",
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c558597a",
   "metadata": {},
   "source": [
    "**B2.** Why can't we use $\\chi^2_3$ for the likelihood-ratio statistic of the QPO? Sketch how you would calibrate it by simulation (posterior predictive, Vaughan 2010)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2242800",
   "metadata": {},
   "source": [
    "## C. X-ray photons with `period_search.py`\n",
    "\n",
    "`sd.make_xray_file()` writes a simulated EPIC-pn event file (`TIME`, `PI` in eV, `STDGTI`) of an SMC pulsar,\n",
    "with a flare and a data drop excluded by the GTIs. **Pretend you do not know the period.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f5959532",
   "metadata": {},
   "outputs": [],
   "source": [
    "fn = sd.make_xray_file(\"sim_smc_pulsar_pn.fits\")\n",
    "t, meta = ps.read_events(fn, energy=(0.5, 10.0), pi_to_kev=0.001, return_meta=True)\n",
    "print(meta[\"mission\"], meta[\"instrument\"], meta[\"n_events\"], \"events, exposure\", meta[\"exposure\"], \"s, notes:\", meta[\"notes\"])\n",
    "from astropy.io import fits\n",
    "with fits.open(fn) as h:\n",
    "    tall = h[\"EVENTS\"].data[\"TIME\"]; gti = np.array(h[\"STDGTI\"].data.tolist())\n",
    "bins = np.arange(tall.min(), tall.max() + 100, 100)\n",
    "plt.step(bins[:-1] - bins[0], np.histogram(tall, bins)[0] / 100, where=\"post\", color=\"gray\", label=\"all\")\n",
    "plt.step(bins[:-1] - bins[0], np.histogram(t, bins)[0] / 100, where=\"post\", label=\"GTI, 0.5-10 keV\")\n",
    "plt.xlabel(\"t [s]\"); plt.ylabel(\"rate [cts/s]\"); plt.legend();"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e9e57a44",
   "metadata": {},
   "source": [
    "**C1.** Blind search: bin at 0.5 s, compute the Leahy periodogram, the 99.9% threshold after all trials, and the highest peak. What period does it suggest? Check 2P and P/2 by folding."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9b226f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "053a1395",
   "metadata": {},
   "source": [
    "**C2.** Narrow search 11.75–12.0 s: run EF (m = 10), Z²₄ and GL (m = 2…12) on the same grid. Compare best periods, the EF p-value and the GL odds. Plot the GL odds per m."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1715bb55",
   "metadata": {},
   "outputs": [],
   "source": [
    "fgrid = ps.frequency_grid(t, pmin=11.75, pmax=12.0, oversample=10)\n",
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "604178d3",
   "metadata": {},
   "source": [
    "**C3.** Period error: bootstrap the events (EF, 150 resamples). Report the 68% interval and compare it with the peak width $P^2/T$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42ca2a6b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ab0d8fd",
   "metadata": {},
   "source": [
    "**C4.** The same from the terminal (run in a shell, or here with `!`):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "87914ef1",
   "metadata": {},
   "outputs": [],
   "source": [
    "!python psearch.py sim_smc_pulsar_pn.fits -m GL -mspec -pmin 11.75 -pmax 12.0 -e 0.5 10 --pi2kev 0.001 -j run_gl.json -q\n",
    "!python psplot.py run_gl.json -pbins 16 -o run_gl.png"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8cf1ba81",
   "metadata": {},
   "source": [
    "**C5. Real data (provided in class).** Repeat C1–C4 on the SMC pulsar observations. Add: pulse profile and pulsed fraction in 0.2–2 keV vs 2–10 keV.\n",
    "\n",
    "*Placeholder — file names and period ranges from Georgios.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "545a0653",
   "metadata": {},
   "outputs": [],
   "source": [
    "# fn_real = \"PXXXXXXXXXX_pn_bary.fits\"      # barycentred event file\n",
    "# t, meta = ps.read_events(fn_real, energy=(0.2, 12.0), pi_to_kev=0.001, return_meta=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "09c852de",
   "metadata": {},
   "source": [
    "## D. Write your own Gregory–Loredo\n",
    "\n",
    "Flow chart (slides): models $M_1$ (constant) and $M_m$ ($m$-bin periodic); priors ($1/f$ over the range, flat bin phase, equal $m$);\n",
    "fold → count $n_j$ for $n_\\theta$ phase offsets → $\\ln O_m(f,\\theta)=N\\ln m+\\ln(m-1)!-\\ln(N+m-1)!+\\sum_j\\ln n_j!$\n",
    "→ average over $\\theta$ → integrate over $f$ → average over $m$. Work in logs (`gammaln`, `logsumexp`).\n",
    "\n",
    "**D1.** Complete the function. **D2.** Test it on the simulated pulsar and on scrambled times. **D3.** Compare with `ps.gregory_loredo`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d6aa383b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def gl_log10_odds(t, freqs, m_values=range(2, 13), n_phase=16):\n",
    "    t = t - t[0]; N = t.size\n",
    "    lnprior = -np.log(freqs) - np.log(np.log(freqs[-1] / freqs[0]))   # 1/f prior, normalised\n",
    "    lndf = np.log(np.gradient(freqs))\n",
    "    lnO_m = []\n",
    "    for m in m_values:\n",
    "        # TODO: your code here\n",
    "    lnO = logsumexp(lnO_m) - np.log(len(lnO_m))\n",
    "    return lnO / np.log(10), np.array(lnO_m) / np.log(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a7e98ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fdc3bf1d",
   "metadata": {},
   "source": [
    "## E. Optical light curves (OGLE-like)\n",
    "\n",
    "Two cadences of the same SMC Be star with a non-radial pulsation at $f=1.55\\,{\\rm d^{-1}}$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4cec7c37",
   "metadata": {},
   "outputs": [],
   "source": [
    "tA, tB = sd.ogle_cadences()\n",
    "rng = np.random.default_rng(5)\n",
    "yA = sd.be_star(tA) + rng.normal(0, 0.006, tA.size); yB = sd.be_star(tB) + rng.normal(0, 0.006, tB.size)\n",
    "fg = np.linspace(0.02, 4.0, 40000)\n",
    "print(tA.size, \"sparse points over\", round(np.ptp(tA)), \"d;\", tB.size, \"dense points over\", round(np.ptp(tB)), \"d\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e67bedac",
   "metadata": {},
   "source": [
    "**E1.** For both cadences: Lomb–Scargle (psd, with errors) and the window function $|W(f)|^2$. Which peaks are aliases $|f\\pm k|$? Compute $\\Delta\\ln L$ between the true peak and the best alias."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0138efaa",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a6754529",
   "metadata": {},
   "source": [
    "**E2.** Make the signal 4× weaker (amplitude 3 mmag) and repeat. Which cadence still identifies the true frequency?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f64a8e1e",
   "metadata": {},
   "source": [
    "**E3. How many harmonics?** For the eclipsing binary below, compute the exact evidence (`T.fourier_evidence`) and BIC for $K=1\\dots20$ at $f=1/P$. Which $K$? What does a 1-term LS find, and why?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0d5d7f97",
   "metadata": {},
   "outputs": [],
   "source": [
    "te = tA.copy(); ye = sd.eclipsing(te) + np.random.default_rng(32).normal(0, 0.012, te.size); de = np.full(te.size, 0.012)\n",
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6e789b3b",
   "metadata": {},
   "source": [
    "## E4. Light curves, not photons: Gregory–Loredo for magnitudes\n",
    "\n",
    "In a phase bin $j$ the measurements are combined by their **weighted mean** $\\bar y_j$ (weights $w_i=1/(\\sigma_i^2+s^2)$, $s$ = jitter);\n",
    "marginalising the bin level gives a factor $\\sqrt{2\\pi/W_j}/\\Delta r$ (Occam) times $e^{-\\chi^2_j/2}$ (scatter inside the bin). `gl_gauss.py` implements it.\n",
    "\n",
    "First a simulated BeXRB in OGLE (Be-disc trend, two outbursts, weak periastron flares at $P_{\\rm orb}=23.9$ d, sparse before MJD 59500, dense after)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cef973cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gl_gauss as G\n",
    "from fig9_extra_sim import bexrb_lightcurve\n",
    "t_o, y_o = bexrb_lightcurve()\n",
    "def running_median(t, y, half):\n",
    "    return np.array([np.median(y[np.abs(t - ti) < half]) for ti in t])\n",
    "plt.figure(figsize=(11, 3)); plt.plot(t_o, y_o, \".\", ms=2); plt.gca().invert_yaxis(); plt.xlabel(\"MJD\"); plt.ylabel(\"I\");"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "05c6cf76",
   "metadata": {},
   "source": [
    "**E5.** Split at MJD 59500. For each part: LS of the raw data, and after subtracting a running median of half-width 5 d and 50 d. Where is the highest peak? Then run `G.gl_gauss` (P = 10–60 d) on the ±50 d detrended data with a jitter estimated from the scatter."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce43505c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d18257c",
   "metadata": {},
   "source": [
    "## E6. Real OGLE data\n",
    "\n",
    "* **RX J0520.5−6932** (LMC): `https://www.astrouw.edu.pl/ogle/ogle4/xrom/rx-j0520.5-6932/phot.dat` — split at MJD 59500; find the two major outbursts; search for the orbital period before and after; compare aliases and odds.\n",
    "* **SMC X-3** (`sxp7.78`) and **SMC X-2** (`sxp2.37`): strong long-term trends — how does the trend mask the period, how does the detrending window change it? Analyse seasons separately.\n",
    "\n",
    "Questions: how do we combine measurements in a phase bin? Is the period stable between seasons? What are the odds under a red-noise null (simulate with `T.tk95`, same sampling and detrending)?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40215f96",
   "metadata": {},
   "outputs": [],
   "source": [
    "import urllib.request, os\n",
    "FILES = {\"rx-j0520.5-6932\": \"rxj0520.dat\", \"sxp7.78\": \"smc_x3.dat\", \"sxp2.37\": \"smc_x2.dat\"}\n",
    "def load_ogle(name):\n",
    "    # OGLE XROM phot.dat: HJD, I, sigma_I, ... -> MJD, I, sigma_I (uses a local copy if present)\n",
    "    fn = FILES.get(name, name + \".dat\")\n",
    "    if not os.path.exists(fn):\n",
    "        urllib.request.urlretrieve(f\"https://www.astrouw.edu.pl/ogle/ogle4/xrom/{name}/phot.dat\", fn)\n",
    "    d = np.loadtxt(fn)\n",
    "    return d[:, 0] - 2400000.5, d[:, 1], d[:, 2]\n",
    "def rmed(t, y, h):\n",
    "    return np.array([np.median(y[np.abs(t - ti) < h]) for ti in t])\n",
    "mjd, mag, err = load_ogle(\"rx-j0520.5-6932\")\n",
    "print(len(mjd), \"points, MJD\", round(mjd.min()), \"-\", round(mjd.max()))\n",
    "plt.figure(figsize=(11, 3)); plt.plot(mjd, mag, \".\", ms=1.5); plt.gca().invert_yaxis(); plt.axvline(59500, color=\"r\"); plt.xlabel(\"MJD\");"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f81a9cc8",
   "metadata": {},
   "source": [
    "**E7.** RX J0520.5−6932: exclude the two major outbursts, detrend each segment (±50 d), and compare LS before/after MJD 59500 (15–40 d). Which peaks are ±1/yr aliases? Then SMC X-3 with windows ±100, ±50, ±10 d."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fd4a9462",
   "metadata": {},
   "outputs": [],
   "source": [
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7456567d",
   "metadata": {},
   "source": [
    "## F. False alarms with red noise\\n\\nA pure red-noise light curve ($S\\propto f^{-2}$, 400 points). **F1.** Compute the LS (psd) periodogram and the 99% global threshold assuming white noise. **F2.** Fit a power law to the periodogram (Whittle), simulate 300 light curves with `T.tk95`, and compute the local and global 99% levels. How many 'significant' peaks survive?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "314790f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "rng = np.random.default_rng(12)\n",
    "Nr = 400; tr = np.arange(Nr, dtype=float); er = 0.2\n",
    "yr = T.tk95(Nr, 1.0, lambda f: f**-2.0, rng) + rng.normal(0, er, Nr)\n",
    "fr2 = np.linspace(1 / Nr, 0.5, 2000)\n",
    "pr = LombScargle(tr, yr, er).power(fr2, normalization=\"psd\")\n",
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "664306c1",
   "metadata": {},
   "source": [
    "## G. Werewolves\\n\\nOser's model: sighting rate $\\propto 0.9+0.1\\sin(2\\pi t/28\\,{\\rm d})$, $N=885$ in a year. **G1.** Rayleigh $S/N=|\\sum e^{2\\pi i t_k/28}|^2/N$ for one simulated year; single-frequency p-value $e^{-S/N}$. **G2.** Repeat 2000 times: what fraction of years gives $p<0.01$ (the *power*)? How many sightings for 90% power? **G3.** If you did not know the period (search 10–60 d), how many independent trials?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f4a9d641",
   "metadata": {},
   "outputs": [],
   "source": [
    "def sightings(N, rng):\n",
    "    out = np.empty(0)\n",
    "    while out.size < N:\n",
    "        c = rng.uniform(0, 365, 3 * N); out = np.r_[out, c[rng.random(c.size) < 0.9 + 0.1 * np.sin(2 * np.pi * c / 28)]]\n",
    "    return out[:N]\n",
    "rng = np.random.default_rng(13)\n",
    "tw = sightings(885, rng); S = T.rayleigh(tw, 1 / 28)\n",
    "print(f\"S/N = {S:.2f}, p = {np.exp(-S):.3g}\")\n",
    "# TODO: your code here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e38057a2",
   "metadata": {},
   "source": [
    "## H. Homework\n",
    "1. Monday's first slide, bottom light curve (amplitude 0.1): LS psd peak, single-frequency and global false-alarm probability, Bayesian $p(f|D)$. Is it periodic? Give numbers.\n",
    "2. Full X-ray analysis of one provided observation (C5), with a one-paragraph report.\n",
    "3. One OGLE light curve (E4): sparse vs dense cadence.\n",
    "4. Your own Gregory–Loredo (D) or its magnitude version (E4) on one OGLE source, with a red-noise null."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eda86c51",
   "metadata": {},
   "outputs": [],
   "source": [
    "t_h, (y1, y2, y3) = sd.monday_hook()\n",
    "plt.errorbar(t_h, y3, 0.4, fmt=\"o\", ms=3); plt.xlabel(\"t\"); plt.title(\"Monday, bottom panel\");"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
