Chris Parmer — home

Light curve / transit

Astronomy — Kepler photometry

Example from the compendium of canonical charts

Astronomy — Light curve / transit (Kepler photometry)

Python Code

"""Astronomy — Light curve / transit (Kepler photometry)."""


import numpy as np
import pandas as pd
import plotly.graph_objects as go

URL = "https://raw.githubusercontent.com/lightkurve/lightkurve/main/tests/data/ep60021426alldiagnostics.csv"


def generate():
    print("fetching Kepler light curve data …")
    try:
        df = fetch_csv(URL)
        print(f"  columns: {list(df.columns)}")
        # Find time and flux columns
        time_col = None
        flux_col = None
        for c in df.columns:
            cl = c.strip().lower()
            if "bjd" in cl or "time" in cl or "cadence" in cl:
                time_col = c
            if "corrected" in cl and "flux" in cl:
                flux_col = c
        if time_col is None:
            time_col = df.columns[0]
        if flux_col is None:
            for c in df.columns:
                if "flux" in c.lower():
                    flux_col = c
                    break
        if flux_col is None:
            flux_col = df.columns[1]
        print(f"  using time={time_col!r}, flux={flux_col!r}")
        df = df[[time_col, flux_col]].copy()
        df.columns = ["time", "flux"]
        df["flux"] = pd.to_numeric(df["flux"], errors="coerce")
        df["time"] = pd.to_numeric(df["time"], errors="coerce")
        df = df.dropna()
        used_synthetic = False
    except Exception as e:
        print(f"  fetch failed ({e}); generating synthetic Kepler-like light curve")
        used_synthetic = True
        rng = np.random.default_rng(42)
        n = 3000
        time = np.linspace(200, 270, n)
        flux = 1.0 + rng.normal(0, 0.001, n)
        # inject transits with period ~8 days, depth ~0.015
        period = 8.0
        t0 = 204.5
        duration = 0.2
        for k in range(10):
            tc = t0 + k * period
            in_transit = np.abs((time - tc + period / 2) % period - period / 2) < duration / 2
            flux[in_transit] -= 0.015
        df = pd.DataFrame({"time": time, "flux": flux})

    # normalize flux around 1 if it's not already
    median_flux = df["flux"].median()
    if abs(median_flux) > 10:
        df["flux"] = df["flux"] / median_flux

    fig = go.Figure([
        go.Scatter(
            x=df["time"],
            y=df["flux"],
            mode="markers",
            marker=dict(size=5, opacity=0.7, color=VIOLET),
            hovertemplate="t=%{x:.3f}<br>flux=%{y:.5f}<extra></extra>",
        )
    ])
    fig.update_layout(
        xaxis=dict(title="Time (BJD − 2454833)"),
        yaxis=dict(title="Corrected Flux"),
        margin=dict(t=40, b=60, l=70, r=40),
        height=500,
    )
    return fig


if __name__ == "__main__":
    generate()

Made with Plotly