### Install TransitLeastSquares from GitHub Source: https://github.com/hippke/tls/blob/master/README.md Install the latest development version of TransitLeastSquares directly from the GitHub repository. This method requires Git to be installed. ```bash git clone https://github.com/hippke/tls.git cd tls python setup.py install ``` ```bash python3 setup.py install ``` -------------------------------- ### Install TLS from GitHub with python3 Source: https://github.com/hippke/tls/blob/master/docs/source/Installation.md If 'python' on your system does not point to Python 3, use 'python3 setup.py install' when installing TLS from the GitHub repository. ```bash git clone https://github.com/hippke/tls.git cd tls python3 setup.py install ``` -------------------------------- ### Install TransitLeastSquares using pip Source: https://github.com/hippke/tls/blob/master/README.md Install the latest stable version of the TransitLeastSquares package using pip. This is the recommended installation method for most users. ```bash pip install transitleastsquares ``` ```bash pip3 install transitleastsquares ``` -------------------------------- ### Install TLS from GitHub Source: https://github.com/hippke/tls/blob/master/docs/source/Installation.md Clone the TLS repository from GitHub and install it directly from the source. This is useful for development or when needing the absolute latest code. ```bash git clone https://github.com/hippke/tls.git cd tls python setup.py install ``` -------------------------------- ### TLS Configuration File Structure Source: https://github.com/hippke/tls/blob/master/docs/source/Command.md This is an example configuration file for TLS. It includes sections for grid search parameters, transit template, speed settings, and file handling. ```ini [Grid] R_star = 1 R_star_min = 0.8 R_star_max = 1.2 M_star = 1 M_star_min = 0.8 M_star_max = 1.2 period_min = 0 period_max = 1e10 n_transits_min = 3 [Template] transit_template = default [Speed] duration_grid_step = 1.1 transit_depth_min = 10e-6 oversampling_factor = 2 T0_fit_margin = 0.01 use_threads = 4 [File] delimiter = , ``` -------------------------------- ### TLS Maximum Command Line Usage Source: https://github.com/hippke/tls/blob/master/docs/source/Command.md An example demonstrating the use of optional configuration and output file arguments with the transitleastsquares command. ```bash transitleastsquares test_data.csv --config=tls_config.cfg --output=results.csv ``` -------------------------------- ### Install TLS using pip Source: https://github.com/hippke/tls/blob/master/docs/source/Installation.md Use this command to install the latest stable version of TLS from PyPI. Ensure you are using the correct pip for your Python environment. ```bash pip install transitleastsquares ``` -------------------------------- ### TLS Minimum Command Line Usage Source: https://github.com/hippke/tls/blob/master/docs/source/Command.md A basic example of calling the transitleastsquares command with only the required lightcurve file. ```bash transitleastsquares test_data.csv ``` -------------------------------- ### Install TLS using pip3 Source: https://github.com/hippke/tls/blob/master/docs/source/Installation.md If you have multiple Python versions, use pip3 to ensure TLS is installed for Python 3. This is the recommended approach for Python 3 environments. ```bash pip3 install transitleastsquares ``` -------------------------------- ### Import Libraries for TESS Data Analysis Source: https://github.com/hippke/tls/blob/master/tutorials/11 A planet from TESS with TLS.ipynb Imports necessary libraries for plotting, astronomical data handling, and transit least squares analysis. Ensure these libraries are installed before running. ```python import matplotlib.pyplot as plt; plt.rcParams["figure.dpi"] = 150 import astropy import numpy from astropy.io import fits from astropy.stats import sigma_clip from transitleastsquares import ( transitleastsquares, cleaned_array, catalog_info, transit_mask ) ``` -------------------------------- ### TLS Transit Least Squares Initialization Source: https://github.com/hippke/tls/blob/master/tutorials/10 Measurement uncertainties.ipynb Initializes the Transit Least Squares (TLS) algorithm for analyzing light curve data. This output indicates the start of the search process, including the number of data points and periods to be analyzed. ```text Transit Least Squares TLS 1.0.16 (29 January 2019) Creating model cache for 39 durations Searching 13149 data points, 1781 periods from 300.025 to 399.939 days Using all 8 CPU threads ``` -------------------------------- ### Create Synthetic Data for Transit Analysis Source: https://github.com/hippke/tls/blob/master/tutorials/08 Edge effect jitter correction.ipynb Generates synthetic time-series data with injected transits and noise using numpy and batman. This data is used to compare TLS and BLS performance. Ensure numpy, batman, and transitleastsquares are installed. ```python import numpy import batman from transitleastsquares import transitleastsquares, period_grid from astropy.stats import BoxLeastSquares # Create empty time series to inject transits and noise numpy.random.seed(seed=0) # reproducibility start = 12 days = 365.25 * 3 samples_per_day = 12 samples = int(days * samples_per_day) t = numpy.linspace(start, start + days, samples) # Use batman to create transits ma = batman.TransitParams() ma.t0 = start + 20 # time of inferior conjunction; first transit is X days after start ma.per = 365.25 # orbital period ma.rp = 6371 / 696342 # 6371 planet radius (in units of stellar radii) ma.a = 217 # semi-major axis (in units of stellar radii) ma.inc = 90 # orbital inclination (in degrees) ma.ecc = 0 # eccentricity ma.w = 90 # longitude of periastron (in degrees) ma.u = [0.5, 0.5] # limb darkening coefficients ma.limb_dark = "quadratic" # limb darkening model m = batman.TransitModel(ma, t) # initializes model original_flux = m.light_curve(ma) # calculates light curve # Create noise and merge with flux ppm = 5 stdev = 10**-6 * ppm noise = numpy.random.normal(0, stdev, int(samples)) y = original_flux + noise y_box = numpy.copy(y) t_box = numpy.copy(t) ``` -------------------------------- ### Run TLS with Grazing and Box Transit Templates Source: https://github.com/hippke/tls/blob/master/tutorials/05 Custom transit shapes - Example of the grazing planet WASP-75.ipynb Initializes and runs the Transit Least Squares (TLS) algorithm with both a 'grazing' and a 'box' transit template. This allows for a direct comparison of how different transit shapes affect the detection and characterization of planetary signals. ```python from transitleastsquares import transitleastsquares model_grazing = transitleastsquares(t, y_filt) results_grazing = model_grazing.power( transit_template='grazing') model_box = transitleastsquares(t, y_filt) results_box= model_box.power( transit_template='box') from matplotlib import rcParams; rcParams["figure.dpi"] = 150 ax.get_yaxis().set_tick_params(which='both', direction='out') ax.get_xaxis().set_tick_params(which='both', direction='out') plt.plot( results_grazing.model_folded_phase, results_grazing.model_folded_model, color='red') plt.scatter( results_grazing.folded_phase, results_grazing.folded_y, color='blue', s=10, alpha=0.5, zorder=2) plt.plot( results_box.model_folded_phase, results_box.model_folded_model, color='orange') plt.xlim(0.45, 0.55) plt.ylim(0.99, 1.001) plt.xlabel('Phase') plt.ylabel('Relative flux'); ``` -------------------------------- ### Plot TLS Periodogram Source: https://github.com/hippke/tls/blob/master/tutorials/08 Edge effect jitter correction.ipynb Visualizes the power spectrum obtained from the TLS search. This plot helps in identifying potential periodic signals in the data. Requires matplotlib to be installed. ```python import matplotlib.pyplot as plt from matplotlib import rcParams; rcParams["figure.dpi"] = 150 fig, axes = plt.subplots(1, 2, sharey=True, figsize=(5, 3)) # TLS axes[0].plot( results.periods, results.power - numpy.median(results.power), color='black', lw=0.5) axes[0].set_ylabel(r'SDE') axes[0].set_xlabel('Period (days)') axes[0].set_xlim(min(results.periods), max(results.periods)) ``` -------------------------------- ### TLS Transit Search Initialization and Parameters Source: https://github.com/hippke/tls/blob/master/tutorials/07 The influence of limb darkening values.ipynb Shows the initialization of the Transit Least Squares (TLS) search, including the version, model cache creation, data points and periods searched, and CPU thread usage. ```text Signal detection efficiency (SDE), catalog value LDs: 20.51699 Transit Least Squares TLS 1.0.22 (15 February 2019) Creating model cache for 35 durations Searching 3405 data points, 7790 periods from 0.601 to 36.992 days Using all 8 CPU threads ``` -------------------------------- ### Calculate Optimal Period Grid Density Source: https://github.com/hippke/tls/blob/master/tutorials/09 Optimal period grid and optimal duration grid.ipynb Calculates and visualizes the number of trial periods generated by the optimal period grid for different stellar masses and data time spans. This demonstrates how the optimal grid adapts sampling density. ```python from transitleastsquares import period_grid import numpy import matplotlib.pyplot as plt # Main sequence stars with masses and radii R = numpy.array([0.13, 0.32, 0.63, 0.74, 0.85, 0.93, 1, 1.05, 1.2, 1.3]) M = numpy.array([0.1, 0.21, 0.47, 0.69, 0.78, 0.93, 1, 1.1, 1.3, 1.7]) p10d = [] p100d = [] p1000d = [] for i in range(len(R)): p10d.append(len(period_grid(R[i], M[i], 10))) p100d.append(len(period_grid(R[i], M[i], 100))) p1000d.append(len(period_grid(R[i], M[i], 1000))) plt.plot(M, p10d, color='black', lw=0.5) plt.plot(M, p100d, color='black', lw=0.5) plt.plot(M, p1000d, color='black', lw=0.5) plt.text(0.75, 1.2*10**5, '1000 days') plt.text(0.75, 10**4, '100 days') plt.text(0.75, 0.7*10**3, '10 days') plt.yscale('log') plt.xlim(0, 1.7) plt.ylabel(r'Number of trial periods') plt.xlabel(r'Stellar mass ($M_{\odot}$)'); ``` -------------------------------- ### TLS Command Line Syntax Source: https://github.com/hippke/tls/blob/master/docs/source/Command.md Use this syntax to call the transitleastsquares command. Specify input lightcurve and optional output and config files. ```bash transitleastsquares [-h] [-o OUTPUT] [-c CONFIG] lightcurve ``` -------------------------------- ### Run Transit Least Squares (TLS) Source: https://github.com/hippke/tls/blob/master/tutorials/06 Comparison between TLS and BLS.ipynb Initializes and runs the Transit Least Squares algorithm to detect periodic transit signals in the prepared light curve data. This step identifies potential exoplanet candidates by analyzing the power spectrum. ```python from transitleastsquares import transitleastsquares model = transitleastsquares(t, y_filt) results = model.power() ``` -------------------------------- ### Search Data with TLS and BLS Source: https://github.com/hippke/tls/blob/master/tutorials/08 Edge effect jitter correction.ipynb Performs a transit search on the synthetic data using both the Transit Least Squares (TLS) and the standard Box Least Squares (BLS) algorithms. This allows for a direct comparison of their periodograms and detection capabilities. Ensure transitleastsquares and astropy are installed. ```python # Search with TLS model = transitleastsquares(t, y) results = model.power( period_min=360, period_max=370, transit_depth_min=ppm*10**-6, oversampling_factor=10, duration_grid_step=1.02, u=[0.4, 0.4], limb_dark='quadratic', M_star = 1, M_star_max=1.1 ) # Search with BLS periods = period_grid( R_star=1, M_star=1, time_span=(max(t) - min(t)), period_min=360, # 10.04 period_max=370, # 10.05 oversampling_factor=10) durations = numpy.linspace(0.2, 0.7, 50) model = BoxLeastSquares(t_box, y_box) results_bls = model.power(periods, durations) # Flatten the BLS periodogram for comparability chi2 = 1 / results_bls.power SR = min(chi2) / chi2 SDE = (1 - numpy.mean(SR)) / numpy.std(SR) SDE_power = SR - numpy.min(SR) # shift down to touch 0 scale = SDE / numpy.max(SDE_power) # scale factor to touch max=SDE SDE_power = SDE_power * scale ``` -------------------------------- ### Run Transit Least Squares (TLS) Analysis Source: https://github.com/hippke/tls/blob/master/tutorials/01 Quick start with synthetic data.ipynb Initializes and runs the Transit Least Squares algorithm on time-series data. This is the core step for detecting transits. Requires the time and flux arrays. ```python from transitleastsquares import transitleastsquares model = transitleastsquares(time, flux) results = model.power() ``` -------------------------------- ### Run Transit Least Squares (TLS) and Plot Periodogram Source: https://github.com/hippke/tls/blob/master/tutorials/03 Multiple planets - K2-3, a red dwarf with 3 Super-Earths.ipynb Applies the TLS algorithm to find exoplanet periods and visualizes the resulting periodogram. Identifies potential transit periods and their harmonics. ```python model_third_run = transitleastsquares(t_third_run, y_third_run) results_third_run = model_third_run.power() plt.figure() ax = plt.gca() ax.axvline(results_third_run.period, alpha=0.4, lw=3) plt.xlim(numpy.min(results_third_run.periods), numpy.max(results_third_run.periods)) for n in range(2, 10): ax.axvline(n*results_third_run.period, alpha=0.4, lw=1, linestyle="dashed") ax.axvline(results_third_run.period / n, alpha=0.4, lw=1, linestyle="dashed") plt.ylabel(r'SDE') plt.xlabel('Period (days)') plt.plot(results_third_run.periods, results_third_run.power, color='black', lw=0.5) plt.xlim(0, max(results_third_run.periods)); ``` -------------------------------- ### Fetch Stellar Parameters from Catalog Source: https://github.com/hippke/tls/blob/master/tutorials/07 The influence of limb darkening values.ipynb Retrieves stellar mass, radius, and quadratic limb darkening parameters for a given EPIC ID from the exoplanet catalog. Useful for initializing transit models with known stellar properties. ```python from transitleastsquares import transitleastsquares, catalog_info, cleaned_array EPIC_id = 211351816 ab, mass, mass_min, mass_max, radius, radius_min, radius_max = catalog_info(EPIC_id) print('Stellar mass', mass) print('Stellar radius', radius) print('Quadratic LD parameters (a,b)=', ab) ``` -------------------------------- ### Run TLS with Non-Uniform Noise (With Uncertainties) Source: https://github.com/hippke/tls/blob/master/tutorials/10 Measurement uncertainties.ipynb Re-runs the TLS algorithm, this time providing the estimated measurement uncertainties (`dy`) along with the light curve data. This demonstrates how TLS accounts for non-uniform noise when uncertainties are provided. Requires transitleastsquares and numpy. ```python from transitleastsquares import transitleastsquares import numpy model = transitleastsquares(t, y, dy) # <== Here, the uncertainties are added results = model.power( period_min=300, period_max=400, oversampling_factor=3, duration_grid_step=1.05, T0_fit_margin=0.2 ) print('SDE non uniform noise, uncertainties used: ', format(results.SDE, '.5f')) ``` -------------------------------- ### Run Transit Least Squares (TLS) Search Source: https://github.com/hippke/tls/blob/master/tutorials/11 A planet from TESS with TLS.ipynb Initializes and runs the TLS power spectrum search for transits. Requires the `transitleastsquares` library. ```python from transitleastsquares import transitleastsquares model = transitleastsquares(time, flux) results = model.power(u=ab) ``` -------------------------------- ### Comparing TLS Search with Different Limb Darkening Models Source: https://github.com/hippke/tls/blob/master/tutorials/07 The influence of limb darkening values.ipynb Performs TLS searches using specific limb darkening models ('quadratic' with catalog values 'ab', and 'quadratic' with Grunblatt+ 2016 values). It prints the SDE for each case to compare their impact. ```python model = transitleastsquares(t, y_filt) results = model.power(limb_dark='quadratic', u=ab) print('Signal detection efficiency (SDE), catalog value LDs:', format(results.SDE, '.5f')) model = transitleastsquares(t, y_filt) results = model.power(limb_dark='quadratic', u=[0.6505,0.1041]) print('Signal detection efficiency (SDE), Grunblatt+ (2016) LDs:', format(results.SDE, '.5f')) ``` -------------------------------- ### Recover Planet b using Transit Least Squares Source: https://github.com/hippke/tls/blob/master/tutorials/03 Multiple planets - K2-3, a red dwarf with 3 Super-Earths.ipynb Initializes the Everest library to download and load K2-3 system data. Filters out bad data points and NaNs, then applies median filtering and sigma clipping to the light curve. Finally, it uses the transitleastsquares library to perform a power spectrum analysis to detect planet b and plots the folded phase. ```python import numpy import scipy import everest from astropy.stats import sigma_clip import matplotlib.pyplot as plt import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('matplotlib') logger.setLevel(logging.CRITICAL) from matplotlib import rcParams; rcParams["figure.dpi"] = 150 EPIC_id = 201367065 star = everest.Everest(EPIC_id) t = numpy.delete(star.time, star.badmask) y = numpy.delete(star.fcor, star.badmask) t = numpy.array(t[~numpy.isnan(y)], dtype='float32') y = numpy.array(y[~numpy.isnan(y)], dtype='float32') trend = scipy.signal.medfilt(y, 25) y_filt = y /trend y_filt = sigma_clip(y_filt, sigma_upper=2, sigma_lower=float('inf')) from transitleastsquares import transitleastsquares model = transitleastsquares(t, y_filt) results = model.power() plt.figure() plt.plot( results.model_folded_phase, results.model_folded_model, color='red') plt.scatter( results.folded_phase, results.folded_y, color='blue', s=10, alpha=0.5, zorder=2) plt.xlim(0.49, 0.51) plt.xlabel('Phase') plt.ylabel('Relative flux'); ``` -------------------------------- ### Loading and Cleaning Astronomical Data with Everest Source: https://github.com/hippke/tls/blob/master/tutorials/07 The influence of limb darkening values.ipynb Loads stellar light curve data using the `everest` library and cleans it by removing NaNs and applying sigma clipping. This prepares the data for transit analysis. ```python import everest import scipy from astropy.stats import sigma_clip from transitleastsquares import transitleastsquares, cleaned_array EPIC_id = 211351816 # Example EPIC ID star = everest.Everest(EPIC_id) t = numpy.delete(star.time, star.badmask) y = numpy.delete(star.fcor, star.badmask) t = numpy.array(t[~numpy.isnan(y)], dtype='float32') y = numpy.array(y[~numpy.isnan(y)], dtype='float32') trend = scipy.signal.medfilt(y, 101) y_filt = y /trend y_filt = sigma_clip(y_filt, sigma_upper=3, sigma_lower=99) t, y_filt = cleaned_array(t, y_filt) ``` -------------------------------- ### Perform TLS power spectrum search Source: https://github.com/hippke/tls/blob/master/tutorials/02 Starter's guide - K2-3b, a red dwarf with a planet.ipynb Initializes the transitleastsquares model with the preprocessed time and flux data. It then performs a power spectrum search for transits, using a specified oversampling factor and duration grid step to account for potential aliasing and improve sensitivity. ```python from transitleastsquares import transitleastsquares model = transitleastsquares(t, y_filt) results = model.power(oversampling_factor=5, duration_grid_step=1.02) ``` -------------------------------- ### Visualize Linear Period-Duration Grid Source: https://github.com/hippke/tls/blob/master/tutorials/09 Optimal period grid and optimal duration grid.ipynb Visualizes a linear grid of periods and durations, illustrating the concept of a full search space. This approach is simple but computationally inefficient for short periods. ```python import numpy import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib import rcParams; rcParams["figure.dpi"] = 150 ax = plt.gca() rect = patches.Rectangle((0.5, 0.01), 980, 0.92, linewidth=1, edgecolor='r', facecolor='red') ax.add_patch(rect) for x in numpy.linspace(0.5, 980, 20): for y in numpy.linspace(0.02, 0.92, 20): plt.plot(x, y, color='black', marker='o', markersize=1) ax.set_xlabel(r'Period (days)') ax.set_ylabel(r'Transit duration (days)') ax.set_xlim(0, 1000) ax.set_ylim(0, 1); ``` -------------------------------- ### Prepare Data for Transit Least Squares Source: https://github.com/hippke/tls/blob/master/tutorials/06 Comparison between TLS and BLS.ipynb Loads Kepler data, cleans it by removing NaNs and bad masks, and applies sigma clipping to filter outliers. This prepares the time-series flux data for transit detection algorithms. ```python import numpy import scipy import everest import matplotlib.pyplot as plt from astropy.stats import sigma_clip import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('matplotlib') logger.setLevel(logging.CRITICAL) EPIC_id = 212521166 star = everest.Everest(EPIC_id) t = numpy.delete(star.time, star.badmask) y = numpy.delete(star.fcor, star.badmask) t = numpy.array(t[~numpy.isnan(y)], dtype='float32') y = numpy.array(y[~numpy.isnan(y)], dtype='float32') trend = scipy.signal.medfilt(y, 25) y_filt = y /trend y_filt = sigma_clip(y_filt, sigma_upper=2, sigma_lower=float('inf')) fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 6)) ax = axes[0] ax.plot(t, y, "k") ax.plot(t, trend) ax.set_ylabel("Flux (electrons per sec)") ax = axes[1] ax.plot(t, y_filt, "k") ax.set_xlim(t.min(), t.max()) ax.set_xlabel("Time (days)") ax.set_ylabel("Normalized flux"); ``` -------------------------------- ### Generate Optimal Period Grid Source: https://github.com/hippke/tls/blob/master/docs/source/Python interface.md Use this function to create a grid of trial periods optimized for transit searches. It automatically calculates an optimal sampling based on stellar and time span parameters. TLS calls this function internally, but it can be used separately for custom BLS searches. ```python from transitleastsquares import period_grid periods = period_grid(R_star=1, M_star=1, time_span=400) ``` -------------------------------- ### Run TLS with Non-Uniform Noise (No Uncertainties) Source: https://github.com/hippke/tls/blob/master/tutorials/10 Measurement uncertainties.ipynb Re-runs the TLS algorithm on data with non-uniform noise, but without providing the measurement uncertainties. This demonstrates the impact of ignoring noise variations on the SDE. Requires transitleastsquares and numpy. ```python from transitleastsquares import transitleastsquares import numpy model = transitleastsquares(t, y) results = model.power( period_min=300, period_max=400, oversampling_factor=3, duration_grid_step=1.05, T0_fit_margin=0.2 ) print('SDE non uniform noise, no uncertainties used: ', format(results.SDE, '.5f')) ``` -------------------------------- ### Run TLS with Uniform Noise Source: https://github.com/hippke/tls/blob/master/tutorials/10 Measurement uncertainties.ipynb Initializes and runs the Transit Least Squares (TLS) algorithm on synthetic data with uniform noise. It calculates the power spectrum to find potential transits and prints the Signal Detection Efficiency (SDE). Requires transitleastsquares and numpy. ```python from transitleastsquares import transitleastsquares import numpy model = transitleastsquares(t, y) results = model.power( period_min=300, period_max=400, oversampling_factor=3, duration_grid_step=1.05, T0_fit_margin=0.2 ) print('SDE with uniform noise', format(results.SDE, '.5f')) ``` -------------------------------- ### Plot Power Spectrum with Non-Uniform Noise (With Uncertainties) Source: https://github.com/hippke/tls/blob/master/tutorials/10 Measurement uncertainties.ipynb Visualizes the power spectrum from TLS analysis when non-uniform noise is present and correctly accounted for by providing measurement uncertainties. Requires matplotlib and numpy. ```python import matplotlib.pyplot as plt import numpy plt.figure() ax = plt.gca() ax.axvline(results.period, alpha=0.4, lw=3) plt.xlim(numpy.min(results.periods), numpy.max(results.periods)) for n in range(2, 10): ax.axvline(n*results.period, alpha=0.4, lw=1, linestyle="dashed") ax.axvline(results.period / n, alpha=0.4, lw=1, linestyle="dashed") plt.ylabel(r'SDE') plt.xlabel('Period (days)') plt.plot(results.periods, results.power, color='black', lw=0.5) ``` -------------------------------- ### Load Data and Perform TLS Search Source: https://github.com/hippke/tls/blob/master/tutorials/04 Exploring the TLS spectra and statistics.ipynb Loads astronomical data, detrends it, and performs a transit search using the transitleastsquares library. Requires numpy, scipy, everest, and matplotlib. Ensure data is cleaned and formatted correctly. ```python import numpy import scipy import everest import matplotlib.pyplot as plt import logging from astropy.stats import sigma_clip from transitleastsquares import transitleastsquares float_formatter = lambda x: "%.2f" % x numpy.set_printoptions(formatter={'float_kind':float_formatter}) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('matplotlib') logger.setLevel(logging.CRITICAL) EPIC_id = 212521166 star = everest.Everest(EPIC_id) t = numpy.delete(star.time, star.badmask) y = numpy.delete(star.fcor, star.badmask) t = numpy.array(t[~numpy.isnan(y)], dtype='float32') y = numpy.array(y[~numpy.isnan(y)], dtype='float32') trend = scipy.signal.medfilt(y, 25) y_filt = y /trend y_filt = sigma_clip(y_filt, sigma_upper=3, sigma_lower=float('inf')) model = transitleastsquares(t, y_filt) results = model.power() ``` -------------------------------- ### period_grid(parameters) Source: https://github.com/hippke/tls/blob/master/docs/source/Python interface.md Generates an optimal grid of trial periods for searching transit signals. This function is called automatically by TLS but can be used separately for classical BLS searches. ```APIDOC ## period_grid(parameters) ### Description Generates an optimal grid of trial periods for searching transit signals, considering factors like stellar mass and radius to optimize frequency sampling. ### Parameters * **R_star:** Stellar radius (in units of solar radii) * **M_star:** Stellar mass (in units of solar masses) * **time_span:** Duration of time series (in units of days) * **period_min:** Minimum trial period (in units of days). Optional. * **period_max:** Maximum trial period (in units of days). Optional. * **oversampling_factor:** Default: 2. Optional. ### Returns A 1D array of float values representing a grid of trial periods in units of days. ### Example Usage ```python from transitleastsquares import period_grid periods = period_grid(R_star=1, M_star=1, time_span=400) ``` ### Notes - Parameters are auto-enforced to ranges `0.1 < R_star < 10000` and `0.01 < M_star < 1000`. - If the grid size is less than 100 values, the function returns the default grid `R_star=M_star=1`. - Very short time series (less than a few days of duration) default to a grid size with a span of 5 days. ``` -------------------------------- ### Generate Synthetic Transit Data with Batman Source: https://github.com/hippke/tls/blob/master/tutorials/01 Quick start with synthetic data.ipynb Uses the batman package to create a synthetic transit light curve for a planet around a solar-like star. Includes adding white noise to simulate observational data. Requires numpy, batman, and matplotlib. ```python import numpy import batman import matplotlib.pyplot as plt from matplotlib import rcParams; rcParams["figure.dpi"] = 150 numpy.random.seed(seed=0) # reproducibility # Create test data time_start = 3.14 data_duration = 100 samples_per_day = 48 samples = int(data_duration * samples_per_day) time = numpy.linspace(time_start, time_start + data_duration, samples) # Use batman to create transits ma = batman.TransitParams() ma.t0 = time_start # time of inferior conjunction; first transit is X days after start ma.per = 10.123 # orbital period ma.rp = 6371 / 696342 # 6371 planet radius (in units of stellar radii) ma.a = 19 # semi-major axis (in units of stellar radii) ma.inc = 90 # orbital inclination (in degrees) ma.ecc = 0 # eccentricity ma.w = 90 # longitude of periastron (in degrees) ma.u = [0.4, 0.4] # limb darkening coefficients ma.limb_dark = "quadratic" # limb darkening model m = batman.TransitModel(ma, time) # initializes model synthetic_signal = m.light_curve(ma) # calculates light curve # Create noise and merge with flux ppm = 50 # Noise level in parts per million noise = numpy.random.normal(0, 10**-6 * ppm, int(samples)) flux = synthetic_signal + noise # Plot raw data plt.figure() ax = plt.gca() ax.scatter(time, flux, color='black', s=1) ax.set_ylabel("Flux") ax.set_xlabel("Time (days)") plt.xlim(min(time), max(time)) plt.ylim(0.999, 1.001); ``` -------------------------------- ### Compare TLS Power Spectra Source: https://github.com/hippke/tls/blob/master/tutorials/05 Custom transit shapes - Example of the grazing planet WASP-75.ipynb Plots the power spectra obtained from TLS searches using both 'grazing' and 'box' transit templates. This visualization helps to assess the difference in detection sensitivity and signal-to-noise ratio (SDE) between the two models, particularly for periods between 2 and 3 days. ```python plt.ylabel(r'SDE') plt.xlabel('Period (days)') plt.plot(results_grazing.periods, results_grazing.power, color='red') plt.plot(results_box.periods, results_box.power, color='orange') plt.plot((2, 3), (results_grazing.SDE, results_grazing.SDE), color='red', linestyle='dashed') plt.plot((2, 3), (results_box.SDE, results_box.SDE), color='orange', linestyle='dashed') plt.text(2.2, results_box.SDE*1.01, format(results_box.SDE, '.1f'), color='orange') plt.text(2.2, results_grazing.SDE*1.01, format(results_grazing.SDE, '.1f'), color='red') plt.xlim(2, 3); ``` -------------------------------- ### Download and preprocess K2 light curve Source: https://github.com/hippke/tls/blob/master/tutorials/02 Starter's guide - K2-3b, a red dwarf with a planet.ipynb Downloads the K2 light curve for a specified EPIC ID using the Everest package. It then cleans the data by removing NaNs, applying a sliding median filter to remove stellar variability, and clipping positive 3-sigma outliers. Negative outliers are retained as they may indicate transits. ```python from matplotlib import rcParams; rcParams["figure.dpi"] = 150 EPIC_id = 201367065 star = everest.Everest(EPIC_id) t = numpy.delete(star.time, star.badmask) y = numpy.delete(star.fcor, star.badmask) t = numpy.array(t[~numpy.isnan(y)], dtype='float32') y = numpy.array(y[~numpy.isnan(y)], dtype='float32') trend = scipy.signal.medfilt(y, 25) y_filt = y /trend y_filt = sigma_clip(y_filt, sigma_upper=2, sigma_lower=float('inf')) fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 6)) ax = axes[0] ax.plot(t, y, "k") ax.plot(t, trend) ax.set_ylabel("Flux (electrons per sec)") ax = axes[1] ax.plot(t, y_filt, "k") ax.set_xlim(t.min(), t.max()) ax.set_xlabel("Time (days)") ax.set_ylabel("Normalized flux"); ``` -------------------------------- ### Plot Power Spectrum with Non-Uniform Noise (No Uncertainties) Source: https://github.com/hippke/tls/blob/master/tutorials/10 Measurement uncertainties.ipynb Visualizes the power spectrum from TLS analysis when non-uniform noise is present but not accounted for by uncertainties. Requires matplotlib and numpy. ```python import matplotlib.pyplot as plt import numpy plt.figure() ax = plt.gca() ax.axvline(results.period, alpha=0.4, lw=3) plt.xlim(numpy.min(results.periods), numpy.max(results.periods)) for n in range(2, 10): ax.axvline(n*results.period, alpha=0.4, lw=1, linestyle="dashed") ax.axvline(results.period / n, alpha=0.4, lw=1, linestyle="dashed") plt.ylabel(r'SDE') plt.xlabel('Period (days)') plt.plot(results.periods, results.power, color='black', lw=0.5) plt.text(results.period + 1, results.SDE * 0.9, 'SDE=' + format(results.SDE, '.1f')) plt.text(results.period + 1, results.SDE * 0.7, 'Non-uniform noise\nwithout uncertainties') plt.xlim(300, 400); ``` -------------------------------- ### Print transit statistics Source: https://github.com/hippke/tls/blob/master/tutorials/02 Starter's guide - K2-3b, a red dwarf with a planet.ipynb Prints key statistics derived from the TLS search results, including the detected period, number of transit times, transit depth, and transit duration. This provides a quantitative summary of the detected transit signal. ```python print('Period', format(results.period, '.5f'), 'd') print(len(results.transit_times), 'transit times in time series:', \ ['{0:0.5f}'.format(i) for i in results.transit_times]) print('Transit depth', format(results.depth, '.5f')) print('Transit duration (days)', format(results.duration, '.5f')) ``` -------------------------------- ### Create Synthetic Transit Data with Batman Source: https://github.com/hippke/tls/blob/master/tutorials/10 Measurement uncertainties.ipynb Generates synthetic transit light curve data using the batman package. This is useful for testing TLS with simulated observations, including setting up transit parameters and calculating the original flux. ```python import numpy import batman # Create test data numpy.random.seed(seed=0) # reproducibility days = 365.25 * 3 samples_per_day = 12 samples = int(days * samples_per_day) t = numpy.linspace(start, start + days, samples) # Use batman to create transits ma = batman.TransitParams() ma.t0 = (start + 20) # time of inferior conjunction; first transit is X days after start ma.per = 365.25 # orbital period ma.rp = 6371 / 696342 # planet radius (in units of stellar radii) ma.a = 217 # semi-major axis (in units of stellar radii) ma.inc = 90 # orbital inclination (in degrees) ma.ecc = 0 # eccentricity ma.w = 90 # longitude of periastron (in degrees) ma.u = [0.5] # limb darkening coefficients ma.limb_dark = "linear" # limb darkening model m = batman.TransitModel(ma, t) # initializes model original_flux = m.light_curve(ma) # calculates light curve ``` -------------------------------- ### Run Box Least Squares (BLS) Source: https://github.com/hippke/tls/blob/master/tutorials/06 Comparison between TLS and BLS.ipynb Initializes and runs the Box Least Squares algorithm to detect periodic transit signals. It automatically searches over a range of durations to find the best-fitting period. ```python from astropy.stats import BoxLeastSquares durations = numpy.linspace(0.05, 0.2, 20) model_bls = BoxLeastSquares(t, y_filt) results_bls = model_bls.autopower(durations, frequency_factor=10) period = results_bls.period[numpy.argmax(results_bls.power)] ``` -------------------------------- ### Print TLS Analysis Results Source: https://github.com/hippke/tls/blob/master/tutorials/01 Quick start with synthetic data.ipynb Prints key statistics from the TLS analysis, including the detected period, number and times of transits, transit depth, duration, and Signal Detection Efficiency (SDE). ```python print('Period', format(results.period, '.5f'), 'd') print(len(results.transit_times), 'transit times in time series:', \ ['{0:0.5f}'.format(i) for i in results.transit_times]) print('Transit depth', format(results.depth, '.5f')) print('Best duration (days)', format(results.duration, '.5f')) print('Signal detection efficiency (SDE):', results.SDE) ``` -------------------------------- ### Plot Transit Lightcurve and Data Points Source: https://github.com/hippke/tls/blob/master/tutorials/03 Multiple planets - K2-3, a red dwarf with 3 Super-Earths.ipynb Displays the full lightcurve with in-transit and out-of-transit data points highlighted, along with the best-fit TLS model. Useful for visually inspecting the transit event. ```python plt.figure() in_transit = transit_mask( t_third_run, results_third_run.period, results_third_run.duration, results_third_run.T0) plt.scatter( t_third_run[in_transit], y_third_run[in_transit], color='red', s=2, zorder=0) plt.scatter( t_third_run[~in_transit], y_third_run[~in_transit], color='blue', alpha=0.5, s=2, zorder=0) plt.plot( results_third_run.model_lightcurve_time, results_third_run.model_lightcurve_model, alpha=0.5, color='red', zorder=1) plt.xlim(min(t), max(t)) plt.ylim(min(y_filt), max(y_filt)) plt.xlabel('Time (days)') plt.ylabel('Relative flux'); ``` -------------------------------- ### Print Best-Fit Signal Statistics Source: https://github.com/hippke/tls/blob/master/tutorials/04 Exploring the TLS spectra and statistics.ipynb Prints key statistical information about the best-fit transit signal found by TLS, including period, mid-transit time, and duration. Formats output to 5 decimal places. ```python print('Period of the best-fit signal', format(results.period, '.5f')) print('Mid-transit time of the first transit within the time series', format(results.T0, '.5f')) print('Best-fit transit duration (in days)', format(results.duration, '.5f')) ``` -------------------------------- ### Plot Light Curve and TLS Model Source: https://github.com/hippke/tls/blob/master/tutorials/02 Starter's guide - K2-3b, a red dwarf with a planet.ipynb Use this code to visualize the transit event. It plots the in-transit and out-of-transit data points separately and overlays the best-fit TLS model. Ensure 't', 'y_filt', and 'results' are defined. ```python from transitleastsquares import transit_mask plt.figure() in_transit = transit_mask( t, results.period, results.duration, results.T0) plt.scatter( t[in_transit], y_filt[in_transit], color='red', s=2, zorder=0) plt.scatter( t[~in_transit], y_filt[~in_transit], color='blue', alpha=0.5, s=2, zorder=0) plt.plot( results.model_lightcurve_time, results.model_lightcurve_model, alpha=0.5, color='red', zorder=1) plt.xlim(min(t), max(t)) plt.ylim(0.9985, 1.0003) plt.xlabel('Time (days)') plt.ylabel('Relative flux'); ``` -------------------------------- ### Download and Detrend WASP-75 Data Source: https://github.com/hippke/tls/blob/master/tutorials/05 Custom transit shapes - Example of the grazing planet WASP-75.ipynb Downloads the light curve data for WASP-75 using the `everest` library and performs initial detrending and outlier rejection. This step is crucial for preparing the data for transit analysis. ```python import numpy import scipy import everest from astropy.stats import sigma_clip import matplotlib.pyplot as plt import logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger('matplotlib') logger.setLevel(logging.CRITICAL) EPIC_ID = 206154641 star = everest.Everest(EPIC_ID) t = star.time y = star.fcor t = numpy.delete(star.time, star.badmask) y = numpy.delete(star.fcor, star.badmask) t = numpy.array(t[~numpy.isnan(y)], dtype='float32') y = numpy.array(y[~numpy.isnan(y)], dtype='float32') trend = scipy.signal.medfilt(y, 25) y_filt = y / trend y_filt = sigma_clip(y_filt, sigma_upper=3, sigma_lower=99) fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 6)) ax = axes[0] ax.plot(t, y, "k") ax.plot(t, trend) ax.set_ylabel("Flux (electrons per sec)") ax = axes[1] ax.plot(t, y_filt, "k") ax.set_xlim(t.min(), t.max()) ax.set_xlabel("Time (days)") ax.set_ylabel("Flux"); ``` -------------------------------- ### Plotting Transit Light Curves with Different Limb Darkening Values Source: https://github.com/hippke/tls/blob/master/tutorials/07 The influence of limb darkening values.ipynb Generates and plots transit light curves using the `transit` function with specified limb darkening coefficients. This helps visualize the theoretical impact of different LD models. ```python import numpy import matplotlib.pyplot as plt from transitleastsquares import transit time = numpy.linspace(-0.09, 0.09, 1000) ab = [0.4804, 0.1867] # Example EPIC catalog LD values plt.figure() plt.plot(time, transit(ld=[0.4804, 0.1867]), color='black', label='TLS default') plt.plot(time, transit(ld=ab), color='red', label='EPIC catalog') plt.plot(time, transit(ld=[0.6505, 0.1041]), color='blue', label='Grunblatt+ 2016') plt.legend() ``` -------------------------------- ### Analyze Transit Depths Source: https://github.com/hippke/tls/blob/master/tutorials/11 A planet from TESS with TLS.ipynb Prints detailed transit parameters and plots the individual transit depths with uncertainties. Requires `numpy` and `matplotlib.pyplot`. ```python print('Period', format(results.period, '.5f'), 'd at T0=', results.T0) print(len(results.transit_times), 'transit times in time series:', ['{0:0.5f}'.format(i) for i in results.transit_times]) print('Number of data points during each unique transit', results.per_transit_count) print('The number of transits with intransit data points', results.distinct_transit_count) print('The number of transits with no intransit data points', results.empty_transit_count) print('Transit depth', format(results.depth, '.5f'), '(at the transit bottom)') print('Transit duration (days)', format(results.duration, '.5f')) print('Transit depths (mean)', results.transit_depths) print('Transit depth uncertainties', results.transit_depths_uncertainties) plt.figure() plt.errorbar( results.transit_times, results.transit_depths, yerr=results.transit_depths_uncertainties, fmt='o', color='red') plt.plot( (time.min(), time.max()), (numpy.mean(results.transit_depths), numpy.mean(results.transit_depths)), color='black', linestyle='dashed') plt.plot((time.min(), time.max()), (1, 1), color='black') plt.xlabel('Time (days)') plt.ylabel('Flux'); ``` -------------------------------- ### Retrieve Stellar Catalog Information Source: https://github.com/hippke/tls/blob/master/docs/source/Python interface.md Fetches stellar parameters like limb darkening coefficients and radius from catalogs. Ensure data is validated before use in TLS. ```python ab, R_star, R_star_min, R_star_max, M_star, M_star_min, M_star_max = catalog_info(EPIC_ID=211611158) print('Quadratic limb darkening a, b', ab[0], ab[1]) print('Stellar radius', R_star, '+', R_star_max, '-', R_star_min) print('Stellar mass', M_star, '+', M_star_max, '-', M_star_min) ``` -------------------------------- ### Plot TLS Power Spectrum Source: https://github.com/hippke/tls/blob/master/tutorials/04 Exploring the TLS spectra and statistics.ipynb Generates and plots the TLS power spectrum, highlighting the detected period and its harmonics. Uses matplotlib for visualization. Recommended for general use due to smoothed noise power. ```python from matplotlib import rcParams; rcParams["figure.dpi"] = 150 plt.figure() ax = plt.gca() ax.axvline(results.period, alpha=0.4, lw=3) plt.xlim(numpy.min(results.periods), numpy.max(results.periods)) for n in range(2, 10): ax.axvline(n*results.period, alpha=0.4, lw=1, linestyle="dashed") ax.axvline(results.period / n, alpha=0.4, lw=1, linestyle="dashed") plt.ylabel(r'SDE') plt.xlabel('Period (days)') plt.plot(results.periods, results.power, color='black', lw=0.5) plt.xlim(0, max(results.periods)); ``` -------------------------------- ### catalog_info(EPIC_ID or TIC_ID) Source: https://github.com/hippke/tls/blob/master/docs/source/Python interface.md Provides priors for stellar mass, radius, and limb darkening for stars observed during Kepler and TESS missions. ```APIDOC ## catalog_info(EPIC_ID or TIC_ID) ### Description Retrieves stellar parameters (mass, radius) and limb darkening coefficients from astronomical catalogs based on provided stellar IDs. ### Parameters * **EPIC_ID:** *(int)* The EPIC catalog ID (K2, Ecliptic Plane Input Catalog) * **TIC_ID:** *(int)* The TIC catalog ID (TESS Input Catalog) * **KIC_ID:** *(int)* The Kepler Input Catalog ID (Kepler K1 Input Catalog) ### Returns * **ab:** *(tuple of floats)* Quadratic limb darkening parameters a, b * **mass:** *(float)* Stellar mass (in units of solar masses) * **mass_min:** *(float)* 1-sigma upper confidence interval on stellar mass (in units of solar mass) * **mass_max:** *(float)* 1-sigma lower confidence interval on stellar mass (in units of solar mass) * **radius:** *(float)* Stellar radius (in units of solar radii) * **radius_min:** *(float)* 1-sigma upper confidence interval on stellar radius (in units of solar radii) * **radius_max:** *(float)* 1-sigma lower confidence interval on stellar radius (in units of solar radii) ### Note Matching is performed by finding the nearest $T_{ m eff}$, and subsequently the nearest ${ m logg}$. ```