### Display Install Prefix Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/CMakeLists.txt Logs the CMAKE_INSTALL_PREFIX, which is the base directory for installing the project's files. ```cmake message(STATUS "CMAKE_INSTALL_PREFIX: ${CMAKE_INSTALL_PREFIX}") ``` -------------------------------- ### Install and Test Theano Interface Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/user/install.md Install additional dependencies for the Theano interface and run specific tests for it. ```bash python -m pip install "[test,theano]" python -m pytest -v python/test/theano ``` -------------------------------- ### Install Project Headers Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/CMakeLists.txt Installs the header files from the 'include/' directory to the system's include directory as defined by CMAKE_INSTALL_INCLUDEDIR. ```cmake install( DIRECTORY "include/" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" ) ``` -------------------------------- ### Installing JAX Extension Source: https://github.com/exoplanet-dev/celerite2/blob/main/CMakeLists.txt Installs the 'xla_ops' JAX extension module to the 'jax' subdirectory within the project's installation path. ```cmake install(TARGETS xla_ops LIBRARY DESTINATION "${SKBUILD_PROJECT_NAME}/jax") ``` -------------------------------- ### Basic Project Setup Source: https://github.com/exoplanet-dev/celerite2/blob/main/CMakeLists.txt Initializes the CMake build system, sets the project name and version, and specifies the C++ language standard. ```cmake cmake_minimum_required(VERSION 3.15...3.27) project( ${SKBUILD_PROJECT_NAME} VERSION ${SKBUILD_PROJECT_VERSION} LANGUAGES CXX) ``` -------------------------------- ### Install Development Dependencies for Testing Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/user/install.md Install the necessary packages, including testing tools, to run the unit tests for celerite2. ```bash python -m pip install "[test]" ``` -------------------------------- ### Install celerite2 from Source Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/user/install.md Clone the repository and install celerite2 in editable mode. This is useful for development or when you need the latest unreleased features. ```bash git clone --recursive https://github.com/exoplanet-dev/celerite2.git cd celerite2 python -m pip install -e . ``` -------------------------------- ### Install celerite2 using pip Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/user/install.md Use this command to install the latest stable version of celerite2 from the Python Package Index. ```bash python -m pip install -U celerite2 ``` -------------------------------- ### Installing Python Module (driver) Source: https://github.com/exoplanet-dev/celerite2/blob/main/CMakeLists.txt Installs the 'driver' module to the specified library destination within the project's installation directory. ```cmake install(TARGETS driver LIBRARY DESTINATION ${SKBUILD_PROJECT_NAME}) ``` -------------------------------- ### Setup Initial celerite2 GP Model Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Initializes a celerite2 Gaussian Process with a mixture of SHOTerm terms (quasi-periodic and non-periodic) and computes the initial log likelihood. ```python import celerite2 from celerite2 import terms # Quasi-periodic term term1 = terms.SHOTerm(sigma=1.0, rho=1.0, tau=10.0) # Non-periodic component term2 = terms.SHOTerm(sigma=1.0, rho=5.0, Q=0.25) kernel = term1 + term2 # Setup the GP gp = celerite2.GaussianProcess(kernel, mean=0.0) gp.compute(t, yerr=yerr) print("Initial log likelihood: {0}".format(gp.log_likelihood(y))) ``` -------------------------------- ### Optimize celerite2 GP model with SciPy Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/user/upgrade.md Example demonstrating how to find the maximum likelihood model for a celerite2 Gaussian Process using scipy.optimize.minimize. Requires manual parameter re-exponentiation and recomputation. ```python from scipy.optimize import minimize def set_params(params, gp): gp.mean = params[0] theta = np.exp(params[1:]) gp.kernel = terms.SHOTerm(S0=theta[0], Q=theta[1], w0=theta[2]) return gp def neg_log_like(params, gp): gp = set_params(params, gp) gp.recompute(quiet=True) return -gp.log_likelihood(y) initial_params = [2.123, np.log(kernel.S0), np.log(kernel.Q), np.log(kernel.w0)] soln = minimize(neg_log_like, initial_params, method="L-BFGS-B", args=(gp,)) opt_gp = set_params(soln.x, gp) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/user/install.md Execute the unit tests using pytest to verify the installation and functionality of celerite2. ```bash python -m pytest -v python/test ``` -------------------------------- ### Define celerite GP model Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/user/upgrade.md Example of defining a Gaussian Process model using the original celerite library with a SHOTerm kernel. ```python import numpy as np import celerite from celerite import terms x, y, yerr = data kernel = terms.SHOTerm(log_S0=np.log(1.0), log_Q=np.log(2.5), log_omega0=np.log(0.2)) gp = celerite.GP(kernel, mean=2.123) gp.compute(x, yerr) print("Initial log likelihood: {0}".format(gp.log_likelihood(y))) ``` -------------------------------- ### Define celerite2 GP model Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/user/upgrade.md Example of defining an equivalent Gaussian Process model using celerite2 with a SHOTerm kernel. Note the parameter format and class names. ```python import numpy as np import celerite2 from celerite2 import terms x, y, yerr = data kernel = terms.SHOTerm(S0=1.0, Q=2.5, w0=0.2) gp = celerite2.GaussianProcess(kernel, mean=2.123) gp.compute(x, yerr=yerr) print("Initial log likelihood: {0}".format(gp.log_likelihood(y))) ``` -------------------------------- ### Get and Display Git Hash Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/CMakeLists.txt Executes a Git command to retrieve the current commit hash and displays it along with the project version. ```cmake execute_process(COMMAND git rev-parse HEAD WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} OUTPUT_VARIABLE PROJECT_GIT_HASH OUTPUT_STRIP_TRAILING_WHITESPACE) message(STATUS "${PROJECT_NAME} version : ${PROJECT_VERSION}") message(STATUS "${PROJECT_NAME} Git hash: ${PROJECT_GIT_HASH}") ``` -------------------------------- ### Define Celerite2 Term and GaussianProcess in PyMC Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/api/pymc.md This snippet shows how to import and use celerite2 terms and the GaussianProcess class within the PyTensor framework for PyMC model building. Ensure PyTensor and celerite2 are installed. ```python import pytensor.tensor as pt from celerite2.pymc import GaussianProcess, terms term = terms.SHOTerm(S0=at.scalar(), w0=at.scalar(), Q=at.scalar()) gp = GaussianProcess(term) ``` -------------------------------- ### Configure and Add Tests Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/CMakeLists.txt Sets up the build to include tests if the 'Build_Tests' option is enabled. If enabled, it initializes testing and adds the subdirectory 'test' for test compilation. ```cmake option(Build_Tests "Build tests" ON) if(Build_Tests) enable_testing() add_subdirectory(test) endif() ``` -------------------------------- ### Set up MCMC for Posterior Inference Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb This snippet configures the log probability function for MCMC, combining the GP's log-likelihood with a wide normal prior on parameters. It also initializes the MCMC sampler using emcee and runs the sampling process. Use this to explore the posterior distribution of model parameters. ```python import emcee prior_sigma = 2.0 def log_prob(params, gp): gp = set_params(params, gp) return ( gp.log_likelihood(y) - 0.5 * np.sum((params / prior_sigma) ** 2), gp.kernel.get_psd(omega), ) np.random.seed(5693854) coords = soln.x + 1e-5 * np.random.randn(32, len(soln.x)) sampler = emcee.EnsembleSampler( coords.shape[0], coords.shape[1], log_prob, args=(gp,) ) state = sampler.run_mcmc(coords, 2000, progress=False) sampler.reset() state = sampler.run_mcmc(state, 5000, progress=False) ``` -------------------------------- ### Discover and Build C++ Test Executables Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/test/CMakeLists.txt Finds all .cpp files recursively and creates an executable for each. Applies platform-specific compiler options and registers them as tests. ```cmake file(GLOB_RECURSE all_tests RELATIVE ${CMAKE_CURRENT_LIST_DIR} *.cpp) foreach(test ${all_tests}) get_filename_component(test_name ${test} NAME_WE) get_filename_component(test_dir ${test} DIRECTORY) add_executable(${test_name} ${test}) if(WIN32) target_compile_options(${test_name} PUBLIC /Wall /bigobj) else() target_compile_options(${test_name} PUBLIC -Wall -pedantic -Wextra -Werror) if(HAS_NO_DEPRECATED_COPY) target_compile_options(${test_name} PUBLIC -Wno-deprecated-copy) endif() endif() set_property(TARGET ${test_name} PROPERTY RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${test_dir}) add_test(NAME ${test_name} COMMAND ${test_name} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/${test_dir}) endforeach() ``` -------------------------------- ### Include Project Headers and Vendor Libraries Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/CMakeLists.txt Adds the project's 'include' directory and the 'vendor/eigen' directory to the include path for compilation. ```cmake include_directories(${CMAKE_CURRENT_LIST_DIR}/include) include_directories(${CMAKE_CURRENT_LIST_DIR}/vendor/eigen) ``` -------------------------------- ### Define Project and Version Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/CMakeLists.txt Sets the project name to Celerite2 and its version to 0.1.0. Also includes CXX as a supported language. ```cmake project(Celerite2 VERSION 0.1.0 LANGUAGES CXX) ``` -------------------------------- ### Adding and Configuring JAX Extension Source: https://github.com/exoplanet-dev/celerite2/blob/main/CMakeLists.txt Adds the JAX extension module, sets its C++ standard to C++17, and includes the found XLA directory. ```cmake pybind11_add_module(xla_ops "python/celerite2/jax/xla_ops.cpp") target_compile_features(xla_ops PUBLIC cxx_std_17) target_include_directories(xla_ops PUBLIC "${XLA_DIR}") ``` -------------------------------- ### Run MCMC sampling with NUTS kernel in numpyro Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb This snippet initializes and runs a Markov Chain Monte Carlo (MCMC) simulation using the No-U-Turn Sampler (NUTS) kernel within numpyro. It specifies warmup and sampling iterations, number of chains, and uses a random key for reproducibility. The `%time` magic command is used to measure execution time. ```python nuts_kernel = NUTS(numpyro_model, dense_mass=True) mcmc = MCMC( nuts_kernel, num_warmup=1000, num_samples=1000, num_chains=2, progress_bar=False, ) rng_key = random.PRNGKey(34923) %time mcmc.run(rng_key, t, yerr, y=y) ``` -------------------------------- ### Plot Power Spectral Density (PSD) Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Visualizes the power spectral density of the initial GP model, showing individual terms and the full model. ```python freq = np.linspace(1.0 / 8, 1.0 / 0.3, 500) omega = 2 * np.pi * freq def plot_psd(gp): for n, term in enumerate(gp.kernel.terms): plt.loglog(freq, term.get_psd(omega), label="term {0}".format(n + 1)) plt.loglog(freq, gp.kernel.get_psd(omega), ":k", label="full model") plt.xlim(freq.min(), freq.max()) plt.legend() plt.xlabel("frequency [1 / day]") plt.ylabel("power [day ppt$^2$]") plt.title("initial psd") plot_psd(gp) ``` -------------------------------- ### ArviZ Summary for emcee Inference Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Generates a summary table for emcee inference results using ArviZ. This includes posterior expectations and convergence diagnostics for specified model parameters. ```python az.summary( emcee_data, var_names=[ "mean", "log_sigma1", "log_rho1", "log_tau", "log_sigma2", "log_rho2", "log_jitter", ], ) ``` -------------------------------- ### Including Directories Source: https://github.com/exoplanet-dev/celerite2/blob/main/CMakeLists.txt Specifies directories where header files for the project and its dependencies can be found. ```cmake include_directories( "c++/include" "c++/vendor/eigen" "python/celerite2") ``` -------------------------------- ### Finding JAXlib Include Directory Source: https://github.com/exoplanet-dev/celerite2/blob/main/CMakeLists.txt Executes a Python command to find the include directory for jaxlib. If successful, it proceeds to build the JAX extension. ```cmake execute_process( COMMAND "${Python_EXECUTABLE}" "-c" "from jax import ffi; print(ffi.include_dir())" OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE XLA_DIR RESULT_VARIABLE JAXLIB_RES) if(JAXLIB_RES EQUAL 0 AND NOT "${XLA_DIR}" STREQUAL "") message(STATUS "Building JAX extension with XLA include: ${XLA_DIR}") ``` -------------------------------- ### Plot Maximum Likelihood Model Results Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Visualizes the power spectral density (PSD) and predictions of a Gaussian Process model after maximum likelihood optimization. Use this to assess the quality of the optimized model. ```python plt.figure() plt.title("maximum likelihood psd") plot_psd(opt_gp) plt.figure() plt.title("maximum likelihood prediction") plot_prediction(opt_gp) ``` -------------------------------- ### Skipping JAX Extension Source: https://github.com/exoplanet-dev/celerite2/blob/main/CMakeLists.txt Logs a message indicating that the JAX extension is being skipped because the jax.ffi include directory could not be found. ```cmake else() message(STATUS "Skipping JAX extension (jax.ffi include_dir not found)") endif() ``` -------------------------------- ### ArviZ Summary for numpyro Inference Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Generates a summary table for numpyro inference results using ArviZ. This includes posterior expectations and convergence diagnostics for specified model parameters. ```python az.summary( numpyro_data, var_names=[ "mean", "log_sigma1", "log_rho1", "log_tau", "log_sigma2", "log_rho2", "log_jitter", ], ) ``` -------------------------------- ### ArviZ Summary for PyMC Inference Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Generates a summary table for PyMC inference results using ArviZ. This includes posterior expectations and convergence diagnostics for specified model parameters. ```python az.summary( pm_data, var_names=[ "mean", "log_sigma1", "log_rho1", "log_tau", "log_sigma2", "log_rho2", "log_jitter", ], ) ``` -------------------------------- ### JAX JIT-compiled Log Likelihood Function Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/api/jax.md This snippet defines a JAX JIT-compiled function to compute the log-likelihood of a Gaussian Process model with a SHO term. It requires importing jax, GaussianProcess, and terms from celerite2.jax. ```python import jax from celerite2.jax import GaussianProcess, terms @jax.jit def log_likelihood(params, x, diag, y): term = terms.SHOTerm(S0=params["S0"], w0=params["w0"], Q=params["Q"]) gp = GaussianProcess(term) gp.compute(x, diag=diag) return gp.log_likelihood(y) ``` -------------------------------- ### Combine SHOTerms using Addition and Multiplication Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/api/python.md Demonstrates how to combine two SHOTerm objects using both addition and multiplication operators in Python. This is useful for building complex models from simpler components. ```python from celerite2 import terms term1 = terms.SHOTerm(sigma=1.0, w0=0.5, Q=2.5) term2 = terms.SHOTerm(sigma=0.5, w0=0.5, Q=0.2) term = term1 + term2 # or ... term = term1 * term2 ``` -------------------------------- ### Finding Dependencies Source: https://github.com/exoplanet-dev/celerite2/blob/main/CMakeLists.txt Locates required packages such as pybind11 for Python C++ bindings and a specific Python version with development components. ```cmake set(PYBIND11_NEWPYTHON ON) find_package(pybind11 CONFIG REQUIRED) find_package(Python 3.11 REQUIRED COMPONENTS Interpreter Development.Module) ``` -------------------------------- ### Optimize GP Parameters with Maximum Likelihood Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb This snippet optimizes Gaussian Process parameters (mean, kernel, jitter) using scipy's minimize function. It defines helper functions to set parameters and calculate the negative log-likelihood. Use this for finding the best-fit parameters for your GP model. ```python from scipy.optimize import minimize def set_params(params, gp): gp.mean = params[0] theta = np.exp(params[1:]) gp.kernel = terms.SHOTerm( sigma=theta[0], rho=theta[1], tau=theta[2] ) + terms.SHOTerm(sigma=theta[3], rho=theta[4], Q=0.25) gp.compute(t, diag=yerr**2 + theta[5], quiet=True) return gp def neg_log_like(params, gp): gp = set_params(params, gp) return -gp.log_likelihood(y) initial_params = [0.0, 0.0, 0.0, np.log(10.0), 0.0, np.log(5.0), np.log(0.01)] soln = minimize(neg_log_like, initial_params, method="L-BFGS-B", args=(gp,)) opt_gp = set_params(soln.x, gp) soln ``` -------------------------------- ### celerite2.jax.GaussianProcess Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/api/jax.md The celerite2.jax.GaussianProcess class provides a JAX-compatible interface for celerite2 models. It allows users to define and compute with celerite2 models within a JAX environment, enabling automatic differentiation and JIT compilation. ```APIDOC ## celerite2.jax.GaussianProcess ### Description Provides a JAX-compatible interface to *celerite2* models. This class allows for the construction and computation of Gaussian Processes using JAX, enabling features like automatic differentiation and JIT compilation. ### Methods - `compute(x, diag=None)`: Computes the Gaussian Process for the given inputs. - `log_likelihood(y)`: Computes the log-likelihood of the data `y`. - `numpyro_dist()`: Returns a numpyro `Distribution` representing a multivariate normal with a *celerite* covariance matrix. ### Parameters - `term`: A celerite2 term model implemented in JAX. - `x` (array-like): The input data points. - `diag` (array-like, optional): Diagonal components of the covariance matrix. - `y` (array-like): The observed data. ### Example Usage ```python import jax from celerite2.jax import GaussianProcess, terms @jax.jit def log_likelihood(params, x, diag, y): term = terms.SHOTerm(S0=params["S0"], w0=params["w0"], Q=params["Q"]) gp = GaussianProcess(term) gp.compute(x, diag=diag) return gp.log_likelihood(y) ``` ``` -------------------------------- ### Simulate Quasi-Periodic Data Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Generates a simulated dataset with quasi-periodic oscillations and a gap, including plotting the true underlying signal and the noisy observed data. ```python import numpy as np import matplotlib.pyplot as plt np.random.seed(42) t = np.sort( np.append( np.random.uniform(0, 3.8, 57), np.random.uniform(5.5, 10, 68), ) ) # The input coordinates must be sorted yerr = np.random.uniform(0.08, 0.22, len(t)) y = ( 0.2 * (t - 5) + np.sin(3 * t + 0.1 * (t - 5) ** 2) + yerr * np.random.randn(len(t)) ) true_t = np.linspace(0, 10, 500) true_y = 0.2 * (true_t - 5) + np.sin(3 * true_t + 0.1 * (true_t - 5) ** 2) plt.plot(true_t, true_y, "k", lw=1.5, alpha=0.3) plt.errorbar(t, y, yerr=yerr, fmt=".k", capsize=0) plt.xlabel("x [day]") plt.ylabel("y [ppm]") plt.xlim(0, 10) plt.ylim(-2.5, 2.5) _ = plt.title("simulated data") ``` -------------------------------- ### Enable Compile Commands Export Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/CMakeLists.txt Enables the generation of a compile_commands.json file, which is useful for code analysis tools and IDEs. ```cmake set(CMAKE_EXPORT_COMPILE_COMMANDS ON) ``` -------------------------------- ### Enable Folder Organization in IDEs Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/CMakeLists.txt Enables the use of folders to organize targets and groups in integrated development environments (IDEs). ```cmake set_property(GLOBAL PROPERTY USE_FOLDERS ON) ``` -------------------------------- ### Plotting Posterior PSD with Matplotlib Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Visualize the posterior estimate of the power spectral density (PSD) from a PyMC trace using Matplotlib. This helps in qualitatively assessing the model fit and understanding the frequency components of the data. ```python psds = trace.posterior["psd"].values q = np.percentile(psds, [16, 50, 84], axis=(0, 1)) plt.loglog(freq, q[1], color="C0") plt.fill_between(freq, q[0], q[2], color="C0", alpha=0.1) plt.xlim(freq.min(), freq.max()) plt.xlabel("frequency [1 / day]") plt.ylabel("power [day ppt$^2$]") _ = plt.title("posterior psd using PyMC") ``` -------------------------------- ### Plot Posterior Power Spectral Density (PSD) Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Visualizes the posterior distribution of the power spectral density (PSD) derived from MCMC samples. It plots the median PSD with shaded regions representing the 16th and 84th percentiles. Use this to understand the uncertainty in the frequency components of the model. ```python psds = sampler.get_blobs(discard=100, flat=True) q = np.percentile(psds, [16, 50, 84], axis=0) plt.loglog(freq, q[1], color="C0") plt.fill_between(freq, q[0], q[2], color="C0", alpha=0.1) plt.xlim(freq.min(), freq.max()) plt.xlabel("frequency [1 / day]") plt.ylabel("power [day ppt$^2$]") _ = plt.title("posterior psd using emcee") ``` -------------------------------- ### CMake C++ Build Configuration Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/test/CMakeLists.txt Sets the C++ standard to C++17 and enforces its usage. Disables C++ extensions for better portability. ```cmake set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) ``` -------------------------------- ### BibTeX Entries for celerite2 Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/user/citation.md Use these BibTeX entries when citing the celerite2 package and its foundational paper in academic publications. The first entry is for the original celerite paper, and the second is for the celerite2 specific paper. ```bibtex @article{celerite1, author = {{Foreman-Mackey}, D. and {Agol}, E. and {Ambikasaran}, S. and {Angus}, R.}, title = "{Fast and Scalable Gaussian Process Modeling with Applications to Astronomical Time Series}", journal = {\aj}, year = 2017, month = dec, volume = 154, pages = {220}, doi = {10.3847/1538-3881/aa9332}, adsurl = {http://adsabs.harvard.edu/abs/2017AJ....154..220F}, adsnote = {Provided by the SAO/NASA Astrophysics Data System} } @article{celerite2, author = {{Foreman-Mackey}, D.}, title = "{Scalable Backpropagation for Gaussian Processes using Celerite}", journal = {Research Notes of the American Astronomical Society}, year = 2018, month = feb, volume = 2, number = 1, pages = {31}, doi = {10.3847/2515-5172/aaaf6c}, adsurl = {http://adsabs.harvard.edu/abs/2018RNAAS...2a..31F}, adsnote = {Provided by the SAO/NASA Astrophysics Data System} } ``` -------------------------------- ### Define numpyro model with celerite2 JAX kernel Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb This snippet defines a numpyro model for Gaussian Process regression using celerite2's JAX backend. It includes sampling for model parameters and defines the kernel with two SHOTerms. Ensure JAX is configured for 64-bit precision and necessary libraries are imported. ```python from jax import config config.update("jax_enable_x64", True) from jax import random import jax.numpy as jnp import numpyro import numpyro.distributions as dist from numpyro.infer import MCMC, NUTS import celerite2.jax from celerite2.jax import terms as jax_terms def numpyro_model(t, yerr, y=None): mean = numpyro.sample("mean", dist.Normal(0.0, prior_sigma)) log_jitter = numpyro.sample("log_jitter", dist.Normal(0.0, prior_sigma)) log_sigma1 = numpyro.sample("log_sigma1", dist.Normal(0.0, prior_sigma)) log_rho1 = numpyro.sample("log_rho1", dist.Normal(0.0, prior_sigma)) log_tau = numpyro.sample("log_tau", dist.Normal(0.0, prior_sigma)) term1 = jax_terms.SHOTerm( sigma=jnp.exp(log_sigma1), rho=jnp.exp(log_rho1), tau=jnp.exp(log_tau) ) log_sigma2 = numpyro.sample("log_sigma2", dist.Normal(0.0, prior_sigma)) log_rho2 = numpyro.sample("log_rho2", dist.Normal(0.0, prior_sigma)) term2 = jax_terms.SHOTerm( sigma=jnp.exp(log_sigma2), rho=jnp.exp(log_rho2), Q=0.25 ) kernel = term1 + term2 gp = celerite2.jax.GaussianProcess(kernel, mean=mean) gp.compute(t, diag=yerr**2 + jnp.exp(log_jitter), check_sorted=False) numpyro.sample("obs", gp.numpyro_dist(), obs=y) numpyro.deterministic("psd", kernel.get_psd(omega)) ``` -------------------------------- ### Plot posterior expectations of the power spectrum Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb This snippet visualizes the posterior distribution of the power spectral density (PSD) obtained from MCMC samples. It calculates percentiles and plots the median PSD along with a shaded region representing the credible interval. Ensure `numpy` and `matplotlib.pyplot` are imported as `np` and `plt` respectively, and `freq` is defined. ```python psds = np.asarray(mcmc.get_samples()["psd"]) q = np.percentile(psds, [16, 50, 84], axis=0) plt.loglog(freq, q[1], color="C0") plt.fill_between(freq, q[0], q[2], color="C0", alpha=0.1) plt.xlim(freq.min(), freq.max()) plt.xlabel("frequency [1 / day]") plt.ylabel("power [day ppt$^2$]") _ = plt.title("posterior psd using numpyro") ``` -------------------------------- ### Set Minimum CMake Version Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/CMakeLists.txt Specifies the minimum version of CMake required to build the project. Ensures compatibility with required CMake features. ```cmake cmake_minimum_required(VERSION 3.5) ``` -------------------------------- ### Plotting Posterior Distribution of Period Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Generates a histogram comparing the posterior distribution of the 'log_rho1' parameter (related to the oscillatory signal's period) across emcee, PyMC, and numpyro inference results. Requires ArviZ for data loading and matplotlib for plotting. ```python import arviz as az emcee_data = az.from_emcee( sampler, var_names=[ "mean", "log_sigma1", "log_rho1", "log_tau", "log_sigma2", "log_rho2", "log_jitter", ], ) pm_data = trace numpyro_data = az.from_numpyro(mcmc) bins = np.linspace(1.5, 2.75, 25) plt.hist( np.exp(np.asarray((emcee_data.posterior["log_rho1"].T)).flatten()), bins, histtype="step", density=True, label="emcee", ) plt.hist( np.exp(np.asarray((pm_data.posterior["log_rho1"].T)).flatten()), bins, histtype="step", density=True, label="PyMC", ) plt.hist( np.exp(np.asarray((numpyro_data.posterior["log_rho1"].T)).flatten()), bins, histtype="step", density=True, label="numpyro", ) plt.legend() plt.yticks([]) plt.xlabel(r"$\rho_1$") _ = plt.ylabel(r"$p(\rho_1)$") ``` -------------------------------- ### Conditional JAX Extension Build Source: https://github.com/exoplanet-dev/celerite2/blob/main/CMakeLists.txt Configures the build to optionally include a JAX extension if the BUILD_JAX option is enabled and jaxlib is found. ```cmake option(BUILD_JAX "Build JAX extension (requires jaxlib headers)" ON) if(BUILD_JAX) ``` -------------------------------- ### Adding Python C++ Module (backprop) Source: https://github.com/exoplanet-dev/celerite2/blob/main/CMakeLists.txt Adds a Python module named 'backprop' from the specified C++ source file and sets the C++ standard to C++14. ```cmake pybind11_add_module(backprop "python/celerite2/backprop.cpp") target_compile_features(backprop PUBLIC cxx_std_14) ``` -------------------------------- ### Check for Compiler Flag Support Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/test/CMakeLists.txt Checks if the compiler supports the -Wno-deprecated-copy flag, which is used to suppress deprecation warnings. ```cmake include(CheckCXXCompilerFlag) check_cxx_compiler_flag(-Wno-deprecated-copy HAS_NO_DEPRECATED_COPY) ``` -------------------------------- ### Define Celerite2 Term and GaussianProcess in Theano Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/api/pymc3.md This snippet shows how to import necessary components from celerite2.pymc3 and Theano to define a celerite2 term (SHOTerm) and a GaussianProcess object within the Theano framework. This is a foundational step for using celerite2 in PyMC3 models. ```python import theano.tensor as tt from celerite2.pymc3 import GaussianProcess, terms term = terms.SHOTerm(S0=tt.dscalar(), w0=tt.dscalar(), Q=tt.dscalar()) gp = GaussianProcess(term) ``` -------------------------------- ### Plot Posterior Predictions from MCMC Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Generates a plot showing multiple prediction samples from the MCMC chain, illustrating the uncertainty in the model's predictions. Use this to visualize the range of possible outcomes based on the posterior distribution. ```python chain = sampler.get_chain(discard=100, flat=True) for sample in chain[np.random.randint(len(chain), size=50)]: gp = set_params(sample, gp) conditional = gp.condition(y, true_t) plt.plot(true_t, conditional.sample(), color="C0", alpha=0.1) plt.title("posterior prediction") plot_prediction(None) ``` -------------------------------- ### Adding Python C++ Module (driver) Source: https://github.com/exoplanet-dev/celerite2/blob/main/CMakeLists.txt Adds a Python module named 'driver' from the specified C++ source file and sets the C++ standard to C++14. ```cmake pybind11_add_module(driver "python/celerite2/driver.cpp") target_compile_features(driver PUBLIC cxx_std_14) ``` -------------------------------- ### Set Default Build Type to Release Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/CMakeLists.txt Sets the CMAKE_BUILD_TYPE to 'Release' if it hasn't been specified, ensuring a Release build by default. The CACHE STRING and FORCE options ensure this setting is persistent and overrides previous configurations. ```cmake if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release CACHE STRING "Type of build" FORCE) endif() message(STATUS "Build-type: ${CMAKE_BUILD_TYPE}") ``` -------------------------------- ### Prevent In-Tree Builds Source: https://github.com/exoplanet-dev/celerite2/blob/main/c++/CMakeLists.txt Prevents building the project within its source directory. Users must create a separate build directory. ```cmake if (CMAKE_BINARY_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR) message(FATAL_ERROR "Building in-source is not supported! Create a build dir and remove ${CMAKE_SOURCE_DIR}/CMakeCache.txt") endif() ``` -------------------------------- ### PyMC Gaussian Process Model Definition Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Define a Gaussian Process model with custom terms (SHOTerm) using celerite2's PyMC integration. This snippet is useful for probabilistic modeling of time-series data where the underlying process can be described by a sum of terms. ```python import pymc as pm from celerite2.pymc import GaussianProcess, terms as pm_terms with pm.Model() as model: mean = pm.Normal("mean", mu=0.0, sigma=prior_sigma) log_jitter = pm.Normal("log_jitter", mu=0.0, sigma=prior_sigma) log_sigma1 = pm.Normal("log_sigma1", mu=0.0, sigma=prior_sigma) log_rho1 = pm.Normal("log_rho1", mu=0.0, sigma=prior_sigma) log_tau = pm.Normal("log_tau", mu=0.0, sigma=prior_sigma) term1 = pm_terms.SHOTerm( sigma=pm.math.exp(log_sigma1), rho=pm.math.exp(log_rho1), tau=pm.math.exp(log_tau), ) log_sigma2 = pm.Normal("log_sigma2", mu=0.0, sigma=prior_sigma) log_rho2 = pm.Normal("log_rho2", mu=0.0, sigma=prior_sigma) term2 = pm_terms.SHOTerm( sigma=pm.math.exp(log_sigma2), rho=pm.math.exp(log_rho2), Q=0.25 ) kernel = term1 + term2 gp = GaussianProcess(kernel, mean=mean) gp.compute(t, diag=yerr**2 + pm.math.exp(log_jitter), quiet=True) gp.marginal("obs", observed=y) pm.Deterministic("psd", kernel.get_psd(omega)) trace = pm.sample( tune=1000, draws=1000, target_accept=0.9, init="adapt_full", cores=2, chains=2, random_seed=34923, ) ``` -------------------------------- ### Plot GP Prediction vs. Truth Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/tutorials/first.ipynb Compares the GP model's prediction for the missing data against the true underlying signal and the observed noisy data. ```python def plot_prediction(gp): plt.plot(true_t, true_y, "k", lw=1.5, alpha=0.3, label="data") plt.errorbar(t, y, yerr=yerr, fmt=".k", capsize=0, label="truth") if gp: mu, variance = gp.predict(y, t=true_t, return_var=True) sigma = np.sqrt(variance) plt.plot(true_t, mu, label="prediction") plt.fill_between(true_t, mu - sigma, mu + sigma, color="C0", alpha=0.2) plt.xlabel("x [day]") plt.ylabel("y [ppm]") plt.xlim(0, 10) plt.ylim(-2.5, 2.5) plt.legend() plt.title("initial prediction") plot_prediction(gp) ``` -------------------------------- ### C++ Autodiff Forward Pass Signature Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/api/c++.md Signature for the forward pass of an autodiff function in C++. Output parameters will be resized in place. ```cpp template void func( const Eigen::MatrixBase &x, const Eigen::MatrixBase &Y, Eigen::MatrixBase const &A_out, Eigen::MatrixBase const &b_out, Eigen::MatrixBase const &S_out ) ``` -------------------------------- ### C++ Autodiff Reverse Pass Signature Source: https://github.com/exoplanet-dev/celerite2/blob/main/docs/api/c++.md Signature for the reverse pass of an autodiff function in C++. It calculates the sensitivities of the inputs based on the sensitivities of the outputs. ```cpp template void func_rev( // Original inputs const Eigen::MatrixBase &x, const Eigen::MatrixBase &Y, // Original outputs const Eigen::MatrixBase &A, const Eigen::MatrixBase &b, const Eigen::MatrixBase &S, // The sensitivities of the outputs, note: S is not included const Eigen::MatrixBase &bA, const Eigen::MatrixBase &bb, // The (resulting) sensitivities of the inputs Eigen::MatrixBase const &bx_out, Eigen::MatrixBase const &bY_out ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.