### JSON setup file configuration Source: https://radvel.readthedocs.io/en/latest/_sources/api_service.rst.txt A JSON document defining the RadVel setup parameters, replacing the legacy Python setup module. ```json { "starname": "epic203771098", "nplanets": 2, "instnames": ["j"], "fitting_basis": "per tc secosw sesinw k", "bjd0": 2454833.0, "planet_letters": {"1": "b", "2": "c"}, "params": { "per1": {"value": 20.885258, "vary": false}, "tc1": {"value": 2072.79438, "vary": false}, "secosw1": {"value": 0.0, "vary": false}, "sesinw1": {"value": 0.1, "vary": false}, "k1": {"value": 10.0}, "per2": {"value": 42.363011, "vary": false}, "tc2": {"value": 2082.62516, "vary": false}, "secosw2": {"value": 0.0, "vary": false}, "sesinw2": {"value": 0.1, "vary": false}, "k2": {"value": 10.0}, "dvdt": {"value": 0.0}, "curv": {"value": 0.0}, "gamma_j": {"value": 1.0, "vary": false, "linear": true}, "jit_j": {"value": 2.6} }, "data": {"kind": "dataset_ref", "dataset": "epic203771098.csv"}, "priors": [ {"type": "eccentricity", "num_planets": 2}, {"type": "positivek", "num_planets": 2}, {"type": "jeffreys", "param": "k1", "minval": 0.01, "maxval": 1000}, {"type": "jeffreys", "param": "k2", "minval": 0.01, "maxval": 1000}, {"type": "hardbounds", "param": "jit_j", "minval": 0.0, "maxval": 15.0}, {"type": "gaussian", "param": "dvdt", "mu": 0.0, "sigma": 1.0}, {"type": "gaussian", "param": "curv", "mu": 0.0, "sigma": 0.1} ], "stellar": {"mstar": 1.12, "mstar_err": 0.05} } ``` -------------------------------- ### Initialize and use GeneralRVModel Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/model.html Example showing how to initialize a GeneralRVModel with custom parameters and a forward model function. ```python >>> import radvel # In this example, we'll assume a function called 'my_rv_function' that # computes RV values has been defined elsewhere. We'll assume that # 'my_rv_function' depends on planets' usual RV parameters # contained in radvel.Parameters as well as some additional # parameter, 'my_param'. >>> params = radvel.Parameters(2) >>> params['my_param'] = rv.Parameter(my_param_value,vary=True) >>> rvmodel = radvel.GeneralRVModel(myparams,my_rv_function) >>> rv = rvmodel(10) ``` -------------------------------- ### Posterior Output Example Source: https://radvel.readthedocs.io/en/latest/tutorials/K2-24_Fitting%2BMCMC.html Example output showing parameter values, variation status, and applied priors. ```text parameter value vary per1 20.8853 False tc1 2072.79 False secosw1 0.01 False sesinw1 0.01 False logk1 1.5503 True per2 42.363 False tc2 2082.63 False secosw2 0.01 False sesinw2 0.01 False logk2 1.36832 True dvdt -0.0295124 True curv 0.00183616 True gamma -4.013 False jit 2.08458 True tp1 2070.18 e1 0.0002 w1 0.785398 k1 4.71289 tp2 2077.33 e2 0.0002 w2 0.785398 k2 3.92875 Priors ------ Gaussian prior on jit, mu=1.0986122886681096, sigma=0.5 Gaussian prior on logk2, mu=1.6094379124341003, sigma=10 Gaussian prior on logk1, mu=1.6094379124341003, sigma=10 Gaussian prior on gamma, mu=0, sigma=10 ``` -------------------------------- ### Likelihood Module Imports and Setup Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/likelihood.html Initializes the module by importing necessary libraries and configuring a custom warning formatter. ```python from __future__ import annotations import warnings import numpy as np from numpy.typing import ArrayLike from scipy.linalg import cho_factor, cho_solve import radvel.model from radvel import gp from radvel.model import GeneralRVModel, RVModel _has_celerite = gp._try_celerite() if _has_celerite: import celerite def custom_formatwarning(msg: str, *args: object, **kwargs: object) -> str: # ignore everything except the message return str(msg) + '\n' warnings.formatwarning = custom_formatwarning ``` -------------------------------- ### Create a Parameters object Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/model.html Example of initializing a Parameters object for a 2-planet system with a custom mapping from planet numbers to letters. ```python >>> import radvel # create a Parameters object for a 2-planet system with # custom planet number to letter mapping >>> params = radvel.Parameters(2, planet_letters={1:'d', 2:'e'}) ``` -------------------------------- ### Start the radvel API service Source: https://radvel.readthedocs.io/en/latest/_sources/ui_guide.rst.txt Run the Docker container to start the API service, which includes the UI at /ui. ```console $ docker run --rm -p 8000:8000 -v "$PWD/.runs:/data" \ ghcr.io/california-planet-search/radvel-api:latest $ open http://localhost:8000/ui ``` -------------------------------- ### Quickstart RadVel service with Docker Source: https://radvel.readthedocs.io/en/latest/_sources/api_service.rst.txt Run the RadVel API service using a named Docker volume for data persistence and access the UI at localhost:8000. ```console $ docker run --rm -p 8000:8000 \ -v rv-data:/data \ ghcr.io/california-planet-search/radvel-api:latest $ open http://localhost:8000/ui ``` -------------------------------- ### Initialize MCMC Run Parameters Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/mcmc.html Sets up timing, burn-in status, and convergence tracking variables before starting the MCMC loop. ```python num_run = int(np.round(nrun / (checkinterval -1))) statevars.totsteps = nrun*statevars.nwalkers*statevars.ensembles statevars.mixcount = 0 statevars.ismixed = 0 if proceed and statevars.preburned != 0: statevars.burn_complete = True statevars.nburn = statevars.preburned else: statevars.burn_complete = False statevars.nburn = 0 statevars.ncomplete = statevars.nburn statevars.pcomplete = 0 statevars.rate = 0 statevars.ar = 0 statevars.minAfactor = -1 statevars.maxArchange = np.inf statevars.mintz = -1 statevars.maxgr = np.inf statevars.t0 = time.time() ``` -------------------------------- ### _namespace_from_dict function Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/utils.html Builds a SimpleNamespace mirroring a setup-file's globals from a dict. Shared between initialize_posterior_from_dict and the API setup shim. ```python def _namespace_from_dict(config): """Build a SimpleNamespace mirroring a setup-file's globals from a dict. Shared between :func:`initialize_posterior_from_dict` and the API setup shim that the HTTP service writes into a run directory so the legacy :func:`initialize_posterior` loader sees the same namespace. """ P = types.SimpleNamespace() P.starname = config.get('starname', 'unnamed') P.nplanets = int(config['nplanets']) P.instnames = list(config['instnames']) P.fitting_basis = config['fitting_basis'] P.bjd0 = float(config.get('bjd0', 0.0)) planet_letters = config.get('planet_letters') if planet_letters is not None: P.planet_letters = {int(k): v for k, v in planet_letters.items()} P.data = _data_to_dataframe(config['data']).reset_index(drop=True) # The CLI setup-file convention requires a 'tel' column. Inline-rows # payloads include it explicitly, but built-in CSV fixtures don't — # default to the single instrument when there's only one defined. if 'tel' not in P.data.columns and len(P.instnames) == 1: P.data['tel'] = P.instnames[0] ``` -------------------------------- ### Run radvel fit on example configuration Source: https://radvel.readthedocs.io/en/latest/_sources/quickstartcli.rst.txt Performs a maximum-likelihood fit using the HD164922.py example configuration file. Results are placed by default in a directory named after the configuration file (without .py), or you can specify an output directory with the -o flag. ```bash $ radvel fit -s /path/to/radvel/example_planets/HD164922.py ``` -------------------------------- ### MultiNest execution and result extraction Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/nested_sampling.html Example of running the MultiNest sampler and extracting posterior samples and evidence statistics. ```python ndim = len(post.name_vary_params()) pymultinest.run(loglike, prior_transform, ndim, **run_kwargs) a = pymultinest.Analyzer( outputfiles_basename=run_kwargs["outputfiles_basename"], n_params=ndim ) results = {} results["samples"] = a.get_equal_weighted_posterior()[:, :-1] results["lnZ"] = a.get_stats()["global evidence"] results["lnZerr"] = a.get_stats()["global evidence error"] if tmp: shutil.rmtree(output_dir) return results ``` -------------------------------- ### POST /runs/{run_id}/mcmc Source: https://radvel.readthedocs.io/en/latest/api_service.html Starts an asynchronous MCMC job. ```APIDOC ## POST /runs/{run_id}/mcmc ### Description Starts an asynchronous MCMC job and returns a job_id. ### Method POST ### Endpoint /runs/{run_id}/mcmc ### Parameters #### Path Parameters - **run_id** (string) - Required - The ID of the run. #### Request Body - **nsteps** (integer) - Optional - Number of steps. - **nwalkers** (integer) - Optional - Number of walkers. - **ensembles** (integer) - Optional - Number of ensembles. ``` -------------------------------- ### MultiNest Output Log Source: https://radvel.readthedocs.io/en/latest/tutorials/toi141_fitting_nested_sampling.html Example output from MultiNest v3.10 showing convergence warnings and final log-evidence calculation. ```text ***************************************************** MultiNest v3.10 Copyright Farhan Feroz & Mike Hobson Release Jul 2015 no. of live points = 300 dimensionality = 14 ***************************************************** MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. MultiNest Warning! Parameter 6 of mode 1 is converging towards the edge of the prior. analysing data from tmpdir/out.txt ln(ev)= -688.18227660867854 +/- 0.38357873738457438 Total Likelihood Evaluations: 110915 Sampling finished. Exiting MultiNest ``` -------------------------------- ### radvel.utils.initialize_posterior Source: https://radvel.readthedocs.io/en/latest/utils.html Initializes a Posterior object from a Python setup file. It parses the setup file and initializes the RVModel, Likelihood, Posterior, and priors. ```APIDOC ## radvel.utils.initialize_posterior ### Description Initializes a Posterior object from a Python setup file. It parses the setup file and initializes the RVModel, Likelihood, Posterior, and priors. ### Method Function call ### Endpoint `radvel.utils.initialize_posterior(config_file: str, decorr: bool = False) -> tuple[ModuleType, Posterior]` ### Parameters - **config_file** (string) - Required - Path to config file - **decorr** (bool) - Optional - Decorrelate RVs against columns defined in the decorr_vars list ### Returns - (object representation of config file, radvel.Posterior object) - tuple ### Return Type tuple ``` -------------------------------- ### Install radvel with pip Source: https://radvel.readthedocs.io/en/latest/_sources/quickstartcli.rst.txt Installs radvel via pip. Recommended after setting up a scientific Python environment such as Anaconda or Miniconda. ```bash $ pip install radvel ``` -------------------------------- ### MCMC Execution Output Source: https://radvel.readthedocs.io/en/latest/tutorials/K2-24_Fitting%2BMCMC.html Example console output during the MCMC sampling process. ```text 200000/4000000 (5.0%) steps complete; Running 21445.43 steps/s; Mean acceptance rate = 55.4%; Min Auto Factor = 75; Max Auto Relative-Change = inf; Min Tz = 18327.9; Max G-R = 1.002 Discarding burn-in now that the chains are marginally well-mixed 460000/4000000 (11.5%) steps complete; Running 17740.35 steps/s; Mean acceptance rate = 55.0%; Min Auto Factor = 90; Max Auto Relative-Change = 0.0245; Min Tz = 16833.8; Max G-R = 1.002 Chains are well-mixed after 460000 steps! MCMC completed in 23.4 seconds ``` -------------------------------- ### initialize_posterior function Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/utils.html Initializes a Posterior object from a Python setup file. Parses the file and returns a tuple of the config module and Posterior object. ```python [docs] def initialize_posterior(config_file: str, decorr: bool = False) -> tuple[ModuleType, radvel.posterior.Posterior]: """Initialize Posterior object from a Python setup file. Parse a setup file and initialize the RVModel, Likelihood, Posterior and priors. Args: config_file (string): path to config file decorr (bool): (optional) decorrelate RVs against columns defined in the decorr_vars list Returns: tuple: (object representation of config file, radvel.Posterior object) """ system_name = os.path.basename(config_file).split('.')[0] P = load_module_from_file(system_name, os.path.abspath(config_file)) return _finalise_posterior(P, decorr=decorr) ``` -------------------------------- ### radvel.report module imports and setup Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/report.html Imports required modules, sets up the Jinja2 environment, and defines the print basis and units dictionary used for parameter labels. ```python from __future__ import annotations from types import ModuleType import numpy as np import pandas as pd import subprocess import os import tempfile import shutil from operator import itemgetter from jinja2 import Environment, PackageLoader, select_autoescape import radvel from radvel.posterior import Posterior env = Environment(loader=PackageLoader('radvel', 'templates')) print_basis = 'per tc tp e w k' units = { 'per': 'days', 'tp': 'JD', 'tc': 'JD', 'e': '', 'w': 'radians', 'k': 'm s$^{-1}$', 'logk': r'$\ln{(\rm m\ s^{-1})}$', 'secosw': '', 'sesinw': '', 'gamma': 'm s$-1$', 'jitter': 'm s$-1$', 'logjit': r'$\ln{(\rm m\ s^{-1})}$', 'jit': r'$\rm m\ s^{-1}$', 'dvdt': 'm s$^{-1}$ d$^{-1}$', 'curv': 'm s$^{-1}$ d$^{-2}$', 'gp_amp': 'm s$-1$', 'gp_explength': 'days', 'gp_per': 'days', 'gp_perlength': '', # 'mpsini': '$M_\earth$', # 'rp': '$R_\earth$', # 'rhop': 'g cm$^{-3}$', } ``` -------------------------------- ### Define a UserDefinedPrior Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/prior.html Example of how to define a custom prior using the UserDefinedPrior class by providing a function that returns the log-value of a PDF. ```python >>> def myPriorFunc(inp_list): ... if inp_list[0] > 0. and inp_list[0] < 1.: ... return 0. ... else: ... return -np.inf >>> myTexString = 'Uniform Prior on $\sqrt{e}$' >>> myPrior = radvel.prior.UserDefinedPrior(['se'], myPriorFunc, myTexString) ``` -------------------------------- ### radvel.utils.initialize_posterior_from_dict Source: https://radvel.readthedocs.io/en/latest/utils.html Initializes a Posterior object from an in-memory dict. It mirrors the namespace of a Python setup file but accepts JSON-friendly types so callers can build a posterior without writing a file to disk first. ```APIDOC ## radvel.utils.initialize_posterior_from_dict ### Description Initializes a Posterior object from an in-memory dict. It mirrors the namespace of a Python setup file but accepts JSON-friendly types so callers can build a posterior without writing a file to disk first. ### Method Function call ### Endpoint `radvel.utils.initialize_posterior_from_dict(config, decorr=False) -> tuple[SimpleNamespace, Posterior]` ### Parameters - **config** (dict) - Required - Mapping with keys `starname`, `nplanets`, `instnames`, `fitting_basis`, `params`, `data`, `priors`, optionally `bjd0`, `time_base`, `planet_letters`, `stellar`, `planet`, `decorr_vars`, `hnames`, `kernel_name`, `any_basis`, `anybasis_params`. - **decorr** (bool) - Optional - Same meaning as `initialize_posterior()`. ### Returns - (SimpleNamespace mirroring the legacy `P` module, radvel.Posterior) - tuple ### Return Type tuple ``` -------------------------------- ### radvel derive Source: https://radvel.readthedocs.io/en/latest/_sources/quickstartcli.rst.txt Combines RV time-series properties with host star parameters from the setup file to derive physical parameters for the planetary system. See the epic203771098.py example for including stellar parameters. ```bash $ radvel derive -s /path/to/radvel/example_planets/HD164922.py ``` -------------------------------- ### Install radvel in development mode Source: https://radvel.readthedocs.io/en/latest/_sources/quickstartcli.rst.txt Development installation for contributing to radvel. Clones the repository, installs problematic dependencies via conda (recommended for macOS), and installs radvel in editable mode. ```bash $ git clone https://github.com/California-Planet-Search/radvel.git $ cd radvel # Install problematic dependencies via conda (recommended for macOS) $ conda install pytables h5py # Install radvel in development mode $ pip install -e . ``` -------------------------------- ### Initialize Ensemble Samplers Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/mcmc.html Sets up the emcee EnsembleSampler objects and initial positions for each ensemble. ```python statevars.samplers = [] statevars.samples = [] statevars.initial_positions = [] for e in range(ensembles): pi = post.get_vary_params() p0 = np.vstack([pi]*statevars.nwalkers) p0 += [np.random.rand(statevars.ndim)*pscales for i in range(statevars.nwalkers)] if not proceed: statevars.initial_positions.append(p0) else: statevars.initial_positions.append(statevars.prechains[e][-1, :, :]) statevars.samplers.append(emcee.EnsembleSampler(statevars.nwalkers, statevars.ndim, post.logprob_array)) ``` -------------------------------- ### Install radvel on macOS with conda dependencies Source: https://radvel.readthedocs.io/en/latest/_sources/quickstartcli.rst.txt Alternative installation for macOS users encountering compilation issues, especially with newer Xcode versions. Installs problematic dependencies via conda before installing radvel. ```bash $ conda install pytables h5py $ pip install radvel ``` -------------------------------- ### Import necessary libraries Source: https://radvel.readthedocs.io/en/latest/tutorials/K2-24_Fitting%2BMCMC.html Initializes the environment with required scientific and plotting libraries. ```python %matplotlib inline import os import matplotlib import numpy as np import pylab as pl import pandas as pd from scipy import optimize import corner import radvel import radvel.likelihood from radvel.plot import orbit_plots, mcmc_plots matplotlib.rcParams['font.size'] = 14 ``` -------------------------------- ### Build and Optimize Three-Planet Model Source: https://radvel.readthedocs.io/en/latest/tutorials/toi141_fitting_nested_sampling.html Initializes a three-planet model and performs optimization using the Nelder-Mead method. ```python post_three = build_model(3) res = optimize.minimize( post_three.neglogprob_array, post_three.get_vary_params(), method='Nelder-Mead', options=dict(maxiter=200, maxfev=100000, xatol=1e-8) ) post_three.set_vary_params(res.x) print(post_three) ``` -------------------------------- ### GET /jobs/{id} Source: https://radvel.readthedocs.io/en/latest/api_service.html Polls the status of an asynchronous job. ```APIDOC ## GET /jobs/{id} ### Description Retrieves the current state and telemetry of an asynchronous job. ### Method GET ### Endpoint /jobs/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the job. ``` -------------------------------- ### Build Two-Planet Model Source: https://radvel.readthedocs.io/en/latest/tutorials/toi141_fitting_nested_sampling.html Initializes the two-planet model by passing 2 to the build_model function and prints the parameter configuration. ```python post_two = build_model(2) print(post_two) ``` -------------------------------- ### Run UltraNest Sampler Source: https://radvel.readthedocs.io/en/latest/tutorials/k2_24_demo_all_samplers.html Executes the UltraNest sampler and prints the execution time. ```python ultranest_start = time.time() # Ultranest does not accept False for "resume" ultranest_results = rns.run(post, sampler="ultranest", output_dir="ultranest_demo", proceed=PROCEED, overwrite=OVERWRITE) ultranest_time = time.time() - ultranest_start print(f"Running ultranest took {ultranest_time / 60:.2f} min") ``` ```text [ultranest] Sampling 400 live points from prior ... [ultranest] Explored until L=-8e+01 8 [-82.8705..-82.8701]*| it/evals=10099/269614 eff=3.7513% N=400 0 00 0 [ultranest] Likelihood function evaluations: 269614 [ultranest] Writing samples and results to disk ... [ultranest] Writing samples and results to disk ... done [ultranest] logZ = -103.4 +- 0.1932 [ultranest] Effective samples strategy satisfied (ESS = 2740.8, need >400) [ultranest] Posterior uncertainty strategy is satisfied (KL: 0.46+-0.07 nat, need <0.50 nat) [ultranest] Evidency uncertainty strategy is satisfied (dlogz=0.19, need <0.5) [ultranest] logZ error budget: single: 0.21 bs:0.19 tail:0.01 total:0.19 required:<0.50 [ultranest] done iterating. Running ultranest took 4.17 min ``` -------------------------------- ### GET /runs/{run_id}/files/{filename} Source: https://radvel.readthedocs.io/en/latest/api_service.html Downloads a file associated with a run. ```APIDOC ## GET /runs/{run_id}/files/{filename} ### Description Downloads a specific file generated by the run. ### Method GET ### Endpoint /runs/{run_id}/files/{filename} ### Parameters #### Path Parameters - **run_id** (string) - Required - The ID of the run. - **filename** (string) - Required - The name of the file to download. ``` -------------------------------- ### Initialize radvel Parameters Source: https://radvel.readthedocs.io/en/latest/tutorials/GaussianProcess-tutorial.html Create a Parameters object for a single-planet system. ```python nplanets=1 params = radvel.Parameters(nplanets,basis='per tc secosw sesinw k') ``` -------------------------------- ### Run Dynesty Static Sampler Source: https://radvel.readthedocs.io/en/latest/tutorials/k2_24_demo_all_samplers.html Executes the static Dynesty sampler and prints the execution time. ```python dynesty_start = time.time() dynesty_results = rns.run(post, sampler="dynesty-static", output_dir="dynesty_demo", proceed=PROCEED, overwrite=OVERWRITE) dynesty_time = time.time() - dynesty_start print(f"Running dynesty took {dynesty_time / 60:.2f} min") ``` ```text iter: 10799 | +500 | bound: 1410 | nc: 1 | ncall: 1075955 | eff(%): 1.051 | loglstar: -inf < -82.470 < inf | logz: -103.429 +/- nan | dlogz: 0.001 > 0.509 Running dynesty took 15.31 min ``` -------------------------------- ### Import necessary libraries Source: https://radvel.readthedocs.io/en/latest/tutorials/GaussianProcess-tutorial.html Perform preliminary imports for data handling, radvel modeling, and optimization. ```python import numpy as np import pandas as pd import os import radvel import radvel.likelihood from radvel.plot import orbit_plots, mcmc_plots from scipy import optimize %matplotlib inline ``` -------------------------------- ### Compare Model Evidence Source: https://radvel.readthedocs.io/en/latest/tutorials/toi141_fitting_nested_sampling.html Print the log-evidence values for one, two, and three-planet models to determine the best fit. ```python print(f"Evidence one planet: {results_single['lnZ']:.2f} +/- {results_single['lnZerr']:.2f}") print(f"Evidence two planet: {results_two['lnZ']:.2f} +/- {results_two['lnZerr']:.2f}") print(f"Evidence three planet: {results_three['lnZ']:.2f} +/- {results_three['lnZerr']:.2f}") ``` -------------------------------- ### Run nested sampling with PyMultiNest (_run_multinest) Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/nested_sampling.html Configures and runs the PyMultiNest sampler. It sets outputfiles_basename to /out and resume to proceed. Raises ValueError if 'outputfiles_basename' or 'resume' are in run_kwargs. Creates the output directory if needed. Returns a dictionary with samples, lnZ, and lnZerr. ```python import pymultinest run_kwargs = run_kwargs or {} # By default, assume we want a temporary output dir tmp = True if output_dir is None: output_dir = "tmpdir" else: # if an actual outupt dir was specified, it is not temporary tmp = False if "outputfiles_basename" in run_kwargs: raise ValueError( "outputfiles_basename not supported for multinest. Use radvel's output_dir instead." ) run_kwargs["outputfiles_basename"] = os.path.join(output_dir, "out") if "resume" in run_kwargs: raise ValueError( "'resume' not supported for multinest. Use radvel's 'proceed' instead." ) run_kwargs["resume"] = proceed os.makedirs(output_dir, exist_ok=tmp or overwrite or proceed) ``` -------------------------------- ### Plot initial model Source: https://radvel.readthedocs.io/en/latest/tutorials/K2-24_Fitting%2BMCMC.html Visualizes the initial model fit before optimization. ```python pl.figure() plot_results(like) ``` ```text
``` -------------------------------- ### POST /runs Source: https://radvel.readthedocs.io/en/latest/api_service.html Creates a new run. ```APIDOC ## POST /runs ### Description Creates a new run and returns the run_id. ### Method POST ### Endpoint /runs ``` -------------------------------- ### Run MultiNest Sampler Source: https://radvel.readthedocs.io/en/latest/tutorials/k2_24_demo_all_samplers.html Executes the MultiNest sampler and prints the execution time. ```python multinest_start = time.time() multinest_results = rns.run(post, sampler="multinest", output_dir="multinest_demo", proceed=PROCEED, overwrite=OVERWRITE) multinest_time = time.time() - multinest_start print(f"Running multinest took {multinest_time / 60:.2f} min") ``` ```text ***************************************************** MultiNest v3.10 Copyright Farhan Feroz & Mike Hobson Release Jul 2015 no. of live points = 400 dimensionality = 5 ***************************************************** analysing data from multinest_demo/out.txt ln(ev)= -102.44719426706034 +/- 0.20587852822593408 Total Likelihood Evaluations: 21919 Sampling finished. Exiting MultiNest Running multinest took 0.32 min ``` -------------------------------- ### Create and activate conda virtual environment Source: https://radvel.readthedocs.io/en/latest/_sources/OSX-multiprocessing.rst.txt Optional step to create and activate a conda virtual environment for best results before rebuilding numpy. ```bash $ conda create --name radvel_virtualenv --python=3.6 # create a virtual environment for best results $ source activate radvel_virtualenv # activate the newly minted virtual environment ``` -------------------------------- ### Use working_directory context manager Source: https://radvel.readthedocs.io/en/latest/utils.html Demonstrates using the working_directory function with a with statement to execute code within a specific directory. ```python >>> with workdir('/temp'): # do something within the /temp directory ``` -------------------------------- ### Run Dynesty Dynamic Sampler Source: https://radvel.readthedocs.io/en/latest/tutorials/k2_24_demo_all_samplers.html Executes the dynamic Dynesty sampler and prints the execution time. ```python dynesty_start = time.time() dynesty_dynamic_results = rns.run(post, sampler="dynesty-dynamic", output_dir="dynesty_demo_dynamic", proceed=PROCEED, overwrite=OVERWRITE) dynesty_time = time.time() - dynesty_start print(f"Running dynesty took {dynesty_time / 60:.2f} min") ``` ```text iter: 21418 | batch: 5 | bound: 38 | nc: 1 | ncall: 1425431 | eff(%): 1.492 | loglstar: -89.495 < -82.594 < -83.899 | logz: -103.194 +/- 0.133 | stop: 0.798 Running dynesty took 21.37 min ``` -------------------------------- ### CeleriteLikelihood.predict: Wrapper for celerite.GP.predict Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/likelihood.html Predicts GP means and standard deviations using the celerite solver. Raises ImportError if celerite is not installed. Extracts hyperparameters gp_B, gp_C, gp_L, and gp_Prot from the kernel. ```python def predict(self, xpred: ArrayLike) -> tuple[np.ndarray, np.ndarray]: """ Realize the GP using the current values of the hyperparameters at values x=xpred. Used for making GP plots. Wrapper for `celerite.GP.predict()`. Args: xpred (np.array): numpy array of x values for realizing the GP Returns: tuple: tuple containing: np.array: numpy array of predictive means \n np.array: numpy array of predictive standard deviations """ if not _has_celerite: raise ImportError("celerite is required for CeleriteLikelihood") self.update_kernel_params() B = self.kernel.hparams['gp_B'].value C = self.kernel.hparams['gp_C'].value L = self.kernel.hparams['gp_L'].value Prot = self.kernel.hparams['gp_Prot'].value ``` -------------------------------- ### Reinstall numpy-dependent packages Source: https://radvel.readthedocs.io/en/latest/OSX-multiprocessing.html Reinstalls packages that depend on numpy after rebuilding it. Installs scipy, matplotlib, cython, astropy, pandas via conda, then corner, celerite, emcee via pip, and finally upgrades radvel. ```bash $ conda install scipy matplotlib cython astropy pandas $ pip install corner celerite emcee $ pip install radvel --upgrade #reinstall radvel ``` -------------------------------- ### Configure Parameters from Config Dictionary Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/utils.html Sets up a radvel.Parameters object from a configuration dictionary, handling time_base, basis conversion, priors, and optional stellar/planet/decorr/hnames/kernel settings. ```python if config.get('time_base') is not None: P.time_base = float(config['time_base']) else: P.time_base = float(np.mean([P.data.time.min(), P.data.time.max()])) any_basis = config.get('any_basis') or P.fitting_basis params_in = config['params'] if isinstance(params_in, radvel.Parameters): params_obj = params_in else: params_obj = _build_parameters(params_in, P.nplanets, any_basis) if str(params_obj.basis) != "Basis Object <{}>".format(P.fitting_basis): params_obj = params_obj.basis.to_any_basis(params_obj, P.fitting_basis) P.params = params_obj P.priors = [_build_prior(p) if isinstance(p, dict) else p for p in config.get('priors', [])] if config.get('stellar') is not None: P.stellar = dict(config['stellar']) if config.get('planet') is not None: P.planet = dict(config['planet']) if config.get('decorr_vars'): P.decorr_vars = list(config['decorr_vars']) if config.get('hnames'): P.hnames = {k: list(v) for k, v in config['hnames'].items()} if config.get('kernel_name'): P.kernel_name = dict(config['kernel_name']) return P ``` -------------------------------- ### Load and prepare TOI-141 RV data Source: https://radvel.readthedocs.io/en/latest/tutorials/toi141_fitting_nested_sampling.html Reads the RV data from radvel's example data directory, extracts time, velocity, error, and instrument arrays, and defines time offsets and instrument groups. ```python data_df = read_csv(os.path.join(radvel.DATADIR, "rvs_toi141.dat"), sep=" ", names=["t", "rv", "erv", "inst"]) t, vel, errvel, inst = data_df.t.values, data_df.rv.values, data_df.erv.values, data_df.inst.values min_time = np.min(t[inst == "FEROS"]) - 30.0 max_time = np.max(t[inst == "FEROS"]) + 30.0 t_mod = np.linspace(min_time, max_time, 1000) inst_groups = data_df.groupby("inst").groups inst_names = list(inst_groups.keys()) T_OFF = 2457000.0 ``` -------------------------------- ### Perform preliminary imports Source: https://radvel.readthedocs.io/en/latest/tutorials/CustomModel-tutorial.html Import necessary libraries for data handling, plotting, and modeling. ```python import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy import optimize import corner import radvel import radvel.likelihood import batman matplotlib.rcParams['font.size'] = 14 ``` -------------------------------- ### Run nested sampling with ultranest (_run_ultranest) Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/nested_sampling.html Configures and runs the ultranest ReactiveNestedSampler. It sets the sampler's log_dir to output_dir and resume to proceed or 'overwrite'. Raises ValueError if 'log_dir' or 'resume' are in sampler_kwargs. For more than 7 parameters, it uses a SliceSampler with nsteps = 2 * num_params. Returns a dictionary with samples, lnZ, lnZerr, and the sampler object. ```python from ultranest import ReactiveNestedSampler from ultranest.stepsampler import SliceSampler, generate_mixture_random_direction run_kwargs = run_kwargs or {} sampler_kwargs = sampler_kwargs or {} if "log_dir" in sampler_kwargs: raise ValueError( "log_dir not supported for ultranest. Use radvel's output_dir instead." ) if "resume" in sampler_kwargs: raise ValueError( "'resume' not supported for ultranest. Use radvel's 'proceed' instead." ) sampler_kwargs["resume"] = proceed or 'overwrite' sampler_kwargs["log_dir"] = output_dir param_names = post.name_vary_params() wrapped_params = [pn.startswith(("tc", "tp")) for pn in param_names] # I guess simplest is to use overwrite or re-run sampler = ReactiveNestedSampler( param_names, post.likelihood_ns_array, post.prior_transform, wrapped_params=wrapped_params, **sampler_kwargs, ) num_params = len(param_names) if num_params > 7: nsteps = len(param_names) * 2 sampler.stepsampler = SliceSampler( nsteps=nsteps, generate_direction=generate_mixture_random_direction, ) sampler.run(**run_kwargs) results = { "samples": sampler.results["samples"], "lnZ": sampler.results["logz"], "lnZerr": sampler.results["logzerr"], "sampler": sampler, } return results ``` -------------------------------- ### TexTable Class Initialization Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/report.html Initializes the TexTable class to handle LaTeX table generation for the summary PDF. ```python class TexTable(RadvelReport): """LaTeX table Class to handle generation of the LaTeX tables within the summary PDF. Args: report (radvel.report.RadvelReport): radvel report object full (bool): get full-length RV table [default: True] """ def __init__(self, report: RadvelReport) -> None: self.report = report self.post = report.post self.quantiles = report.quantiles self.fitting_basis = report.post.params.basis.name self.minafactor = report.minafactor self.maxarchange = report.maxarchange self.maxgr = report.maxgr self.mintz = report.mintz ``` -------------------------------- ### Run MCMC to estimate parameter uncertainties Source: https://radvel.readthedocs.io/en/latest/tutorials/CustomModel-tutorial.html Runs Markov-Chain Monte Carlo with 50 walkers and 500 steps to estimate parameter uncertainties. The tutorial notes that in practice at least 10000 steps and ~50 walkers are recommended. ```python df = radvel.mcmc(post,nwalkers=50,nrun=500) ``` -------------------------------- ### Run Nautilus Sampler Source: https://radvel.readthedocs.io/en/latest/tutorials/k2_24_demo_all_samplers.html Executes the Nautilus sampler with verbose output enabled and prints the execution time. ```python nautilus_start = time.time() nautilus_results = rns.run(post, sampler="nautilus", output_dir="nautilus_demo", proceed=PROCEED, run_kwargs={"verbose": True}, overwrite=OVERWRITE) nautilus_time = time.time() - nautilus_start print(f"Running nautilus took {nautilus_time / 60:.2f} min") ``` ```text Starting the nautilus sampler... Please report issues at github.com/johannesulf/nautilus. Status | Bounds | Ellipses | Networks | Calls | f_live | N_eff | log Z Finished | 36 | 1 | 4 | 81100 | N/A | 19922 | -103.33 Running nautilus took 5.81 min ``` -------------------------------- ### Show radvel CLI help Source: https://radvel.readthedocs.io/en/latest/_sources/quickstartcli.rst.txt Displays the radvel command-line help, listing available subcommands (fit, plot, mcmc, ns, derive, bic, table, report) and options. ```bash $ radvel --help usage: RadVel [-h] [--version] {fit,plot,mcmc,ns,derive,bic,table,report} ... RadVel: The Radial Velocity Toolkit optional arguments: -h, --help show this help message and exit --version Print version number and exit. subcommands: {fit,plot,mcmc,ns,derive,bic,table,report} ``` -------------------------------- ### Set initial likelihood parameters Source: https://radvel.readthedocs.io/en/latest/tutorials/K2-24_Fitting%2BMCMC.html Creates the RVLikelihood object and sets initial guesses for gamma and jitter parameters. ```python mod = initialize_model() like = radvel.likelihood.RVLikelihood(mod, t, vel, errvel) like.params['gamma'] = radvel.Parameter(value=0.1, vary=False, linear=True) like.params['jit'] = radvel.Parameter(value=1.0) ``` -------------------------------- ### Run MCMC exploration Source: https://radvel.readthedocs.io/en/latest/tutorials/GaussianProcess-tutorial.html Explores the parameter space using MCMC. Note that convergence tests may fail with low nrun values. ```python chains = radvel.mcmc(gppost,nrun=100,ensembles=3,savename='rawchains.h5') ``` ```text 15000/15000 (100.0%) steps complete; Running 1231.70 steps/s; Mean acceptance rate = 45.7%; Min Auto Factor = 12; Max Auto Relative-Change = 0.978; Min Tz = 248.2; Max G-R = 1.012 Discarding burn-in now that the chains are marginally well-mixed MCMC: WARNING: chains did not pass convergence tests. They are likely not well-mixed. ``` -------------------------------- ### List implemented GP kernels Source: https://radvel.readthedocs.io/en/latest/tutorials/GaussianProcess-tutorial.html Print the available GP kernels and their associated hyperparameters. ```python print(radvel.gp.KERNELS) ``` ```python {'SqExp': ['gp_length', 'gp_amp'], 'Per': ['gp_per', 'gp_length', 'gp_amp'], 'QuasiPer': ['gp_per', 'gp_perlength', 'gp_explength', 'gp_amp'], 'Celerite': ['gp_B', 'gp_C', 'gp_L', 'gp_Prot']} ``` -------------------------------- ### CeleriteLikelihood.__init__: Sort inputs by time Source: https://radvel.readthedocs.io/en/latest/_modules/radvel/likelihood.html Initializes the CeleriteLikelihood, calling the parent constructor with kernel_name='Celerite' and sorting the input arrays by time order, which is required for celerite calculations. ```python def __init__(self, model: RVModel, t: np.ndarray, vel: np.ndarray, errvel: np.ndarray, hnames: list[str], suffix: str = '', **kwargs) -> None: super(CeleriteLikelihood, self).__init__( model, t, vel, errvel, hnames, suffix=suffix, kernel_name='Celerite' ) # Sort inputs in time order. Required for celerite calculations. order = np.argsort(self.x) self.x = self.x[order] self.y = self.y[order] self.yerr = self.yerr[order] self.N = len(self.x) ``` -------------------------------- ### Run Nested Sampling with PyMultiNest Source: https://radvel.readthedocs.io/en/latest/tutorials/toi141_fitting_nested_sampling.html Executes nested sampling using the PyMultiNest sampler with 300 live points. The results include Bayesian evidence and posterior samples. ```python from radvel import nested_sampling results_single = nested_sampling.run(post_single, sampler="multinest", proceed=False, run_kwargs={"n_live_points": 300}) samples_single = results_single["samples"].values[:, :-1] ``` ```text ***************************************************** MultiNest v3.10 Copyright Farhan Feroz & Mike Hobson Release Jul 2015 no. of live points = 300 dimensionality = 11 ***************************************************** analysing data from tmpdir/out.txt ln(ev)= -802.03188163585685 +/- 0.29243469363345131 Total Likelihood Evaluations: 70820 Sampling finished. Exiting MultiNest ``` -------------------------------- ### Initialize and print single-planet model Source: https://radvel.readthedocs.io/en/latest/tutorials/toi141_fitting_nested_sampling.html Calls the builder function for a single planet and prints the resulting posterior object. ```python post_single = build_model(1) print(post_single) ``` -------------------------------- ### Run MCMC Analysis Source: https://radvel.readthedocs.io/en/latest/tutorials/K2-24_Fitting%2BMCMC.html Execute the MCMC sampler to estimate parameter uncertainties, saving the results to an HDF5 file. ```python df = radvel.mcmc(post,nwalkers=50,nrun=10000,savename='rawchains.h5') ```