Spaces:
Runtime error

kaksha / artifacts /code /kaksha_physics.py
camphor5's picture
initial upload
a3b68cd verified
Raw History Blame Contribute Delete
6.36 kB
# ============================================================
# B8c: PHYSICAL TRANSIT FIT + FOLDED SCATTER for the visual dashboard
# For each signal: fit batman model (rp/rs, a/rs, b, dt0) to the real folded data,
# limb darkening fixed from Teff, soft prior on a/rs from stellar density.
# Returns everything the Space needs to render star/planet geometry + overlay real data.
# ============================================================
import numpy as np
from scipy.optimize import least_squares
# Approximate quadratic limb-darkening (Kepler/TESS-like broadband) vs Teff. Educational precision only.
_LD_TABLE = np.array([[3000, 0.45, 0.35], [3500, 0.48, 0.30], [4000, 0.56, 0.22], [4500, 0.55, 0.20],
[5000, 0.50, 0.22], [5500, 0.44, 0.25], [5800, 0.40, 0.26], [6500, 0.33, 0.30],
[7500, 0.25, 0.32], [9000, 0.18, 0.33]])
def limb_darkening(teff):
if teff is None or not np.isfinite(teff): teff = 5800.0
teff = float(np.clip(teff, 3000, 9000))
return float(np.interp(teff, _LD_TABLE[:, 0], _LD_TABLE[:, 1])), float(np.interp(teff, _LD_TABLE[:, 0], _LD_TABLE[:, 2]))
def a_rs_from_density(period_d, rho_gcc):
"""a/R* = (G rho P^2 / 3pi)^(1/3); with rho in g/cc, P in days -> 3.753 * rho^(1/3) * P^(2/3). Sun-Earth -> 215."""
if rho_gcc is None or not np.isfinite(rho_gcc) or rho_gcc <= 0: return np.nan
return 3.753 * rho_gcc ** (1 / 3) * period_d ** (2 / 3)
def a_rs_from_kepler3(period_d, smass, srad):
"""Kepler's 3rd law: a[AU] = (M P_yr^2)^(1/3); a/R* = a[AU]*215.03/R*."""
if not (np.isfinite(smass) and np.isfinite(srad)) or smass <= 0 or srad <= 0: return np.nan
return float((smass * (period_d / 365.25) ** 2) ** (1 / 3) * 215.03 / srad)
def mass_from_logg(logg, srad):
if not (np.isfinite(logg) and np.isfinite(srad)): return np.nan
return float(10 ** (logg - 4.438) * srad ** 2)
def fit_transit(t, flat, period, t0, dur_h, teff=np.nan, srad=np.nan, smass=np.nan, srho=np.nan,
cadence_min=2.0, n_scatter=600, seed=42):
"""Returns dict with fitted geometry, derived quantities, folded scatter and model curve; None if not fittable."""
import batman
t = np.asarray(t, float); flat = np.asarray(flat, float)
dur_d = float(dur_h) / 24.0; win = 3.0 * dur_d
ph = ((t - t0 + 0.5 * period) % period) - 0.5 * period # days from mid-transit
m = np.abs(ph) < win
if m.sum() < 30: return None
x, y = ph[m], flat[m]
# ---- bin for the fit (<=400 points), weights from counts
nb = int(min(400, max(60, m.sum() // 5)))
edges = np.linspace(-win, win, nb + 1); idx = np.digitize(x, edges) - 1; ok = (idx >= 0) & (idx < nb)
c = np.bincount(idx[ok], minlength=nb); s = np.bincount(idx[ok], weights=y[ok], minlength=nb)
xs = np.bincount(idx[ok], weights=x[ok], minlength=nb); mm = c > 0
xb, yb, cb = xs[mm] / c[mm], s[mm] / c[mm], c[mm]
oot = np.abs(x) > 1.5 * dur_d
sig1 = 1.4826 * np.median(np.abs(y[oot] - np.median(y[oot]))) if oot.sum() > 20 else np.std(y)
sig1 = max(sig1, 1e-6); w = np.sqrt(cb) / sig1
# ---- initial guesses + prior
u1, u2 = limb_darkening(teff)
core = np.abs(xb) < 0.3 * dur_d
depth0 = max(1e-6, 1 - np.median(yb[core])) if core.sum() else 1e-4
rp0 = float(np.clip(np.sqrt(depth0), 0.005, 0.4))
a_prior = a_rs_from_density(period, srho)
a0 = a_prior if np.isfinite(a_prior) else period / (np.pi * dur_d)
a0 = float(np.clip(a0, 1.6, 800))
p = batman.TransitParams(); p.t0, p.per, p.rp, p.a, p.inc = 0.0, period, rp0, a0, 89.0
p.ecc, p.w, p.u, p.limb_dark = 0.0, 90.0, [u1, u2], "quadratic"
if cadence_min > 5: tm = batman.TransitModel(p, xb, supersample_factor=7, exp_time=cadence_min / 1440.0)
else: tm = batman.TransitModel(p, xb)
def model(theta, tmodel=tm):
rp, a, b, dt = theta
p.rp, p.a, p.t0 = rp, a, dt; p.inc = float(np.degrees(np.arccos(np.clip(b / a, 0, 0.999))))
return tmodel.light_curve(p)
def resid(theta):
r = (model(theta) - yb) * w
if np.isfinite(a_prior): r = np.append(r, (np.log(theta[1]) - np.log(a_prior)) / 0.25)
return r
lo = [1e-3, 1.5, 0.0, -0.5 * dur_d]; hi = [0.5, 1000.0, 1.2, 0.5 * dur_d]
x0 = [rp0, a0, 0.3, 0.0]
try:
res = least_squares(resid, x0, bounds=(lo, hi), max_nfev=500)
except Exception:
return None
rp, a, b, dt = [float(v) for v in res.x]
inc = float(np.degrees(np.arccos(np.clip(b / a, 0, 0.999))))
mod_b = model(res.x); chi2 = float(np.sum(((mod_b - yb) * w) ** 2) / max(1, len(yb) - 4))
# ---- dense model curve (241 pts) for the overlay
xm = np.linspace(-win, win, 241)
tm_dense = batman.TransitModel(p, xm, supersample_factor=7, exp_time=cadence_min / 1440.0) if cadence_min > 5 else batman.TransitModel(p, xm)
ym = model(res.x, tm_dense)
# ---- derived quantities
depth_model = float(1 - ym.min())
grazing = bool(b + rp > 1.0)
T14_h = float(period / np.pi * np.arcsin(np.clip(np.sqrt(max((1 + rp) ** 2 - b ** 2, 0)) / (a * np.sin(np.radians(inc))), 0, 1)) * 24)
rp_earth = rp * srad * 109.2 if np.isfinite(srad) else np.nan
rp_jup = rp * srad * 9.731 if np.isfinite(srad) else np.nan
a_au = a * srad / 215.03 if np.isfinite(srad) else np.nan
teq = float(teff * np.sqrt(1 / (2 * a))) if np.isfinite(teff) else np.nan
# ---- folded scatter (<= n_scatter real points) in hours from mid-transit
rng = np.random.default_rng(seed)
pick = np.arange(len(x)) if len(x) <= n_scatter else np.sort(rng.choice(len(x), n_scatter, replace=False))
return {
"rp_rs": rp, "a_rs": a, "b": b, "inc_deg": inc, "dt0_days": dt, "u1": u1, "u2": u2,
"chi2_red": chi2, "depth_model_ppm": depth_model * 1e6, "T14_h": T14_h, "grazing": grazing,
"a_rs_prior": float(a_prior) if np.isfinite(a_prior) else None,
"a_rs_kepler3": a_rs_from_kepler3(period, smass, srad) if np.isfinite(smass) else None,
"rp_earth": rp_earth, "rp_jup": rp_jup, "a_au": a_au, "teq_k": teq,
"star": {"teff": teff, "srad": srad, "smass": smass, "srho": srho},
"scatter": {"dt_hours": (x[pick] * 24).tolist(), "flux": y[pick].tolist()},
"model": {"dt_hours": (xm * 24).tolist(), "flux": ym.tolist()},
"n_points_in_window": int(len(x)), "window_hours": win * 24,
}