def setup(gp=True): client = kplr.API() # Query the KIC and get some parameters. # kic = client.star(8415109) # Bright variable. kic = client.star(2301306) # Quiet G-type. teff, logg, feh = kic.kic_teff, kic.kic_logg, kic.kic_feh assert teff is not None # Get the limb darkening law. mu1, mu2 = get_quad_coeffs(teff, logg=logg, feh=feh) bins = np.linspace(0, 1, 50)[1:] ** 0.5 ldp = bart.ld.QuadraticLimbDarkening(mu1, mu2).histogram(bins) # Build the star object. star = bart.Star(ldp=ldp) # Set up the planet. period = 278. size = 0.03 epoch = 20.0 a = star.get_semimajor(period) b = 0.3 incl = np.degrees(np.arctan2(a, b)) planet = bart.Planet(size, a, t0=epoch) # Set up the system. ps = bart.PlanetarySystem(star, iobs=incl) ps.add_planet(planet) # Load the data and inject into each transit. lcs = kic.get_light_curves(short_cadence=False, fetch=False) datasets = [] for lc in lcs: with lc.open() as f: # The light curve data are in the first FITS HDU. hdu_data = f[1].data time_, flux_, ferr_, quality = [hdu_data[k] for k in ["time", "sap_flux", "sap_flux_err", "sap_quality"]] # Mask the missing data. mask = (np.isfinite(time_) * np.isfinite(flux_) * np.isfinite(ferr_) * (quality == 0)) time_, flux_, ferr_ = [v[mask] for v in [time_, flux_, ferr_]] # Inject the transit. flux_ *= ps.lightcurve(time_) mu = np.median(flux_) datasets.append(bart.data.LightCurve(time_, flux_ / mu, ferr_ / mu)) return datasets, period
def inject(kicid): print(kicid) np.random.seed(int(kicid)) # Get the KIC entry. kic = client.star(kicid) teff, logg, feh = kic.kic_teff, kic.kic_logg, kic.kic_feh assert teff is not None # Get the limb darkening law. mu1, mu2 = get_quad_coeffs(teff, logg=logg, feh=feh) bins = np.linspace(0, 1, 50)[1:] ** 0.5 ldp = bart.ld.QuadraticLimbDarkening(mu1, mu2).histogram(bins) # Build the star object. star = bart.Star(ldp=ldp) # Set up the planet. period = 365 + 30 * np.random.randn() size = 0.005 + 0.02 * np.random.rand() epoch = period * np.random.rand() a = star.get_semimajor(period) b = np.random.rand() incl = np.degrees(np.arctan2(a, b)) planet = bart.Planet(size, a, t0=epoch) # Set up the system. ps = bart.PlanetarySystem(star, iobs=incl) ps.add_planet(planet) # Make sure that that data directory exists. base_dir = os.path.join(output_path, "{0}".format(kicid)) try: os.makedirs(base_dir) except os.error: pass # Save the injected values. with open(os.path.join(base_dir, "truth.txt"), "w") as f: f.write("# " + ",".join(["r/R", "b", "incl", "period", "epoch"]) + "\n") f.write(",".join(map("{0}".format, [size, b, incl, period, epoch]))) f.write("\n") # Load the data and inject into each transit. lcs = kic.get_light_curves(short_cadence=False) for lc in lcs: with lc.open() as f: # The light curve data are in the first FITS HDU. hdu_data = f[1].data # Load the data columns. time = hdu_data["time"] sap_flux = hdu_data["sap_flux"] sap_ferr = hdu_data["sap_flux_err"] pdc_flux = hdu_data["pdcsap_flux"] pdc_ferr = hdu_data["pdcsap_flux_err"] quality = hdu_data["sap_quality"] # Mask out missing data. inds = ~(np.isnan(time) + np.isnan(sap_flux)) pdcinds = ~(np.isnan(time) + np.isnan(pdc_flux)) # Inject the transit into the SAP and PDC light curves. sap_flux[inds] *= ps.lightcurve(time[inds]) pdc_flux[pdcinds] *= ps.lightcurve(time[pdcinds]) # Coerce the filename. fn = os.path.splitext(os.path.split(lc.filename)[1])[0] + ".txt" with open(os.path.join(base_dir, fn), "w") as f: f.write("# " + ",".join(["time", "sap_flux", "sap_ferr", "pdc_flux", "pdc_ferr", "quality"]) + "\n") for line in zip(time, sap_flux, sap_ferr, pdc_flux, pdc_ferr, quality): f.write(",".join(map("{0}".format, line)) + "\n") return None
l2=1.0, period=period, t0=t0, dt=dt).autosplit() else: continue datasets += bart.data.LightCurve(data["time"], data["sap_flux"], data["sap_flux_err"], period=period, t0=t0, texp=kplr.EXPOSURE_TIMES[0], dt=dt).autosplit() # Get the limb darkening profile. kic = koi.star teff, logg, feh = kic.kic_teff, kic.kic_logg, kic.kic_feh assert teff is not None mu1, mu2 = get_quad_coeffs(teff, logg=logg, feh=feh) bins = np.linspace(0, 1, 50)[1:] ** 0.5 ldp = bart.ld.QuadraticLimbDarkening(mu1, mu2, bins=bins) # Set up the star. star = bart.Star(ldp=ldp) # Set up the planet. a = star.get_semimajor(period) incl = np.degrees(np.arctan2(a, 0.883)) # This looks better than KOI. planet = bart.Planet(0.069, a, t0=t0, ix=90.-incl) # Same. # Figure out the transit timing ranges. ranges = [(np.min(d.time), np.max(d.time)) for d in datasets] # Set up the system/model.
def kepler_injection(kicid, period, size, b=0.0, pdc=False, cleaner=default_cleaner, **planet_params): """ Inject a transit into a particular KIC target. This function depends on the `kplr <http://dan.iel.fm/kplr>`_ module to download the raw light curves from MAST. :param kicid: The index of the target in the KIC. :param period: The period of the orbit in days. :param size: The radius of the planet relative to the star. :param b: The impact parameter of the observed transit in stellar radii. (default: 0.0) :param pdc: Should the transit be injected into the PDC data? If not, use SAP. (default: False) :param cleaner: A function that performs any data munging that you want. The default just masks NaNs and removes any data with non-zero quality mask. The function should take 4 (numpy array) arguments: time, flux, uncertainty, and quality. It should return 3 arrays: time, flux, and uncertainty. :param **planet_params: Any other keyword arguments to pass when building the :class:`Planet`. :returns datasets: A list of :class:`data.GPLightCurve` datasets with the transit injected into the flux. :returns ps: The :class:`PlanetarySystem` used to generate the transit. """ if kplr is None: raise ImportError("You need to install kplr (http://dan.iel.fm/kplr) " "before doing a Kepler injection.") # Get the stellar information from the API. client = kplr.API() kic = client.star(kicid) teff, logg, feh = kic.kic_teff, kic.kic_logg, kic.kic_feh assert teff is not None # Get an approximate limb darkening law. mu1, mu2 = get_quad_coeffs(teff, logg=logg, feh=feh) bins = np.linspace(0, 1, 50)[1:] ** 0.5 ldp = ld.QuadraticLimbDarkening(mu1, mu2, bins) # Build the star object. star = Star(ldp=ldp) # Set up the planet. planet = Planet(r=size, period=period, **planet_params) # Set up the system. ps = PlanetarySystem(star) ps.add_planet(planet) # Download the data and inject transits. if pdc: cols = ["time", "pdcsap_flux", "pdcsap_flux_err", "sap_quality"] else: cols = ["time", "sap_flux", "sap_flux_err", "sap_quality"] datasets = [] lcs = kic.get_light_curves(short_cadence=False, fetch=False) for lc in lcs: try: with lc.open() as f: # The light curve data are in the first FITS HDU. hdu_data = f[1].data time, flux, ferr, quality = [hdu_data[k] for k in cols] except urllib2.HTTPError: print("Couldn't find {0}".format(lc.url)) continue # Inject the transit. m = np.isfinite(time) * np.isfinite(flux) flux[m] *= ps.light_curve(time[m]) # Clean the data using the provided callback and save the dataset. time, flux, ferr = cleaner(time, flux, ferr, quality) datasets += data.LightCurve(time, flux, ferr).autosplit() return datasets, ps
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import json import kplr from kplr.ld import get_quad_coeffs koi_number = "319.01" client = kplr.API(data_root=".") koi = client.koi(koi_number) # Save the KOI properties. json.dump(koi.params, open("koi.json", "w"), indent=4, sort_keys=True, separators=(",", ": ")) # Download the light curves. lcs = koi.get_light_curves(fetch=True, short_cadence=False) # Save the paths to the datasets. with open("filenames.txt", "w") as f: f.write("\n".join([d.filename for d in lcs])) # Compute the fiducial limb darkening coefficients. mu1, mu2 = get_quad_coeffs(koi.koi_steff) open("ld.txt", "w").write("{0} {1}".format(mu1, mu2))
def setup(gp=True): client = kplr.API() # Query the KIC and get some parameters. kic = client.star(7364176) teff, logg, feh = kic.kic_teff, kic.kic_logg, kic.kic_feh assert teff is not None # Get the limb darkening law. mu1, mu2 = get_quad_coeffs(teff, logg=logg, feh=feh) bins = np.linspace(0, 1, 50)[1:] ** 0.5 ldp = bart.ld.QuadraticLimbDarkening(mu1, mu2).histogram(bins) # Build the star object. star = bart.Star(ldp=ldp) # Set up the planet. prng = 5.0 period = 272.1884457597957407 size = 0.01 epoch = 103.7235285266694973 + 0.265 a = star.get_semimajor(period) b = 0.1 incl = np.degrees(np.arctan2(a, b)) planet = bart.Planet(size, a, t0=epoch) # Set up the system. ps = bart.PlanetarySystem(star, iobs=incl) ps.add_planet(planet) # Initialize the model. model = bart.Model(ps) # Load the data and inject into each transit. lcs = kic.get_light_curves(short_cadence=False, fetch=False) # Loop over the datasets and read in the data. minn, maxn = 1e10, 0 for lc in lcs: with lc.open() as f: # The light curve data are in the first FITS HDU. hdu_data = f[1].data time_, flux_, ferr_, quality = [hdu_data[k] for k in ["time", "sap_flux", "sap_flux_err", "sap_quality"]] # Mask the missing data. mask = (np.isfinite(time_) * np.isfinite(flux_) * np.isfinite(ferr_) * (quality == 0)) time_, flux_, ferr_ = [v[mask] for v in [time_, flux_, ferr_]] # Cut out data near transits. hp = 0.5 * period inds = np.abs((time_ - epoch + hp) % period - hp) < prng if not np.sum(inds): continue time_, flux_, ferr_ = [v[inds] for v in [time_, flux_, ferr_]] # Inject the transit. flux_ *= ps.lightcurve(time_) tn = np.array(np.round(np.abs((time_ - epoch) / period)), dtype=int) alltn = set(tn) maxn = max([maxn, max(alltn)]) minn = min([minn, min(alltn)]) for n in alltn: m = tn == n tf = time_[m] fl = flux_[m] fle = ferr_[m] if not gp: mu = untrendy.median(tf, fl, dt=4.0) fl /= mu fle /= mu model.datasets.append(dsc(tf, fl, fle, alpha=1.0, l2=3.0, dtbin=None)) # Add some priors. dper = prng / (maxn - minn) # Add some parameters. model.parameters.append(Parameter(planet, "t0")) model.parameters.append(Parameter(planet, "r")) model.parameters.append(ImpactParameter(planet)) # Prior range for the period so that it doesn't predict transits outside # of the data range. ppr = UniformPrior(period - dper, period + dper) model.parameters.append(PeriodParameter(planet, lnprior=ppr)) return model, period
# Load the light curves. lcs = kic.get_light_curves(short_cadence=False) datasets = [] for lc in lcs: with lc.open() as f: data = f[1].data longcadence = f[0].header.get("obsmode") == "long cadence" datasets += GPLightCurve(data["time"] + kplr.KBJD_ZERO - zero, data["sap_flux"], data["sap_flux_err"]).autosplit() datasets = [ds for ds in datasets if len(ds.time) > 10] # Get the limb darkening profile. mu1, mu2 = get_quad_coeffs(5911) bins = np.linspace(0, 1, 50)[1:] ** 0.5 ldp = bart.ld.QuadraticLimbDarkening(mu1, mu2, bins=bins) # Initialize the star. star = bart.Star(mass=1.071, radius=1.626, ldp=ldp) # Set up the planets. pb = bart.Planet(t0=2454960.9753-zero, period=13.83989, r=9.155e-3*2.486, mass=3.003467e-6*4.45) pc = bart.Planet(t0=2454955.9132-zero, period=16.23855, r=9.155e-3*4.679, mass=3.003467e-6*8.08) # Put the system together. ps = bart.NBodySystem(star) ps.add_planet(pb)
import emcee import triangle import numpy as np import scipy.optimize as op import matplotlib.pyplot as pl from kplr.ld import get_quad_coeffs import bart from bart.priors import UniformPrior, NormalPrior from bart.parameters import Parameter, LogParameter np.random.seed(123) # Set up limb darkening. mu1, mu2 = get_quad_coeffs(5647.0, logg=4.236, feh=0.34) ldp = bart.ld.QuadraticLimbDarkening(mu1, mu2) # Build the star. star = bart.Star(mass=1.209, radius=1.391, ldp=ldp) # Build the planet. planet = bart.Planet(r=0.09829*star.radius, period=3.234723, b=0.398) planet.t0 = 0.5*planet.period # Put them together in a planetary system. kepler6 = bart.PlanetarySystem(star) kepler6.add_planet(planet) # Check to make sure that the inferred orbital parameters are reasonable. print("a/R_star = {0}".format(planet.a / star.radius))
def setup(gp=True): client = kplr.API() # Query the KIC and get some parameters. # kic = client.star(8415109) # Bright variable. kic = client.star(2301306) # Quiet G-type. teff, logg, feh = kic.kic_teff, kic.kic_logg, kic.kic_feh assert teff is not None # Get the limb darkening law. mu1, mu2 = get_quad_coeffs(teff, logg=logg, feh=feh) bins = np.linspace(0, 1, 50)[1:] ** 0.5 ldp = bart.ld.QuadraticLimbDarkening(mu1, mu2).histogram(bins) # Build the star object. star = bart.Star(ldp=ldp) # Set up the planet. prng = 3.0 period = 278. size = 0.03 epoch = 20.0 a = star.get_semimajor(period) b = 0.3 incl = np.degrees(np.arctan2(a, b)) planet = bart.Planet(size, a, t0=epoch) # Set up the system. ps = bart.PlanetarySystem(star, iobs=incl) ps.add_planet(planet) # Initialize the model. model = bart.Model(ps) # Load the data and inject into each transit. lcs = kic.get_light_curves(short_cadence=False, fetch=False) # Choose the type of dataset to use. if gp: args = {"alpha": 1.0, "l2": 3.0, "dtbin": None} dsc = bart.data.GPLightCurve else: args = {"dtbin": None} dsc = bart.data.LightCurve # Loop over the datasets and read in the data. minn, maxn = 1e10, 0 for lc in lcs: with lc.open() as f: # The light curve data are in the first FITS HDU. hdu_data = f[1].data time_, flux_, ferr_, quality = [hdu_data[k] for k in ["time", "sap_flux", "sap_flux_err", "sap_quality"]] # Mask the missing data. mask = (np.isfinite(time_) * np.isfinite(flux_) * np.isfinite(ferr_) * (quality == 0)) time_, flux_, ferr_ = [v[mask] for v in [time_, flux_, ferr_]] # Cut out data near transits. hp = 0.5 * period inds = np.abs((time_ - epoch + hp) % period - hp) < prng if not np.sum(inds): continue time_, flux_, ferr_ = [v[inds] for v in [time_, flux_, ferr_]] # Inject the transit. flux_ *= ps.lightcurve(time_) if not gp: mu = untrendy.median(time_, flux_, dt=3.0) flux_ /= mu ferr_ /= mu tn = np.array(np.round(np.abs((time_ - epoch) / period)), dtype=int) alltn = set(tn) maxn = max([maxn, max(alltn)]) minn = min([minn, min(alltn)]) for n in alltn: m = tn == n tf = time_[m] fl = flux_[m] fle = ferr_[m] model.datasets.append(dsc(tf, fl, fle, **args)) # Add some priors. dper = prng / (maxn - minn) # Add some parameters. model.parameters.append(Parameter(planet, "t0")) model.parameters.append(Parameter(planet, "r")) model.parameters.append(ImpactParameter(planet)) # Prior range for the period so that it doesn't predict transits outside # of the data range. ppr = UniformPrior(period - dper, period + dper) model.parameters.append(PeriodParameter(planet, lnprior=ppr)) # # Sample in the GP hyper-parameters. # apr = UniformPrior(0.0, 10.0) # model.parameters.append(MultiParameter(model.datasets, "alpha", # lnprior=apr)) # lpr = UniformPrior(3.0, 20.0) # model.parameters.append(MultiParameter(model.datasets, "l2", # lnprior=lpr)) return model, period