API

This page details the methods and classes provided by the dynesty module.

Top-Level Interface

The top-level interface (defined natively upon initialization) that provides access to the two main sampler “super-classes” via NestedSampler() and DynamicNestedSampler().

dynesty.dynesty.NestedSampler(loglikelihood, prior_transform, ndim, nlive=500, bound='multi', sample='auto', periodic=None, reflective=None, update_interval=None, first_update=None, npdim=None, rstate=None, queue_size=None, pool=None, use_pool=None, live_points=None, logl_args=None, logl_kwargs=None, ptform_args=None, ptform_kwargs=None, gradient=None, grad_args=None, grad_kwargs=None, compute_jac=False, enlarge=None, bootstrap=0, vol_dec=0.5, vol_check=2.0, walks=25, facc=0.5, slices=5, fmove=0.9, max_move=100, update_func=None, ncdim=None, save_history=False, history_filename=None, **kwargs)

Initializes and returns a sampler object for Static Nested Sampling.

Parameters:
loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

prior_transform : function

Function translating a unit cube to the parameter space according to the prior. The input is a 1-d numpy array with length ndim, where each value is in the range [0, 1). The return value should also be a 1-d numpy array with length ndim, where each value is a parameter. The return value is passed to the loglikelihood function. For example, for a 2 parameter model with flat priors in the range [0, 2), the function would be:

def prior_transform(u):
    return 2.0 * u
ndim : int

Number of parameters returned by prior_transform and accepted by loglikelihood.

nlive : int, optional

Number of “live” points. Larger numbers result in a more finely sampled posterior (more accurate evidence), but also a larger number of iterations required to converge. Default is 500.

bound : {'none', 'single', 'multi', 'balls', 'cubes'}, optional

Method used to approximately bound the prior using the current set of live points. Conditions the sampling methods used to propose new live points. Choices are no bound ('none'), a single bounding ellipsoid ('single'), multiple bounding ellipsoids ('multi'), balls centered on each live point ('balls'), and cubes centered on each live point ('cubes'). Default is 'multi'.

sample : {'auto', 'unif', 'rwalk', 'rstagger',

'slice', 'rslice', 'hslice', callable}, optional

Method used to sample uniformly within the likelihood constraint, conditioned on the provided bounds. Unique methods available are: uniform sampling within the bounds('unif'), random walks with fixed proposals ('rwalk'), random walks with variable (“staggering”) proposals ('rstagger'), multivariate slice sampling along preferred orientations ('slice'), “random” slice sampling along all orientations ('rslice'), “Hamiltonian” slices along random trajectories ('hslice'), and any callable function which follows the pattern of the sample methods defined in dynesty.sampling. 'auto' selects the sampling method based on the dimensionality of the problem (from ndim). When ndim < 10, this defaults to 'unif'. When 10 <= ndim <= 20, this defaults to 'rwalk'. When ndim > 20, this defaults to 'hslice' if a gradient is provided and 'slice' otherwise. 'rstagger' and 'rslice' are provided as alternatives for 'rwalk' and 'slice', respectively. Default is 'auto'.

periodic : iterable, optional

A list of indices for parameters with periodic boundary conditions. These parameters will not have their positions constrained to be within the unit cube, enabling smooth behavior for parameters that may wrap around the edge. Default is None (i.e. no periodic boundary conditions).

reflective : iterable, optional

A list of indices for parameters with reflective boundary conditions. These parameters will not have their positions constrained to be within the unit cube, enabling smooth behavior for parameters that may reflect at the edge. Default is None (i.e. no reflective boundary conditions).

update_interval : int or float, optional

If an integer is passed, only update the proposal distribution every update_interval-th likelihood call. If a float is passed, update the proposal after every round(update_interval * nlive)-th likelihood call. Larger update intervals larger can be more efficient when the likelihood function is quick to evaluate. Default behavior is to target a roughly constant change in prior volume, with 1.5 for 'unif', 0.15 * walks for 'rwalk' and 'rstagger', 0.9 * ndim * slices for 'slice', 2.0 * slices for 'rslice', and 25.0 * slices for 'hslice'.

first_update : dict, optional

A dictionary containing parameters governing when the sampler should first update the bounding distribution from the unit cube ('none') to the one specified by sample. Options are the minimum number of likelihood calls ('min_ncall') and the minimum allowed overall efficiency in percent ('min_eff'). Defaults are 2 * nlive and 10., respectively.

npdim : int, optional

Number of parameters accepted by prior_transform. This might differ from ndim in the case where a parameter of loglikelihood is dependent upon multiple independently distributed parameters, some of which may be nuisance parameters.

rstate : RandomState, optional
RandomState instance. If not given, the

global random state of the random module will be used.

queue_size : int, optional

Carry out likelihood evaluations in parallel by queueing up new live point proposals using (at most) queue_size many threads. Each thread independently proposes new live points until the proposal distribution is updated. If no value is passed, this defaults to pool.size (if a pool has been provided) and 1 otherwise (no parallelism).

pool : user-provided pool, optional

Use this pool of workers to execute operations in parallel.

use_pool : dict, optional

A dictionary containing flags indicating where a pool should be used to execute operations in parallel. These govern whether prior_transform is executed in parallel during initialization ('prior_transform'), loglikelihood is executed in parallel during initialization ('loglikelihood'), live points are proposed in parallel during a run ('propose_point'), and bounding distributions are updated in parallel during a run ('update_bound'). Default is True for all options.

live_points : list of 3 ndarray each with shape (nlive, ndim)

A set of live points used to initialize the nested sampling run. Contains live_u, the coordinates on the unit cube, live_v, the transformed variables, and live_logl, the associated loglikelihoods. By default, if these are not provided the initial set of live points will be drawn uniformly from the unit npdim-cube. WARNING: It is crucial that the initial set of live points have been sampled from the prior. Failure to provide a set of valid live points will result in incorrect results.

logl_args : iterable, optional

Additional arguments that can be passed to loglikelihood.

logl_kwargs : dict, optional

Additional keyword arguments that can be passed to loglikelihood.

ptform_args : iterable, optional

Additional arguments that can be passed to prior_transform.

ptform_kwargs : dict, optional

Additional keyword arguments that can be passed to prior_transform.

gradient : function, optional

A function which returns the gradient corresponding to the provided loglikelihood with respect to the unit cube. If provided, this will be used when computing reflections when sampling with 'hslice'. If not provided, gradients are approximated numerically using 2-sided differencing.

grad_args : iterable, optional

Additional arguments that can be passed to gradient.

grad_kwargs : dict, optional

Additional keyword arguments that can be passed to gradient.

compute_jac : bool, optional

Whether to compute and apply the Jacobian dv/du from the target space v to the unit cube u when evaluating the gradient. If False, the gradient provided is assumed to be already defined with respect to the unit cube. If True, the gradient provided is assumed to be defined with respect to the target space so the Jacobian needs to be numerically computed and applied. Default is False.

enlarge : float, optional

Enlarge the volumes of the specified bounding object(s) by this fraction. The preferred method is to determine this organically using bootstrapping. If bootstrap > 0, this defaults to 1.0. If bootstrap = 0, this instead defaults to 1.25.

bootstrap : int, optional

Compute this many bootstrapped realizations of the bounding objects. Use the maximum distance found to the set of points left out during each iteration to enlarge the resulting volumes. Can lead to unstable bounding ellipsoids. Default is 0 (no bootstrap).

vol_dec : float, optional

For the 'multi' bounding option, the required fractional reduction in volume after splitting an ellipsoid in order to to accept the split. Default is 0.5.

vol_check : float, optional

For the 'multi' bounding option, the factor used when checking if the volume of the original bounding ellipsoid is large enough to warrant > 2 splits via ell.vol > vol_check * nlive * pointvol. Default is 2.0.

walks : int, optional

For the 'rwalk' sampling option, the minimum number of steps (minimum 2) before proposing a new live point. Default is 25.

facc : float, optional

The target acceptance fraction for the 'rwalk' sampling option. Default is 0.5. Bounded to be between [1. / walks, 1.].

slices : int, optional

For the 'slice', 'rslice', and 'hslice' sampling options, the number of times to execute a “slice update” before proposing a new live point. Default is 5. Note that 'slice' cycles through all dimensions when executing a “slice update”.

fmove : float, optional

The target fraction of samples that are proposed along a trajectory (i.e. not reflecting) for the 'hslice' sampling option. Default is 0.9.

max_move : int, optional

The maximum number of timesteps allowed for 'hslice' per proposal forwards and backwards in time. Default is 100.

update_func : function, optional

Any callable function which takes in a blob and scale as input and returns a modification to the internal scale as output. Must follow the pattern of the update methods defined in dynesty.nestedsamplers. If provided, this will supersede the default functions used to update proposals. In the case where a custom callable function is passed to sample but no similar function is passed to update_func, this will default to no update.

ncdim: int, optional

The number of clustering dimensions. The first ncdim dimensions will be sampled using the sampling method, the remaining dimensions will just sample uniformly from the prior distribution. If this is None (default), this will default to npdim.

Returns:
sampler : sampler from nestedsamplers

An initialized instance of the chosen sampler specified via bound.

dynesty.dynesty.DynamicNestedSampler(loglikelihood, prior_transform, ndim, bound='multi', sample='auto', periodic=None, reflective=None, update_interval=None, first_update=None, npdim=None, rstate=None, queue_size=None, pool=None, use_pool=None, logl_args=None, logl_kwargs=None, ptform_args=None, ptform_kwargs=None, gradient=None, grad_args=None, grad_kwargs=None, compute_jac=False, enlarge=None, bootstrap=0, vol_dec=0.5, vol_check=2.0, walks=25, facc=0.5, slices=5, fmove=0.9, max_move=100, update_func=None, ncdim=None, save_history=False, history_filename=None, **kwargs)

Initializes and returns a sampler object for Dynamic Nested Sampling.

Parameters:
loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

prior_transform : function

Function translating a unit cube to the parameter space according to the prior. The input is a 1-d numpy array with length ndim, where each value is in the range [0, 1). The return value should also be a 1-d numpy array with length ndim, where each value is a parameter. The return value is passed to the loglikelihood function. For example, for a 2 parameter model with flat priors in the range [0, 2), the function would be:

def prior_transform(u):
    return 2.0 * u
ndim : int

Number of parameters returned by prior_transform and accepted by loglikelihood.

bound : {'none', 'single', 'multi', 'balls', 'cubes'}, optional

Method used to approximately bound the prior using the current set of live points. Conditions the sampling methods used to propose new live points. Choices are no bound ('none'), a single bounding ellipsoid ('single'), multiple bounding ellipsoids ('multi'), balls centered on each live point ('balls'), and cubes centered on each live point ('cubes'). Default is 'multi'.

sample : {'auto', 'unif', 'rwalk', 'rstagger',

'slice', 'rslice', 'hslice'}, optional

Method used to sample uniformly within the likelihood constraint, conditioned on the provided bounds. Unique methods available are: uniform sampling within the bounds('unif'), random walks with fixed proposals ('rwalk'), random walks with variable (“staggering”) proposals ('rstagger'), multivariate slice sampling along preferred orientations ('slice'), “random” slice sampling along all orientations ('rslice'), “Hamiltonian” slices along random trajectories ('hslice'), and any callable function which follows the pattern of the sample methods defined in dynesty.sampling. 'auto' selects the sampling method based on the dimensionality of the problem (from ndim). When ndim < 10, this defaults to 'unif'. When 10 <= ndim <= 20, this defaults to 'rwalk'. When ndim > 20, this defaults to 'hslice' if a gradient is provided and 'slice' otherwise. 'rstagger' and 'rslice' are provided as alternatives for 'rwalk' and 'slice', respectively. Default is 'auto'.

periodic : iterable, optional

A list of indices for parameters with periodic boundary conditions. These parameters will not have their positions constrained to be within the unit cube, enabling smooth behavior for parameters that may wrap around the edge. Default is None (i.e. no periodic boundary conditions).

reflective : iterable, optional

A list of indices for parameters with reflective boundary conditions. These parameters will not have their positions constrained to be within the unit cube, enabling smooth behavior for parameters that may reflect at the edge. Default is None (i.e. no reflective boundary conditions).

update_interval : int or float, optional

If an integer is passed, only update the proposal distribution every update_interval-th likelihood call. If a float is passed, update the proposal after every round(update_interval * nlive)-th likelihood call. Larger update intervals larger can be more efficient when the likelihood function is quick to evaluate. Default behavior is to target a roughly constant change in prior volume, with 1.5 for 'unif', 0.15 * walks for 'rwalk' and 'rstagger', 0.9 * ndim * slices for 'slice', 2.0 * slices for 'rslice', and 25.0 * slices for 'hslice'.

first_update : dict, optional

A dictionary containing parameters governing when the sampler should first update the bounding distribution from the unit cube ('none') to the one specified by sample. Options are the minimum number of likelihood calls ('min_ncall') and the minimum allowed overall efficiency in percent ('min_eff'). Defaults are 2 * nlive and 10., respectively.

npdim : int, optional

Number of parameters accepted by prior_transform. This might differ from ndim in the case where a parameter of loglikelihood is dependent upon multiple independently distributed parameters, some of which may be nuisance parameters.

rstate : RandomState, optional
RandomState instance. If not given, the

global random state of the random module will be used.

queue_size : int, optional

Carry out likelihood evaluations in parallel by queueing up new live point proposals using (at most) queue_size many threads. Each thread independently proposes new live points until the proposal distribution is updated. If no value is passed, this defaults to pool.size (if a pool has been provided) and 1 otherwise (no parallelism).

pool : user-provided pool, optional

Use this pool of workers to execute operations in parallel.

use_pool : dict, optional

A dictionary containing flags indicating where a pool should be used to execute operations in parallel. These govern whether prior_transform is executed in parallel during initialization ('prior_transform'), loglikelihood is executed in parallel during initialization ('loglikelihood'), live points are proposed in parallel during a run ('propose_point'), bounding distributions are updated in parallel during a run ('update_bound'), and the stopping criteria is evaluated in parallel during a run ('stop_function'). Default is True for all options.

logl_args : iterable, optional

Additional arguments that can be passed to loglikelihood.

logl_kwargs : dict, optional

Additional keyword arguments that can be passed to loglikelihood.

ptform_args : iterable, optional

Additional arguments that can be passed to prior_transform.

ptform_kwargs : dict, optional

Additional keyword arguments that can be passed to prior_transform.

gradient : function, optional

A function which returns the gradient corresponding to the provided loglikelihood with respect to the unit cube. If provided, this will be used when computing reflections when sampling with 'hslice'. If not provided, gradients are approximated numerically using 2-sided differencing.

grad_args : iterable, optional

Additional arguments that can be passed to gradient.

grad_kwargs : dict, optional

Additional keyword arguments that can be passed to gradient.

compute_jac : bool, optional

Whether to compute and apply the Jacobian dv/du from the target space v to the unit cube u when evaluating the gradient. If False, the gradient provided is assumed to be already defined with respect to the unit cube. If True, the gradient provided is assumed to be defined with respect to the target space so the Jacobian needs to be numerically computed and applied. Default is False.

enlarge : float, optional

Enlarge the volumes of the specified bounding object(s) by this fraction. The preferred method is to determine this organically using bootstrapping. If bootstrap > 0, this defaults to 1.0. If bootstrap = 0, this instead defaults to 1.25.

bootstrap : int, optional

Compute this many bootstrapped realizations of the bounding objects. Use the maximum distance found to the set of points left out during each iteration to enlarge the resulting volumes. Can lead to unstable bounding ellipsoids. Default is 0 (no bootstrap).

vol_dec : float, optional

For the 'multi' bounding option, the required fractional reduction in volume after splitting an ellipsoid in order to to accept the split. Default is 0.5.

vol_check : float, optional

For the 'multi' bounding option, the factor used when checking if the volume of the original bounding ellipsoid is large enough to warrant > 2 splits via ell.vol > vol_check * nlive * pointvol. Default is 2.0.

walks : int, optional

For the 'rwalk' sampling option, the minimum number of steps (minimum 2) before proposing a new live point. Default is 25.

facc : float, optional

The target acceptance fraction for the 'rwalk' sampling option. Default is 0.5. Bounded to be between [1. / walks, 1.].

slices : int, optional

For the 'slice', 'rslice', and 'hslice' sampling options, the number of times to execute a “slice update” before proposing a new live point. Default is 5. Note that 'slice' cycles through all dimensions when executing a “slice update”.

fmove : float, optional

The target fraction of samples that are proposed along a trajectory (i.e. not reflecting) for the 'hslice' sampling option. Default is 0.9.

max_move : int, optional

The maximum number of timesteps allowed for 'hslice' per proposal forwards and backwards in time. Default is 100.

update_func : function, optional

Any callable function which takes in a blob and scale as input and returns a modification to the internal scale as output. Must follow the pattern of the update methods defined in dynesty.nestedsamplers. If provided, this will supersede the default functions used to update proposals. In the case where a custom callable function is passed to sample but no similar function is passed to update_func, this will default to no update.

ncdim: int, optional

The number of clustering dimensions. The first ncdim dimensions will be sampled using the sampling method, the remaining dimensions will just sample uniformly from the prior distribution. If this is None (default), this will default to npdim.

Returns:
sampler : a dynesty.DynamicSampler instance

An initialized instance of the dynamic nested sampler.

class dynesty.dynesty._function_wrapper(func, args, kwargs, name='input')

Bases: object

A hack to make functions pickleable when args or kwargs are also included. Based on the implementation in emcee.

Bounding

Bounding classes used when proposing new live points, along with a number of useful helper functions. Bounding objects include:

UnitCube:
The unit N-cube (unconstrained draws from the prior).
Ellipsoid:
Bounding ellipsoid.
MultiEllipsoid:
A set of (possibly overlapping) bounding ellipsoids.
RadFriends:
A set of (possibly overlapping) balls centered on each live point.
SupFriends:
A set of (possibly overlapping) cubes centered on each live point.
class dynesty.bounding.UnitCube(ndim)

Bases: object

An N-dimensional unit cube.

Parameters:
ndim : int

The number of dimensions of the unit cube.

contains(self, x)

Checks if unit cube contains the point x.

randoffset(self, rstate=None)

Draw a random offset from the center of the unit cube.

sample(self, rstate=None)

Draw a sample uniformly distributed within the unit cube.

Returns:
x : ndarray with shape (ndim,)

A coordinate within the unit cube.

samples(self, nsamples, rstate=None)

Draw nsamples samples randomly distributed within the unit cube.

Returns:
x : ndarray with shape (nsamples, ndim)

A collection of coordinates within the unit cube.

update(self, points, pointvol=0.0, rstate=None, bootstrap=0, pool=None)

Filler function.

class dynesty.bounding.Ellipsoid(ctr, cov, am=None, axes=None)

Bases: object

An N-dimensional ellipsoid defined by:

(x - v)^T A (x - v) = 1

where the vector v is the center of the ellipsoid and A is a symmetric, positive-definite N x N matrix.

Parameters:
ctr : ndarray with shape (N,)

Coordinates of ellipsoid center.

cov : ndarray with shape (N, N)

Covariance matrix describing the axes.

contains(self, x)

Checks if ellipsoid contains x.

distance(self, x)

Compute the normalized distance to x from the center of the ellipsoid.

distance_many(self, x)

Compute the normalized distance to x from the center of the ellipsoid.

major_axis_endpoints(self)

Return the endpoints of the major axis.

randoffset(self, rstate=None)

Return a random offset from the center of the ellipsoid.

sample(self, rstate=None)

Draw a sample uniformly distributed within the ellipsoid.

Returns:
x : ndarray with shape (ndim,)

A coordinate within the ellipsoid.

samples(self, nsamples, rstate=None)

Draw nsamples samples uniformly distributed within the ellipsoid.

Returns:
x : ndarray with shape (nsamples, ndim)

A collection of coordinates within the ellipsoid.

scale_to_logvol(self, logvol)

Scale ellipoid to a target volume.

unitcube_overlap(self, ndraws=10000, rstate=None)

Using ndraws Monte Carlo draws, estimate the fraction of overlap between the ellipsoid and the unit cube.

update(self, points, pointvol=0.0, rstate=None, bootstrap=0, pool=None, mc_integrate=False)

Update the ellipsoid to bound the collection of points.

Parameters:
points : ndarray with shape (npoints, ndim)

The set of points to bound.

pointvol : float, optional

The minimum volume associated with each point. Default is 0..

rstate : RandomState, optional

RandomState instance.

bootstrap : int, optional

The number of bootstrapped realizations of the ellipsoid. The maximum distance to the set of points “left out” during each iteration is used to enlarge the resulting volumes. Default is 0.

pool : user-provided pool, optional

Use this pool of workers to execute operations in parallel.

mc_integrate : bool, optional

Whether to use Monte Carlo methods to compute the effective overlap of the final ellipsoid with the unit cube. Default is False.

class dynesty.bounding.MultiEllipsoid(ells=None, ctrs=None, covs=None)

Bases: object

A collection of M N-dimensional ellipsoids.

Parameters:
ells : list of Ellipsoid objects with length M, optional

A set of Ellipsoid objects that make up the collection of N-ellipsoids. Used to initialize MultiEllipsoid if provided.

ctrs : ndarray with shape (M, N), optional

Collection of coordinates of ellipsoid centers. Used to initialize MultiEllipsoid if ams is also provided.

covs : ndarray with shape (M, N, N), optional

Collection of matrices describing the axes of the ellipsoids. Used to initialize MultiEllipsoid if ctrs also provided.

_MultiEllipsoid__update_arrays(self)

Update internal arrays to ensure that in sync with ells

contains(self, x)

Checks if the set of ellipsoids contains x.

major_axis_endpoints(self)

Return the endpoints of the major axis of each ellipsoid.

monte_carlo_logvol(self, ndraws=10000, rstate=None, return_overlap=True)

Using ndraws Monte Carlo draws, estimate the log volume of the union of ellipsoids. If return_overlap=True, also returns the estimated fractional overlap with the unit cube.

overlap(self, x, j=None)

Checks how many ellipsoid(s) x falls within, skipping the j-th ellipsoid.

sample(self, rstate=None, return_q=False)

Sample a point uniformly distributed within the union of ellipsoids.

Returns:
x : ndarray with shape (ndim,)

A coordinate within the set of ellipsoids.

idx : int

The index of the ellipsoid x was sampled from.

q : int, optional

The number of ellipsoids x falls within.

samples(self, nsamples, rstate=None)

Draw nsamples samples uniformly distributed within the union of ellipsoids.

Returns:
xs : ndarray with shape (nsamples, ndim)

A collection of coordinates within the set of ellipsoids.

scale_to_logvol(self, logvols)

Scale ellipoids to a corresponding set of target volumes.

update(self, points, pointvol=0.0, vol_dec=0.5, vol_check=2.0, rstate=None, bootstrap=0, pool=None, mc_integrate=False)

Update the set of ellipsoids to bound the collection of points.

Parameters:
points : ndarray with shape (npoints, ndim)

The set of points to bound.

pointvol : float, optional

The minimum volume associated with each point. Default is 0..

vol_dec : float, optional

The required fractional reduction in volume after splitting an ellipsoid in order to to accept the split. Default is 0.5.

vol_check : float, optional

The factor used when checking if the volume of the original bounding ellipsoid is large enough to warrant > 2 splits via ell.vol > vol_check * nlive * pointvol. Default is 2.0.

rstate : RandomState, optional

RandomState instance.

bootstrap : int, optional

The number of bootstrapped realizations of the ellipsoids. The maximum distance to the set of points “left out” during each iteration is used to enlarge the resulting volumes. Default is 0.

pool : user-provided pool, optional

Use this pool of workers to execute operations in parallel.

mc_integrate : bool, optional

Whether to use Monte Carlo methods to compute the effective volume and fractional overlap of the final union of ellipsoids with the unit cube. Default is False.

within(self, x, j=None)

Checks which ellipsoid(s) x falls within, skipping the j-th ellipsoid.

class dynesty.bounding.RadFriends(ndim, cov=None)

Bases: object

A collection of N-balls of identical size centered on each live point.

Parameters:
ndim : int

The number of dimensions of each ball.

cov : ndarray with shape (ndim, ndim), optional

Covariance structure (correlation and size) of each ball.

_get_covariance_from_all_points(self, points)

Compute covariance using all points.

_get_covariance_from_clusters(self, points)

Compute covariance from re-centered clusters.

contains(self, x, ctrs)

Check if the set of balls contains x.

monte_carlo_logvol(self, ctrs, ndraws=10000, rstate=None, return_overlap=True)

Using ndraws Monte Carlo draws, estimate the log volume of the union of balls. If return_overlap=True, also returns the estimated fractional overlap with the unit cube.

overlap(self, x, ctrs)

Check how many balls x falls within.

sample(self, ctrs, rstate=None, return_q=False)

Sample a point uniformly distributed within the union of balls.

Returns:
x : ndarray with shape (ndim,)

A coordinate within the set of balls.

q : int, optional

The number of balls x falls within.

samples(self, nsamples, ctrs, rstate=None)

Draw nsamples samples uniformly distributed within the union of balls.

Returns:
xs : ndarray with shape (nsamples, ndim)

A collection of coordinates within the set of balls.

scale_to_logvol(self, logvol)

Scale ball to encompass a target volume.

update(self, points, pointvol=0.0, rstate=None, bootstrap=0, pool=None, mc_integrate=False, use_clustering=True)

Update the radii of our balls.

Parameters:
points : ndarray with shape (npoints, ndim)

The set of points to bound.

pointvol : float, optional

The minimum volume associated with each point. Default is 0..

rstate : RandomState, optional

RandomState instance.

bootstrap : int, optional

The number of bootstrapped realizations of the ellipsoids. The maximum distance to the set of points “left out” during each iteration is used to enlarge the resulting volumes. Default is 0.

pool : user-provided pool, optional

Use this pool of workers to execute operations in parallel.

mc_integrate : bool, optional

Whether to use Monte Carlo methods to compute the effective volume and fractional overlap of the final union of balls with the unit cube. Default is False.

use_clustering : bool, optional

Whether to use clustering to avoid issues with widely-seperated modes. Default is True.

within(self, x, ctrs)

Check which balls x falls within.

class dynesty.bounding.SupFriends(ndim, cov=None)

Bases: object

A collection of N-cubes of identical size centered on each live point.

Parameters:
ndim : int

The number of dimensions of the cube.

cov : ndarray with shape (ndim, ndim), optional

Covariance structure (correlation and size) of each cube.

_get_covariance_from_all_points(self, points)

Compute covariance using all points.

_get_covariance_from_clusters(self, points)

Compute covariance from re-centered clusters.

contains(self, x, ctrs)

Checks if the set of cubes contains x.

monte_carlo_logvol(self, ctrs, ndraws=10000, rstate=None, return_overlap=False)

Using ndraws Monte Carlo draws, estimate the log volume of the union of cubes. If return_overlap=True, also returns the estimated fractional overlap with the unit cube.

overlap(self, x, ctrs)

Checks how many cubes x falls within, skipping the j-th cube.

sample(self, ctrs, rstate=None, return_q=False)

Sample a point uniformly distributed within the union of cubes.

Returns:
x : ndarray with shape (ndim,)

A coordinate within the set of cubes.

q : int, optional

The number of cubes x falls within.

samples(self, nsamples, ctrs, rstate=None)

Draw nsamples samples uniformly distributed within the union of cubes.

Returns:
xs : ndarray with shape (nsamples, ndim)

A collection of coordinates within the set of cubes.

scale_to_logvol(self, logvol)

Scale cube to encompass a target volume.

update(self, points, pointvol=0.0, rstate=None, bootstrap=0, pool=None, mc_integrate=False, use_clustering=True)

Update the half-side-lengths of our cubes.

Parameters:
points : ndarray with shape (npoints, ndim)

The set of points to bound.

pointvol : float, optional

The minimum volume associated with each point. Default is 0..

rstate : RandomState, optional

RandomState instance.

bootstrap : int, optional

The number of bootstrapped realizations of the ellipsoids. The maximum distance to the set of points “left out” during each iteration is used to enlarge the resulting volumes. Default is 0.

pool : user-provided pool, optional

Use this pool of workers to execute operations in parallel.

mc_integrate : bool, optional

Whether to use Monte Carlo methods to compute the effective volume and fractional overlap of the final union of cubes with the unit cube. Default is False.

use_clustering : bool, optional

Whether to use clustering to avoid issues with widely-seperated modes. Default is True.

within(self, x, ctrs)

Checks which cubes x falls within.

dynesty.bounding.logvol_prefactor(n, p=2.0)

Returns the ln(volume constant) for an n-dimensional sphere with an \(L^p\) norm. The constant is defined as:

lnf = n * ln(2.) + n * LogGamma(1./p + 1) - LogGamma(n/p + 1.)

By default the p=2. norm is used (i.e. the standard Euclidean norm).

dynesty.bounding.randsphere(n, rstate=None)

Draw a point uniformly within an n-dimensional unit sphere.

dynesty.bounding.bounding_ellipsoid(points, pointvol=0.0)

Calculate the bounding ellipsoid containing a collection of points.

Parameters:
points : ndarray with shape (npoints, ndim)

A set of coordinates.

pointvol : float, optional

The minimum volume occupied by a single point. When provided, used to set a minimum bound on the ellipsoid volume as npoints * pointvol. Default is 0..

Returns:
ellipsoid : Ellipsoid

The bounding Ellipsoid object.

dynesty.bounding.bounding_ellipsoids(points, pointvol=0.0, vol_dec=0.5, vol_check=2.0)

Calculate a set of ellipsoids that bound the collection of points.

Parameters:
points : ndarray with shape (npoints, ndim)

A set of coordinates.

pointvol : float, optional

Volume represented by a single point. When provided, used to set a minimum bound on the ellipsoid volume as npoints * pointvol. Default is 0..

vol_dec : float, optional

The required fractional reduction in volume after splitting an ellipsoid in order to to accept the split. Default is 0.5.

vol_check : float, optional

The factor used to when checking whether the volume of the original bounding ellipsoid is large enough to warrant more trial splits via ell.vol > vol_check * npoints * pointvol. Default is 2.0.

Returns:
mell : MultiEllipsoid object

The MultiEllipsoid object used to bound the collection of points.

dynesty.bounding._bounding_ellipsoids(points, ell, pointvol=0.0, vol_dec=0.5, vol_check=2.0)

Internal method used to compute a set of bounding ellipsoids when a bounding ellipsoid for the entire set has already been calculated.

Parameters:
points : ndarray with shape (npoints, ndim)

A set of coordinates.

ell : Ellipsoid

The bounding ellipsoid containing points.

pointvol : float, optional

Volume represented by a single point. When provided, used to set a minimum bound on the ellipsoid volume as npoints * pointvol. Default is 0..

vol_dec : float, optional

The required fractional reduction in volume after splitting an ellipsoid in order to to accept the split. Default is 0.5.

vol_check : float, optional

The factor used to when checking whether the volume of the original bounding ellipsoid is large enough to warrant more trial splits via ell.vol > vol_check * npoints * pointvol. Default is 2.0.

Returns:
ells : list of Ellipsoid objects

List of Ellipsoid objects used to bound the collection of points. Used to initialize the MultiEllipsoid object returned in bounding_ellipsoids().

dynesty.bounding._ellipsoid_bootstrap_expand(args)

Internal method used to compute the expansion factor for a bounding ellipsoid based on bootstrapping.

dynesty.bounding._ellipsoids_bootstrap_expand(args)

Internal method used to compute the expansion factor(s) for a collection of bounding ellipsoids using bootstrapping.

dynesty.bounding._friends_bootstrap_radius(args)

Internal method used to compute the radius (half-side-length) for each ball (cube) used in RadFriends (SupFriends) using bootstrapping.

dynesty.bounding._friends_leaveoneout_radius(points, ftype)

Internal method used to compute the radius (half-side-length) for each ball (cube) used in RadFriends (SupFriends) using leave-one-out (LOO) cross-validation.

Sampling

Functions for proposing new live points used by Sampler (and its children from nestedsamplers) and DynamicSampler.

dynesty.sampling.sample_unif(args)

Evaluate a new point sampled uniformly from a bounding proposal distribution. Parameters are zipped within args to utilize pool.map-style functions.

Parameters:
u : ndarray with shape (npdim,)

Position of the initial sample.

loglstar : float

Ln(likelihood) bound. Not applicable here.

axes : ndarray with shape (ndim, ndim)

Axes used to propose new points. Not applicable here.

scale : float

Value used to scale the provided axes. Not applicable here.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

kwargs : dict

A dictionary of additional method-specific parameters. Not applicable here.

Returns:
u : ndarray with shape (npdim,)

Position of the final proposed point within the unit cube. For uniform sampling this is the same as the initial input position.

v : ndarray with shape (ndim,)

Position of the final proposed point in the target parameter space.

logl : float

Ln(likelihood) of the final proposed point.

nc : int

Number of function calls used to generate the sample. For uniform sampling this is 1 by construction.

blob : dict

Collection of ancillary quantities used to tune scale. Not applicable for uniform sampling.

dynesty.sampling.sample_rwalk(args)

Return a new live point proposed by random walking away from an existing live point.

Parameters:
u : ndarray with shape (npdim,)

Position of the initial sample. This is a copy of an existing live point.

loglstar : float

Ln(likelihood) bound.

axes : ndarray with shape (ndim, ndim)

Axes used to propose new points. For random walks new positions are proposed using the Ellipsoid whose shape is defined by axes.

scale : float

Value used to scale the provided axes.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

kwargs : dict

A dictionary of additional method-specific parameters.

Returns:
u : ndarray with shape (npdim,)

Position of the final proposed point within the unit cube.

v : ndarray with shape (ndim,)

Position of the final proposed point in the target parameter space.

logl : float

Ln(likelihood) of the final proposed point.

nc : int

Number of function calls used to generate the sample.

blob : dict

Collection of ancillary quantities used to tune scale.

dynesty.sampling.sample_rstagger(args)

Return a new live point proposed by random “staggering” away from an existing live point. The difference between this and the random walk is the step size is exponentially adjusted to reach a target acceptance rate during each proposal (in addition to between proposals).

Parameters:
u : ndarray with shape (npdim,)

Position of the initial sample. This is a copy of an existing live point.

loglstar : float

Ln(likelihood) bound.

axes : ndarray with shape (ndim, ndim)

Axes used to propose new points. For random walks new positions are proposed using the Ellipsoid whose shape is defined by axes.

scale : float

Value used to scale the provided axes.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

kwargs : dict

A dictionary of additional method-specific parameters.

Returns:
u : ndarray with shape (npdim,)

Position of the final proposed point within the unit cube.

v : ndarray with shape (ndim,)

Position of the final proposed point in the target parameter space.

logl : float

Ln(likelihood) of the final proposed point.

nc : int

Number of function calls used to generate the sample.

blob : dict

Collection of ancillary quantities used to tune scale.

dynesty.sampling.sample_slice(args)

Return a new live point proposed by a series of random slices away from an existing live point. Standard “Gibs-like” implementation where a single multivariate “slice” is a combination of ndim univariate slices through each axis.

Parameters:
u : ndarray with shape (npdim,)

Position of the initial sample. This is a copy of an existing live point.

loglstar : float

Ln(likelihood) bound.

axes : ndarray with shape (ndim, ndim)

Axes used to propose new points. For slices new positions are proposed along the arthogonal basis defined by axes.

scale : float

Value used to scale the provided axes.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

kwargs : dict

A dictionary of additional method-specific parameters.

Returns:
u : ndarray with shape (npdim,)

Position of the final proposed point within the unit cube.

v : ndarray with shape (ndim,)

Position of the final proposed point in the target parameter space.

logl : float

Ln(likelihood) of the final proposed point.

nc : int

Number of function calls used to generate the sample.

blob : dict

Collection of ancillary quantities used to tune scale.

dynesty.sampling.sample_rslice(args)

Return a new live point proposed by a series of random slices away from an existing live point. Standard “random” implementation where each slice is along a random direction based on the provided axes.

Parameters:
u : ndarray with shape (npdim,)

Position of the initial sample. This is a copy of an existing live point.

loglstar : float

Ln(likelihood) bound.

axes : ndarray with shape (ndim, ndim)

Axes used to propose new slice directions.

scale : float

Value used to scale the provided axes.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

kwargs : dict

A dictionary of additional method-specific parameters.

Returns:
u : ndarray with shape (npdim,)

Position of the final proposed point within the unit cube.

v : ndarray with shape (ndim,)

Position of the final proposed point in the target parameter space.

logl : float

Ln(likelihood) of the final proposed point.

nc : int

Number of function calls used to generate the sample.

blob : dict

Collection of ancillary quantities used to tune scale.

dynesty.sampling.sample_hslice(args)

Return a new live point proposed by “Hamiltonian” Slice Sampling using a series of random trajectories away from an existing live point. Each trajectory is based on the provided axes and samples are determined by moving forwards/backwards in time until the trajectory hits an edge and approximately reflecting off the boundaries. Once a series of reflections has been established, we propose a new live point by slice sampling across the entire path.

Parameters:
u : ndarray with shape (npdim,)

Position of the initial sample. This is a copy of an existing live point.

loglstar : float

Ln(likelihood) bound.

axes : ndarray with shape (ndim, ndim)

Axes used to propose new slice directions.

scale : float

Value used to scale the provided axes.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

kwargs : dict

A dictionary of additional method-specific parameters.

Returns:
u : ndarray with shape (npdim,)

Position of the final proposed point within the unit cube.

v : ndarray with shape (ndim,)

Position of the final proposed point in the target parameter space.

logl : float

Ln(likelihood) of the final proposed point.

nc : int

Number of function calls used to generate the sample.

blob : dict

Collection of ancillary quantities used to tune scale.

Baseline Sampler

The base Sampler class containing various helpful functions. All other samplers inherit this class either explicitly or implicitly.

class dynesty.sampler.Sampler(loglikelihood, prior_transform, npdim, live_points, update_interval, first_update, rstate, queue_size, pool, use_pool, ncdim)

Bases: object

The basic sampler object that performs the actual nested sampling.

Parameters:
loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

npdim : int, optional

Number of parameters accepted by prior_transform.

live_points : list of 3 ndarray each with shape (nlive, ndim)

Initial set of “live” points. Contains live_u, the coordinates on the unit cube, live_v, the transformed variables, and live_logl, the associated loglikelihoods.

update_interval : int

Only update the bounding distribution every update_interval-th likelihood call.

first_update : dict

A dictionary containing parameters governing when the sampler should first update the bounding distribution from the unit cube to the one specified by the user.

rstate : RandomState

RandomState instance.

queue_size: int

Carry out likelihood evaluations in parallel by queueing up new live point proposals using (at most) this many threads/members.

pool: pool

Use this pool of workers to execute operations in parallel.

use_pool : dict, optional

A dictionary containing flags indicating where the provided pool should be used to execute operations in parallel.

_beyond_unit_bound(self, loglstar)

Check whether we should update our bound beyond the initial unit cube.

_empty_queue(self)

Dump all live point proposals currently on the queue.

_fill_queue(self, loglstar)

Sequentially add new live point proposals to the queue.

_get_point_value(self, loglstar)

Grab the first live point proposal in the queue.

_get_print_func(self, print_func, print_progress)
_new_point(self, loglstar, logvol)

Propose points until a new point that satisfies the log-likelihood constraint loglstar is found.

_remove_live_points(self)

Remove the final set of live points if they were previously added to the current set of dead points.

add_final_live(self, print_progress=True, print_func=None)

A wrapper that executes the loop adding the final live points. Adds the final set of live points to the pre-existing sequence of dead points from the current nested sampling run.

Parameters:
print_progress : bool, optional

Whether or not to output a simple summary of the current run that updates with each iteration. Default is True.

print_func : function, optional

A function that prints out the current state of the sampler. If not provided, the default results.print_fn() is used.

add_live_points(self)

Add the remaining set of live points to the current set of dead points. Instantiates a generator that will be called by the user. Returns the same outputs as sample().

citations

Return list of papers that should be cited given the specified configuration of the sampler.

evolve_point(self, *args)
n_effective

Estimate the effective number of posterior samples using the Kish Effective Sample Size (ESS) where ESS = sum(wts)^2 / sum(wts^2). Note that this is len(wts) when wts are uniform and 1 if there is only one non-zero element in wts.

propose_point(self, *args)
reset(self)

Re-initialize the sampler.

results

Saved results from the nested sampling run. If bounding distributions were saved, those are also returned.

run_nested(self, maxiter=None, maxcall=None, dlogz=None, logl_max=inf, n_effective=None, add_live=True, print_progress=True, print_func=None, save_bounds=True)

A wrapper that executes the main nested sampling loop. Iteratively replace the worst live point with a sample drawn uniformly from the prior until the provided stopping criteria are reached.

Parameters:
maxiter : int, optional

Maximum number of iterations. Iteration may stop earlier if the termination condition is reached. Default is sys.maxsize (no limit).

maxcall : int, optional

Maximum number of likelihood evaluations. Iteration may stop earlier if termination condition is reached. Default is sys.maxsize (no limit).

dlogz : float, optional

Iteration will stop when the estimated contribution of the remaining prior volume to the total evidence falls below this threshold. Explicitly, the stopping criterion is ln(z + z_est) - ln(z) < dlogz, where z is the current evidence from all saved samples and z_est is the estimated contribution from the remaining volume. If add_live is True, the default is 1e-3 * (nlive - 1) + 0.01. Otherwise, the default is 0.01.

logl_max : float, optional

Iteration will stop when the sampled ln(likelihood) exceeds the threshold set by logl_max. Default is no bound (np.inf).

n_effective: int, optional

Minimum number of effective posterior samples. If the estimated “effective sample size” (ESS) exceeds this number, sampling will terminate. Default is no ESS (np.inf).

add_live : bool, optional

Whether or not to add the remaining set of live points to the list of samples at the end of each run. Default is True.

print_progress : bool, optional

Whether or not to output a simple summary of the current run that updates with each iteration. Default is True.

print_func : function, optional

A function that prints out the current state of the sampler. If not provided, the default results.print_fn() is used.

save_bounds : bool, optional

Whether or not to save past bounding distributions used to bound the live points internally. Default is True.

sample(self, maxiter=None, maxcall=None, dlogz=0.01, logl_max=inf, n_effective=inf, add_live=True, save_bounds=True, save_samples=True)

The main nested sampling loop. Iteratively replace the worst live point with a sample drawn uniformly from the prior until the provided stopping criteria are reached. Instantiates a generator that will be called by the user.

Parameters:
maxiter : int, optional

Maximum number of iterations. Iteration may stop earlier if the termination condition is reached. Default is sys.maxsize (no limit).

maxcall : int, optional

Maximum number of likelihood evaluations. Iteration may stop earlier if termination condition is reached. Default is sys.maxsize (no limit).

dlogz : float, optional

Iteration will stop when the estimated contribution of the remaining prior volume to the total evidence falls below this threshold. Explicitly, the stopping criterion is ln(z + z_est) - ln(z) < dlogz, where z is the current evidence from all saved samples and z_est is the estimated contribution from the remaining volume. Default is 0.01.

logl_max : float, optional

Iteration will stop when the sampled ln(likelihood) exceeds the threshold set by logl_max. Default is no bound (np.inf).

n_effective: int, optional

Minimum number of effective posterior samples. If the estimated “effective sample size” (ESS) exceeds this number, sampling will terminate. Default is no ESS (np.inf).

add_live : bool, optional

Whether or not to add the remaining set of live points to the list of samples when calculating n_effective. Default is True.

save_bounds : bool, optional

Whether or not to save past distributions used to bound the live points internally. Default is True.

save_samples : bool, optional

Whether or not to save past samples from the nested sampling run (along with other ancillary quantities) internally. Default is True.

Returns:
worst : int

Index of the live point with the worst likelihood. This is our new dead point sample.

ustar : ndarray with shape (npdim,)

Position of the sample.

vstar : ndarray with shape (ndim,)

Transformed position of the sample.

loglstar : float

Ln(likelihood) of the sample.

logvol : float

Ln(prior volume) within the sample.

logwt : float

Ln(weight) of the sample.

logz : float

Cumulative ln(evidence) up to the sample (inclusive).

logzvar : float

Estimated cumulative variance on logz (inclusive).

h : float

Cumulative information up to the sample (inclusive).

nc : int

Number of likelihood calls performed before the new live point was accepted.

worst_it : int

Iteration when the live (now dead) point was originally proposed.

boundidx : int

Index of the bound the dead point was originally drawn from.

bounditer : int

Index of the bound being used at the current iteration.

eff : float

The cumulative sampling efficiency (in percent).

delta_logz : float

The estimated remaining evidence expressed as the ln(ratio) of the current evidence.

update(self, *args)
update_proposal(self, *args)

Static Nested Samplers

Childen of dynesty.sampler used to proposing new live points. Includes:

UnitCubeSampler:
Uses the unit cube to bound the set of live points (i.e. no bound).
SingleEllipsoidSampler:
Uses a single ellipsoid to bound the set of live points.
MultiEllipsoidSampler:
Uses multiple ellipsoids to bound the set of live points.
RadFriendsSampler:
Uses an N-sphere of fixed radius centered on each live point to bound the set of live points.
SupFriendsSampler:
Uses an N-cube of fixed length centered on each live point to bound the set of live points.
class dynesty.nestedsamplers.UnitCubeSampler(loglikelihood, prior_transform, npdim, live_points, method, update_interval, first_update, rstate, queue_size, pool, use_pool, kwargs={}, ncdim=0)

Bases: dynesty.sampler.Sampler

Samples conditioned on the unit N-cube (i.e. with no bounds).

Parameters:
loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

npdim : int

Number of parameters accepted by prior_transform.

live_points : list of 3 ndarray each with shape (nlive, ndim)

Initial set of “live” points. Contains live_u, the coordinates on the unit cube, live_v, the transformed variables, and live_logl, the associated loglikelihoods.

method : {'unif', 'rwalk', 'rstagger',

'slice', 'rslice', 'hslice'}, optional

Method used to sample uniformly within the likelihood constraint, conditioned on the provided bounds.

update_interval : int

Only update the bounding distribution every update_interval-th likelihood call.

first_update : dict

A dictionary containing parameters governing when the sampler should first update the bounding distribution from the unit cube to the one specified by the user.

rstate : RandomState

RandomState instance.

queue_size: int

Carry out likelihood evaluations in parallel by queueing up new live point proposals using (at most) this many threads/members.

pool: pool

Use this pool of workers to execute operations in parallel.

use_pool : dict, optional

A dictionary containing flags indicating where the provided pool should be used to execute operations in parallel.

kwargs : dict, optional

A dictionary of additional parameters.

propose_live(self, *args)

Return a live point/axes to be used by other sampling methods. If args is not empty, it contains the subset of indices of points to sample from.

propose_unif(self, *args)

Propose a new live point by sampling uniformly within the unit cube.

update(self, pointvol)

Update the unit cube bound.

update_hslice(self, blob)

Update the Hamiltonian slice proposal scale based on the relative amount of time spent moving vs reflecting.

update_rwalk(self, blob)

Update the random walk proposal scale based on the current number of accepted/rejected steps.

update_slice(self, blob)

Update the slice proposal scale based on the relative size of the slices compared to our initial guess.

update_unif(self, blob)

Filler function.

update_user(self, blob)

Update the scale based on the user-defined update function.

class dynesty.nestedsamplers.SingleEllipsoidSampler(loglikelihood, prior_transform, npdim, live_points, method, update_interval, first_update, rstate, queue_size, pool, use_pool, kwargs={}, ncdim=0)

Bases: dynesty.sampler.Sampler

Samples conditioned on a single ellipsoid used to bound the set of live points.

Parameters:
loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

npdim : int

Number of parameters accepted by prior_transform.

live_points : list of 3 ndarray each with shape (nlive, ndim)

Initial set of “live” points. Contains live_u, the coordinates on the unit cube, live_v, the transformed variables, and live_logl, the associated loglikelihoods.

method : {'unif', 'rwalk', 'rstagger',

'slice', 'rslice', 'hslice'}, optional

Method used to sample uniformly within the likelihood constraint, conditioned on the provided bounds.

update_interval : int

Only update the bounding distribution every update_interval-th likelihood call.

first_update : dict

A dictionary containing parameters governing when the sampler should first update the bounding distribution from the unit cube to the one specified by the user.

rstate : RandomState

RandomState instance.

queue_size: int

Carry out likelihood evaluations in parallel by queueing up new live point proposals using (at most) this many threads/members.

pool: pool

Use this pool of workers to execute operations in parallel.

use_pool : dict, optional

A dictionary containing flags indicating where the provided pool should be used to execute operations in parallel.

kwargs : dict, optional

A dictionary of additional parameters.

propose_live(self, *args)

Return a live point/axes to be used by other sampling methods. If args is not empty, it contains the subset of indices of points to sample from.

propose_unif(self, *args)

Propose a new live point by sampling uniformly within the ellipsoid.

update(self, pointvol)

Update the bounding ellipsoid using the current set of live points.

update_hslice(self, blob)

Update the Hamiltonian slice proposal scale based on the relative amount of time spent moving vs reflecting.

update_rwalk(self, blob)

Update the random walk proposal scale based on the current number of accepted/rejected steps.

update_slice(self, blob)

Update the slice proposal scale based on the relative size of the slices compared to our initial guess.

update_unif(self, blob)

Filler function.

update_user(self, blob)

Update the scale based on the user-defined update function.

class dynesty.nestedsamplers.MultiEllipsoidSampler(loglikelihood, prior_transform, npdim, live_points, method, update_interval, first_update, rstate, queue_size, pool, use_pool, kwargs={}, ncdim=0)

Bases: dynesty.sampler.Sampler

Samples conditioned on the union of multiple (possibly overlapping) ellipsoids used to bound the set of live points.

Parameters:
loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

npdim : int

Number of parameters accepted by prior_transform.

live_points : list of 3 ndarray each with shape (nlive, ndim)

Initial set of “live” points. Contains live_u, the coordinates on the unit cube, live_v, the transformed variables, and live_logl, the associated loglikelihoods.

method : {'unif', 'rwalk', 'rstagger',

'slice', 'rslice', 'hslice'}, optional

Method used to sample uniformly within the likelihood constraint, conditioned on the provided bounds.

update_interval : int

Only update the bounding distribution every update_interval-th likelihood call.

first_update : dict

A dictionary containing parameters governing when the sampler should first update the bounding distribution from the unit cube to the one specified by the user.

rstate : RandomState

RandomState instance.

queue_size: int

Carry out likelihood evaluations in parallel by queueing up new live point proposals using (at most) this many threads/members.

pool: pool

Use this pool of workers to execute operations in parallel.

use_pool : dict, optional

A dictionary containing flags indicating where the provided pool should be used to execute operations in parallel.

kwargs : dict, optional

A dictionary of additional parameters.

propose_live(self, *args)

Return a live point/axes to be used by other sampling methods. If args is not empty, it contains the subset of indices of points to sample from.

propose_unif(self, *args)

Propose a new live point by sampling uniformly within the union of ellipsoids.

update(self, pointvol)

Update the bounding ellipsoids using the current set of live points.

update_hslice(self, blob)

Update the Hamiltonian slice proposal scale based on the relative amount of time spent moving vs reflecting.

update_rwalk(self, blob)

Update the random walk proposal scale based on the current number of accepted/rejected steps.

update_slice(self, blob)

Update the slice proposal scale based on the relative size of the slices compared to our initial guess.

update_unif(self, blob)

Filler function.

update_user(self, blob)

Update the scale based on the user-defined update function.

class dynesty.nestedsamplers.RadFriendsSampler(loglikelihood, prior_transform, npdim, live_points, method, update_interval, first_update, rstate, queue_size, pool, use_pool, kwargs={}, ncdim=0)

Bases: dynesty.sampler.Sampler

Samples conditioned on the union of (possibly overlapping) N-spheres centered on the current set of live points.

Parameters:
loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

npdim : int

Number of parameters accepted by prior_transform.

live_points : list of 3 ndarray each with shape (nlive, ndim)

Initial set of “live” points. Contains live_u, the coordinates on the unit cube, live_v, the transformed variables, and live_logl, the associated loglikelihoods.

method : {'unif', 'rwalk', 'rstagger',

'slice', 'rslice', 'hslice'}, optional

Method used to sample uniformly within the likelihood constraint, conditioned on the provided bounds.

update_interval : int

Only update the bounding distribution every update_interval-th likelihood call.

first_update : dict

A dictionary containing parameters governing when the sampler should first update the bounding distribution from the unit cube to the one specified by the user.

rstate : RandomState

RandomState instance.

queue_size: int

Carry out likelihood evaluations in parallel by queueing up new live point proposals using (at most) this many threads/members.

pool: pool

Use this pool of workers to execute operations in parallel.

use_pool : dict, optional

A dictionary containing flags indicating where the provided pool should be used to execute operations in parallel.

kwargs : dict, optional

A dictionary of additional parameters.

propose_live(self, *args)

Propose a live point/axes to be used by other sampling methods. If args is not empty, it contains the subset of indices of points to sample from.

propose_unif(self, *args)

Propose a new live point by sampling uniformly within the union of N-spheres defined by our live points.

update(self, pointvol)

Update the N-sphere radii using the current set of live points.

update_hslice(self, blob)

Update the Hamiltonian slice proposal scale based on the relative amount of time spent moving vs reflecting.

update_rwalk(self, blob)

Update the random walk proposal scale based on the current number of accepted/rejected steps.

update_slice(self, blob)

Update the slice proposal scale based on the relative size of the slices compared to our initial guess.

update_unif(self, blob)

Filler function.

update_user(self, blob)

Update the scale based on the user-defined update function.

class dynesty.nestedsamplers.SupFriendsSampler(loglikelihood, prior_transform, npdim, live_points, method, update_interval, first_update, rstate, queue_size, pool, use_pool, kwargs={}, ncdim=0)

Bases: dynesty.sampler.Sampler

Samples conditioned on the union of (possibly overlapping) N-cubes centered on the current set of live points.

Parameters:
loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

npdim : int

Number of parameters accepted by prior_transform.

live_points : list of 3 ndarray each with shape (nlive, ndim)

Initial set of “live” points. Contains live_u, the coordinates on the unit cube, live_v, the transformed variables, and live_logl, the associated loglikelihoods.

method : {'unif', 'rwalk', 'rstagger',

'slice', 'rslice', 'hslice'}, optional

Method used to sample uniformly within the likelihood constraint, conditioned on the provided bounds.

update_interval : int

Only update the bounding distribution every update_interval-th likelihood call.

first_update : dict

A dictionary containing parameters governing when the sampler should first update the bounding distribution from the unit cube to the one specified by the user.

rstate : RandomState

RandomState instance.

queue_size: int

Carry out likelihood evaluations in parallel by queueing up new live point proposals using (at most) this many threads/members.

pool: pool

Use this pool of workers to execute operations in parallel.

use_pool : dict, optional

A dictionary containing flags indicating where the provided pool should be used to execute operations in parallel.

kwargs : dict, optional

A dictionary of additional parameters.

propose_live(self, *args)

Return a live point/axes to be used by other sampling methods. If args is not empty, it contains the subset of indices of points to sample from.

propose_unif(self, *args)

Propose a new live point by sampling uniformly within the collection of N-cubes defined by our live points.

update(self, pointvol)

Update the N-cube side-lengths using the current set of live points.

update_hslice(self, blob)

Update the Hamiltonian slice proposal scale based on the relative amount of time spent moving vs reflecting.

update_rwalk(self, blob)

Update the random walk proposal scale based on the current number of accepted/rejected steps.

update_slice(self, blob)

Update the slice proposal scale based on the relative size of the slices compared to our initial guess.

update_unif(self, blob)

Filler function.

update_user(self, blob)

Update the scale based on the user-defined update function.

Dynamic Nested Sampler

Contains the dynamic nested sampler class DynamicSampler used to dynamically allocate nested samples. Note that DynamicSampler implicitly wraps a sampler from nestedsamplers. Also contains the weight function weight_function() and stopping function stopping_function(). These are used by default within DynamicSampler if corresponding functions are not provided by the user.

class dynesty.dynamicsampler.DynamicSampler(loglikelihood, prior_transform, npdim, bound, method, update_interval, first_update, rstate, queue_size, pool, use_pool, ncdim, kwargs)

Bases: object

A dynamic nested sampler that allocates live points adaptively during a single run according to a specified weight function until a specified stopping criteria is reached.

Parameters:
loglikelihood : function

Function returning ln(likelihood) given parameters as a 1-d numpy array of length ndim.

prior_transform : function

Function transforming a sample from the a unit cube to the parameter space of interest according to the prior.

npdim : int, optional

Number of parameters accepted by prior_transform.

bound : {'none', 'single', 'multi', 'balls', 'cubes'}, optional

Method used to approximately bound the prior using the current set of live points. Conditions the sampling methods used to propose new live points.

method : {'unif', 'rwalk', 'rstagger',

'slice', 'rslice', 'hslice'}, optional

Method used to sample uniformly within the likelihood constraint, conditioned on the provided bounds.

update_interval : int

Only update the bounding distribution every update_interval-th likelihood call.

first_update : dict

A dictionary containing parameters governing when the sampler should first update the bounding distribution from the unit cube to the one specified by the user.

rstate : RandomState

RandomState instance.

queue_size: int

Carry out likelihood evaluations in parallel by queueing up new live point proposals using (at most) this many threads/members.

pool: pool

Use this pool of workers to execute operations in parallel.

use_pool : dict, optional

A dictionary containing flags indicating where the provided pool should be used to execute operations in parallel.

kwargs : dict, optional

A dictionary of additional parameters (described below).

_get_print_func(self, print_func, print_progress)
add_batch(self, nlive=500, wt_function=None, wt_kwargs=None, maxiter=None, maxcall=None, logl_bounds=None, save_bounds=True, print_progress=True, print_func=None, stop_val=None)

Allocate an additional batch of (nested) samples based on the combined set of previous samples using the specified weight function.

Parameters:
nlive : int, optional

The number of live points used when adding additional samples in the batch. Default is 500.

wt_function : func, optional

A cost function that takes a Results instance and returns a log-likelihood range over which a new batch of samples should be generated. The default function simply computes a weighted average of the posterior and evidence information content as:

weight = pfrac * pweight + (1. - pfrac) * zweight
wt_kwargs : dict, optional

Extra arguments to be passed to the weight function.

maxiter : int, optional

Maximum number of iterations allowed. Default is sys.maxsize (no limit).

maxcall : int, optional

Maximum number of likelihood evaluations allowed. Default is sys.maxsize (no limit).

logl_bounds : tuple of size (2,), optional

The ln(likelihood) bounds used to bracket the run. If None, the provided wt_function will be used to determine the bounds (this is the default behavior).

save_bounds : bool, optional

Whether or not to save distributions used to bound the live points internally during dynamic live point allocations. Default is True.

print_progress : bool, optional

Whether to output a simple summary of the current run that updates each iteration. Default is True.

print_func : function, optional

A function that prints out the current state of the sampler. If not provided, the default results.print_fn() is used.

stop_val : float, optional

The value of the stopping criteria to be passed to print_func(). Used internally within run_nested() to keep track of progress.

citations

Return list of papers that should be cited given the specified configuration of the sampler.

combine_runs(self)

Merge the most recent run into the previous (combined) run by “stepping through” both runs simultaneously.

n_effective

Estimate the effective number of posterior samples using the Kish Effective Sample Size (ESS) where ESS = sum(wts)^2 / sum(wts^2). Note that this is len(wts) when wts are uniform and 1 if there is only one non-zero element in wts.

reset(self)

Re-initialize the sampler.

results

Saved results from the dynamic nested sampling run. All saved bounds are also returned.

run_nested(self, nlive_init=500, maxiter_init=None, maxcall_init=None, dlogz_init=0.01, logl_max_init=inf, n_effective_init=inf, nlive_batch=500, wt_function=None, wt_kwargs=None, maxiter_batch=None, maxcall_batch=None, maxiter=None, maxcall=None, maxbatch=None, n_effective=inf, stop_function=None, stop_kwargs=None, use_stop=True, save_bounds=True, print_progress=True, print_func=None, live_points=None)

The main dynamic nested sampling loop. After an initial “baseline” run using a constant number of live points, dynamically allocates additional (nested) samples to optimize a specified weight function until a specified stopping criterion is reached.

Parameters:
nlive_init : int, optional

The number of live points used during the initial (“baseline”) nested sampling run. Default is 500.

maxiter_init : int, optional

Maximum number of iterations for the initial baseline nested sampling run. Iteration may stop earlier if the termination condition is reached. Default is sys.maxsize (no limit).

maxcall_init : int, optional

Maximum number of likelihood evaluations for the initial baseline nested sampling run. Iteration may stop earlier if the termination condition is reached. Default is sys.maxsize (no limit).

dlogz_init : float, optional

The baseline run will stop when the estimated contribution of the remaining prior volume to the total evidence falls below this threshold. Explicitly, the stopping criterion is ln(z + z_est) - ln(z) < dlogz, where z is the current evidence from all saved samples and z_est is the estimated contribution from the remaining volume. The default is 0.01.

logl_max_init : float, optional

The baseline run will stop when the sampled ln(likelihood) exceeds this threshold. Default is no bound (np.inf).

n_effective_init: int, optional

Minimum number of effective posterior samples needed during the baseline run. If the estimated “effective sample size” (ESS) exceeds this number, sampling will terminate. Default is no ESS (np.inf).

nlive_batch : int, optional

The number of live points used when adding additional samples from a nested sampling run within each batch. Default is 500.

wt_function : func, optional

A cost function that takes a Results instance and returns a log-likelihood range over which a new batch of samples should be generated. The default function simply computes a weighted average of the posterior and evidence information content as:

weight = pfrac * pweight + (1. - pfrac) * zweight
wt_kwargs : dict, optional

Extra arguments to be passed to the weight function.

maxiter_batch : int, optional

Maximum number of iterations for the nested sampling run within each batch. Iteration may stop earlier if the termination condition is reached. Default is sys.maxsize (no limit).

maxcall_batch : int, optional

Maximum number of likelihood evaluations for the nested sampling run within each batch. Iteration may stop earlier if the termination condition is reached. Default is sys.maxsize (no limit).

maxiter : int, optional

Maximum number of iterations allowed. Default is sys.maxsize (no limit).

maxcall : int, optional

Maximum number of likelihood evaluations allowed. Default is sys.maxsize (no limit).

maxbatch : int, optional

Maximum number of batches allowed. Default is sys.maxsize (no limit).

n_effective: int, optional

Minimum number of effective posterior samples needed during the entire run. If the estimated “effective sample size” (ESS) exceeds this number, sampling will terminate. Default is no ESS (np.inf).

stop_function : func, optional

A function that takes a Results instance and returns a boolean indicating that we should terminate the run because we’ve collected enough samples.

stop_kwargs : float, optional

Extra arguments to be passed to the stopping function.

use_stop : bool, optional

Whether to evaluate our stopping function after each batch. Disabling this can improve performance if other stopping criteria such as maxcall are already specified. Default is True.

save_bounds : bool, optional

Whether or not to save distributions used to bound the live points internally during dynamic live point allocation. Default is True.

print_progress : bool, optional

Whether to output a simple summary of the current run that updates each iteration. Default is True.

print_func : function, optional

A function that prints out the current state of the sampler. If not provided, the default results.print_fn() is used.

live_points : list of 3 ndarray each with shape (nlive, ndim)

A set of live points used to initialize the nested sampling run. Contains live_u, the coordinates on the unit cube, live_v, the transformed variables, and live_logl, the associated loglikelihoods. By default, if these are not provided the initial set of live points will be drawn from the unit npdim-cube. WARNING: It is crucial that the initial set of live points have been sampled from the prior. Failure to provide a set of valid live points will result in biased results.

sample_batch(self, nlive_new=500, update_interval=None, logl_bounds=None, maxiter=None, maxcall=None, save_bounds=True)

Generate an additional series of nested samples that will be combined with the previous set of dead points. Works by hacking the internal sampler object. Instantiates a generator that will be called by the user.

Parameters:
nlive_new : int

Number of new live points to be added. Default is 500.

update_interval : int or float, optional

If an integer is passed, only update the bounding distribution every update_interval-th likelihood call. If a float is passed, update the bound after every round(update_interval * nlive)-th likelihood call. Larger update intervals can be more efficient when the likelihood function is quick to evaluate. If no value is provided, defaults to the value passed during initialization.

logl_bounds : tuple of size (2,), optional

The ln(likelihood) bounds used to bracket the run. If None, the default bounds span the entire range covered by the original run.

maxiter : int, optional

Maximum number of iterations. Iteration may stop earlier if the termination condition is reached. Default is sys.maxsize (no limit).

maxcall : int, optional

Maximum number of likelihood evaluations. Iteration may stop earlier if termination condition is reached. Default is sys.maxsize (no limit).

save_bounds : bool, optional

Whether or not to save past distributions used to bound the live points internally. Default is True.

Returns:
worst : int

Index of the live point with the worst likelihood. This is our new dead point sample. Negative values indicate the index of a new live point generated when initializing a new batch.

ustar : ndarray with shape (npdim,)

Position of the sample.

vstar : ndarray with shape (ndim,)

Transformed position of the sample.

loglstar : float

Ln(likelihood) of the sample.

nc : int

Number of likelihood calls performed before the new live point was accepted.

worst_it : int

Iteration when the live (now dead) point was originally proposed.

boundidx : int

Index of the bound the dead point was originally drawn from.

bounditer : int

Index of the bound being used at the current iteration.

eff : float

The cumulative sampling efficiency (in percent).

sample_initial(self, nlive=500, update_interval=None, first_update=None, maxiter=None, maxcall=None, logl_max=inf, dlogz=0.01, n_effective=inf, live_points=None, save_samples=False, resume=False)

Generate a series of initial samples from a nested sampling run using a fixed number of live points using an internal sampler from nestedsamplers. Instantiates a generator that will be called by the user.

Parameters:
nlive : int, optional

The number of live points to use for the baseline nested sampling run. Default is 500.

update_interval : int or float, optional

If an integer is passed, only update the bounding distribution every update_interval-th likelihood call. If a float is passed, update the bound after every round(update_interval * nlive)-th likelihood call. Larger update intervals can be more efficient when the likelihood function is quick to evaluate. If no value is provided, defaults to the value passed during initialization.

first_update : dict, optional

A dictionary containing parameters governing when the sampler will first update the bounding distribution from the unit cube ('none') to the one specified by sample.

maxiter : int, optional

Maximum number of iterations. Iteration may stop earlier if the termination condition is reached. Default is sys.maxsize (no limit).

maxcall : int, optional

Maximum number of likelihood evaluations. Iteration may stop earlier if termination condition is reached. Default is sys.maxsize (no limit).

dlogz : float, optional

Iteration will stop when the estimated contribution of the remaining prior volume to the total evidence falls below this threshold. Explicitly, the stopping criterion is ln(z + z_est) - ln(z) < dlogz, where z is the current evidence from all saved samples and z_est is the estimated contribution from the remaining volume. The default is 0.01.

logl_max : float, optional

Iteration will stop when the sampled ln(likelihood) exceeds the threshold set by logl_max. Default is no bound (np.inf).

n_effective: int, optional

Target number of effective posterior samples. If the estimated “effective sample size” (ESS) exceeds this number, sampling will terminate. Default is no ESS (np.inf).

live_points : list of 3 ndarray each with shape (nlive, ndim)

A set of live points used to initialize the nested sampling run. Contains live_u, the coordinates on the unit cube, live_v, the transformed variables, and live_logl, the associated loglikelihoods. By default, if these are not provided the initial set of live points will be drawn from the unit npdim-cube. WARNING: It is crucial that the initial set of live points have been sampled from the prior. Failure to provide a set of valid live points will lead to incorrect results.

Returns:
worst : int

Index of the live point with the worst likelihood. This is our new dead point sample.

ustar : ndarray with shape (npdim,)

Position of the sample.

vstar : ndarray with shape (ndim,)

Transformed position of the sample.

loglstar : float

Ln(likelihood) of the sample.

logvol : float

Ln(prior volume) within the sample.

logwt : float

Ln(weight) of the sample.

logz : float

Cumulative ln(evidence) up to the sample (inclusive).

logzvar : float

Estimated cumulative variance on logz (inclusive).

h : float

Cumulative information up to the sample (inclusive).

nc : int

Number of likelihood calls performed before the new live point was accepted.

worst_it : int

Iteration when the live (now dead) point was originally proposed.

boundidx : int

Index of the bound the dead point was originally drawn from.

bounditer : int

Index of the bound being used at the current iteration.

eff : float

The cumulative sampling efficiency (in percent).

delta_logz : float

The estimated remaining evidence expressed as the ln(ratio) of the current evidence.

dynesty.dynamicsampler.weight_function(results, args=None, return_weights=False)

The default weight function utilized by DynamicSampler. Zipped parameters are passed to the function via args. Assigns each point a weight based on a weighted average of the posterior and evidence information content:

weight = pfrac * pweight + (1. - pfrac) * zweight

where pfrac is the fractional importance placed on the posterior, the evidence weight zweight is based on the estimated remaining posterior mass, and the posterior weight pweight is the sample’s importance weight.

Returns a set of log-likelihood bounds set by the earliest/latest samples where weight > maxfrac * max(weight), with additional left/right padding based on pad.

Parameters:
results : Results instance

Results instance.

args : dictionary of keyword arguments, optional

Arguments used to set the log-likelihood bounds used for sampling, as described above. Default values are pfrac = 0.8, maxfrac = 0.8, and pad = 1.

return_weights : bool, optional

Whether to return the individual weights (and their components) used to compute the log-likelihood bounds. Default is False.

Returns:
logl_bounds : tuple with shape (2,)

Log-likelihood bounds (logl_min, logl_max) determined by the weights.

weights : tuple with shape (3,), optional

The individual weights (pweight, zweight, weight) used to determine logl_bounds.

dynesty.dynamicsampler.stopping_function(results, args=None, rstate=None, M=None, return_vals=False)

The default stopping function utilized by DynamicSampler. Zipped parameters are passed to the function via args. Assigns the run a stopping value based on a weighted average of the stopping values for the posterior and evidence:

stop = pfrac * stop_post + (1.- pfrac) * stop_evid

The evidence stopping value is based on the estimated evidence error (i.e. standard deviation) relative to a given threshold:

stop_evid = evid_std / evid_thresh

The posterior stopping value is based on the fractional error (i.e. standard deviation / mean) in the Kullback-Leibler (KL) divergence relative to a given threshold:

stop_post = (kld_std / kld_mean) / post_thresh

Estimates of the mean and standard deviation are computed using n_mc realizations of the input using a provided 'error' keyword (either 'jitter' or 'simulate', which call related functions jitter_run() and simulate_run() in dynesty.utils, respectively, or 'sim_approx', which boosts 'jitter' by a factor of two).

Returns the boolean stop <= 1. If True, the DynamicSampler will stop adding new samples to our results.

Parameters:
results : Results instance

Results instance.

args : dictionary of keyword arguments, optional

Arguments used to set the stopping values. Default values are pfrac = 1.0, evid_thresh = 0.1, post_thresh = 0.02, n_mc = 128, error = 'sim_approx', and approx = True.

rstate : RandomState, optional

RandomState instance.

M : map function, optional

An alias to a map-like function. This allows users to pass functions from pools (e.g., pool.map) to compute realizations in parallel. By default the standard map function is used.

return_vals : bool, optional

Whether to return the stopping value (and its components). Default is False.

Returns:
stop_flag : bool

Boolean flag indicating whether we have passed the desired stopping criteria.

stop_vals : tuple of shape (3,), optional

The individual stopping values (stop_post, stop_evid, stop) used to determine the stopping criteria.

dynesty.dynamicsampler._kld_error(args)

Internal pool.map-friendly wrapper for kld_error() used by stopping_function().

Sampling Results

Utilities for handling results.

class dynesty.results.Results

Bases: dict

Contains the full output of a run along with a set of helper functions for summarizing the output.

summary(self)

Return a formatted string giving a quick summary of the results.

dynesty.results.print_fn(results, niter, ncall, add_live_it=None, dlogz=None, stop_val=None, nbatch=None, logl_min=-inf, logl_max=inf, pbar=None)

The default function used to print out results in real time.

Parameters:
results : tuple

Collection of variables output from the current state of the sampler. Currently includes: (1) particle index, (2) unit cube position, (3) parameter position, (4) ln(likelihood), (5) ln(volume), (6) ln(weight), (7) ln(evidence), (8) Var[ln(evidence)], (9) information, (10) number of (current) function calls, (11) iteration when the point was originally proposed, (12) index of the bounding object originally proposed from, (13) index of the bounding object active at a given iteration, (14) cumulative efficiency, and (15) estimated remaining ln(evidence).

niter : int

The current iteration of the sampler.

ncall : int

The total number of function calls at the current iteration.

add_live_it : int, optional

If the last set of live points are being added explicitly, this quantity tracks the sorted index of the current live point being added.

dlogz : float, optional

The evidence stopping criterion. If not provided, the provided stopping value will be used instead.

stop_val : float, optional

The current stopping criterion (for dynamic nested sampling). Used if the dlogz value is not specified.

nbatch : int, optional

The current batch (for dynamic nested sampling).

logl_min : float, optional

The minimum log-likelihood used when starting sampling. Default is -np.inf.

logl_max : float, optional

The maximum log-likelihood used when stopping sampling. Default is np.inf.

Useful Helper Functions

A collection of useful functions.

dynesty.utils.unitcheck(u, nonbounded=None)

Check whether u is inside the unit cube. Given a masked array nonbounded, also allows periodic boundaries conditions to exceed the unit cube.

dynesty.utils.resample_equal(samples, weights, rstate=None)

Resample a new set of points from the weighted set of inputs such that they all have equal weight.

Each input sample appears in the output array either floor(weights[i] * nsamples) or ceil(weights[i] * nsamples) times, with floor or ceil randomly selected (weighted by proximity).

Parameters:
samples : ndarray with shape (nsamples,)

Set of unequally weighted samples.

weights : ndarray with shape (nsamples,)

Corresponding weight of each sample.

rstate : RandomState, optional

RandomState instance.

Returns:
equal_weight_samples : ndarray with shape (nsamples,)

New set of samples with equal weights.

Notes

Implements the systematic resampling method described in Hol, Schon, and Gustafsson (2006).

Examples

>>> x = np.array([[1., 1.], [2., 2.], [3., 3.], [4., 4.]])
>>> w = np.array([0.6, 0.2, 0.15, 0.05])
>>> utils.resample_equal(x, w)
array([[ 1.,  1.],
       [ 1.,  1.],
       [ 1.,  1.],
       [ 3.,  3.]])
dynesty.utils.mean_and_cov(samples, weights)

Compute the weighted mean and covariance of the samples.

Parameters:
samples : ndarray with shape (nsamples, ndim)

2-D array containing data samples. This ordering is equivalent to using rowvar=False in cov.

weights : ndarray with shape (nsamples,)

1-D array of sample weights.

Returns:
mean : ndarray with shape (ndim,)

Weighted sample mean vector.

cov : ndarray with shape (ndim, ndim)

Weighted sample covariance matrix.

Notes

Implements the formulae found here.

dynesty.utils.quantile(x, q, weights=None)

Compute (weighted) quantiles from an input set of samples.

Parameters:
x : ndarray with shape (nsamps,)

Input samples.

q : ndarray with shape (nquantiles,)

The list of quantiles to compute from [0., 1.].

weights : ndarray with shape (nsamps,), optional

The associated weight from each sample.

Returns:
quantiles : ndarray with shape (nquantiles,)

The weighted sample quantiles computed at q.

dynesty.utils.jitter_run(res, rstate=None, approx=False)

Probes statistical uncertainties on a nested sampling run by explicitly generating a realization of the prior volume associated with each sample (dead point). Companion function to resample_run() and simulate_run().

Parameters:
res : Results instance

The Results instance taken from a previous nested sampling run.

rstate : RandomState, optional

RandomState instance.

approx : bool, optional

Whether to approximate all sets of uniform order statistics by their associated marginals (from the Beta distribution). Default is False.

Returns:
new_res : Results instance

A new Results instance with corresponding weights based on our “jittered” prior volume realizations.

dynesty.utils.resample_run(res, rstate=None, return_idx=False)

Probes sampling uncertainties on a nested sampling run using bootstrap resampling techniques to generate a realization of the (expected) prior volume(s) associated with each sample (dead point). This effectively splits a nested sampling run with K particles (live points) into a series of K “strands” (i.e. runs with a single live point) which are then bootstrapped to construct a new “resampled” run. Companion function to jitter_run() and simulate_run().

Parameters:
res : Results instance

The Results instance taken from a previous nested sampling run.

rstate : RandomState, optional

RandomState instance.

return_idx : bool, optional

Whether to return the list of resampled indices used to construct the new run. Default is False.

Returns:
new_res : Results instance

A new Results instance with corresponding samples and weights based on our “bootstrapped” samples and (expected) prior volumes.

dynesty.utils.simulate_run(res, rstate=None, return_idx=False, approx=False)

Probes combined uncertainties (statistical and sampling) on a nested sampling run by wrapping jitter_run() and resample_run().

Parameters:
res : Results instance

The Results instance taken from a previous nested sampling run.

rstate : RandomState, optional

RandomState instance.

return_idx : bool, optional

Whether to return the list of resampled indices used to construct the new run. Default is False.

approx : bool, optional

Whether to approximate all sets of uniform order statistics by their associated marginals (from the Beta distribution). Default is False.

Returns:
new_res : Results instance

A new Results instance with corresponding samples and weights based on our “simulated” samples and prior volumes.

dynesty.utils.reweight_run(res, logp_new, logp_old=None)

Reweight a given run based on a new target distribution.

Parameters:
res : Results instance

The Results instance taken from a previous nested sampling run.

logp_new : ndarray with shape (nsamps,)

New target distribution evaluated at the location of the samples.

logp_old : ndarray with shape (nsamps,)

Old target distribution evaluated at the location of the samples. If not provided, the logl values from res will be used.

Returns:
new_res : Results instance

A new Results instance with corresponding weights based on our reweighted samples.

dynesty.utils.unravel_run(res, save_proposals=True, print_progress=True)

Unravels a run with K live points into K “strands” (a nested sampling run with only 1 live point). WARNING: the anciliary quantities provided with each unraveled “strand” are only valid if the point was initialized from the prior.

Parameters:
res : Results instance

The Results instance taken from a previous nested sampling run.

save_proposals : bool, optional

Whether to save a reference to the proposal distributions from the original run in each unraveled strand. Default is True.

print_progress : bool, optional

Whether to output the current progress to stderr. Default is True.

Returns:
new_res : list of Results instances

A list of new Results instances for each individual strand.

dynesty.utils.merge_runs(res_list, print_progress=True)

Merges a set of runs with differing (possibly variable) numbers of live points into one run.

Parameters:
res_list : list of Results instances

A list of Results instances returned from previous runs.

print_progress : bool, optional

Whether to output the current progress to stderr. Default is True.

Returns:
combined_res : Results instance

The Results instance for the combined run.

dynesty.utils.kl_divergence(res1, res2)

Computes the Kullback-Leibler (KL) divergence from the discrete probability distribution defined by res2 to the discrete probability distribution defined by res1.

Parameters:
res1 : Results instance

Results instance for the distribution we are computing the KL divergence to. Note that, by construction, the samples in `res1` *must* be a subset of the samples in `res2`.

res2 : Results instance

Results instance for the distribution we are computing the KL divergence from. Note that, by construction, the samples in `res2` *must* be a superset of the samples in `res1`.

Returns:
kld : ndarray with shape (nsamps,)

The cumulative KL divergence defined over res1.

dynesty.utils.kld_error(res, error='simulate', rstate=None, return_new=False, approx=False)

Computes the Kullback-Leibler (KL) divergence from the discrete probability distribution defined by res to the discrete probability distribution defined by a realization of res.

Parameters:
res : Results instance

Results instance for the distribution we are computing the KL divergence from.

error : {'jitter', 'resample', 'simulate'}, optional

The error method employed, corresponding to jitter_run(), resample_run(), and simulate_run(), respectively. Default is 'simulate'.

rstate : RandomState, optional

RandomState instance.

return_new : bool, optional

Whether to return the realization of the run used to compute the KL divergence. Default is False.

approx : bool, optional

Whether to approximate all sets of uniform order statistics by their associated marginals (from the Beta distribution). Default is False.

Returns:
kld : ndarray with shape (nsamps,)

The cumulative KL divergence defined from res to a random realization of res.

new_res : Results instance, optional

The Results instance corresponding to the random realization we computed the KL divergence to.

dynesty.utils._merge_two(res1, res2, compute_aux=False)

Internal method used to merges two runs with differing (possibly variable) numbers of live points into one run.

Parameters:
res1 : Results instance

The “base” nested sampling run.

res2 : Results instance

The “new” nested sampling run.

compute_aux : bool, optional

Whether to compute auxiliary quantities (evidences, etc.) associated with a given run. WARNING: these are only valid if `res1` or `res2` was initialized from the prior *and* their sampling bounds overlap. Default is False.

Returns:
res : Results instances

Results instance from the newly combined nested sampling run.

dynesty.utils._get_nsamps_samples_n(res)

Helper function for calculating the number of samples

Parameters:
res : Results instance

The Results instance taken from a previous nested sampling run.

Returns:
nsamps: int

The total number of samples

samples_n: array

Number of live points at a given iteration

Plotting Utilities

A set of built-in plotting functions to help visualize dynesty nested sampling Results.

dynesty.plotting.runplot(results, span=None, logplot=False, kde=True, nkde=1000, color='blue', plot_kwargs=None, label_kwargs=None, lnz_error=True, lnz_truth=None, truth_color='red', truth_kwargs=None, max_x_ticks=8, max_y_ticks=3, use_math_text=True, mark_final_live=True, fig=None)

Plot live points, ln(likelihood), ln(weight), and ln(evidence) as a function of ln(prior volume).

Parameters:
results : Results instance

A Results instance from a nested sampling run.

span : iterable with shape (4,), optional

A list where each element is either a length-2 tuple containing lower and upper bounds or a float from (0., 1.] giving the fraction below the maximum. If a fraction is provided, the bounds are chosen to be equal-tailed. An example would be:

span = [(0., 10.), 0.001, 0.2, (5., 6.)]

Default is (0., 1.05 * max(data)) for each element.

logplot : bool, optional

Whether to plot the evidence on a log scale. Default is False.

kde : bool, optional

Whether to use kernel density estimation to estimate and plot the PDF of the importance weights as a function of log-volume (as opposed to the importance weights themselves). Default is True.

nkde : int, optional

The number of grid points used when plotting the kernel density estimate. Default is 1000.

color : str or iterable with shape (4,), optional

A matplotlib-style color (either a single color or a different value for each subplot) used when plotting the lines in each subplot. Default is 'blue'.

plot_kwargs : dict, optional

Extra keyword arguments that will be passed to plot.

label_kwargs : dict, optional

Extra keyword arguments that will be sent to the set_xlabel and set_ylabel methods.

lnz_error : bool, optional

Whether to plot the 1, 2, and 3-sigma approximate error bars derived from the ln(evidence) error approximation over the course of the run. Default is True.

lnz_truth : float, optional

A reference value for the evidence that will be overplotted on the evidence subplot if provided.

truth_color : str or iterable with shape (ndim,), optional

A matplotlib-style color used when plotting lnz_truth. Default is 'red'.

truth_kwargs : dict, optional

Extra keyword arguments that will be used for plotting lnz_truth.

max_x_ticks : int, optional

Maximum number of ticks allowed for the x axis. Default is 8.

max_y_ticks : int, optional

Maximum number of ticks allowed for the y axis. Default is 4.

use_math_text : bool, optional

Whether the axis tick labels for very large/small exponents should be displayed as powers of 10 rather than using e. Default is False.

mark_final_live : bool, optional

Whether to indicate the final addition of recycled live points (if they were added to the resulting samples) using a dashed vertical line. Default is True.

fig : (Figure, Axes), optional

If provided, overplot the run onto the provided figure. Otherwise, by default an internal figure is generated.

Returns:
runplot : (Figure, Axes)

Output summary plot.

dynesty.plotting.traceplot(results, span=None, quantiles=[0.025, 0.5, 0.975], smooth=0.02, thin=1, dims=None, post_color='blue', post_kwargs=None, kde=True, nkde=1000, trace_cmap='plasma', trace_color=None, trace_kwargs=None, connect=False, connect_highlight=10, connect_color='red', connect_kwargs=None, max_n_ticks=5, use_math_text=False, labels=None, label_kwargs=None, show_titles=False, title_quantiles=[0.025, 0.5, 0.975], title_fmt='.2f', title_kwargs=None, truths=None, truth_color='red', truth_kwargs=None, verbose=False, fig=None)

Plot traces and marginalized posteriors for each parameter.

Parameters:
results : Results instance

A Results instance from a nested sampling run. Compatible with results derived from nestle.

span : iterable with shape (ndim,), optional

A list where each element is either a length-2 tuple containing lower and upper bounds or a float from (0., 1.] giving the fraction of (weighted) samples to include. If a fraction is provided, the bounds are chosen to be equal-tailed. An example would be:

span = [(0., 10.), 0.95, (5., 6.)]

Default is 0.999999426697 (5-sigma credible interval) for each parameter.

quantiles : iterable, optional

A list of fractional quantiles to overplot on the 1-D marginalized posteriors as vertical dashed lines. Default is [0.025, 0.5, 0.975] (the 95%/2-sigma credible interval).

smooth : float or iterable with shape (ndim,), optional

The standard deviation (either a single value or a different value for each subplot) for the Gaussian kernel used to smooth the 1-D marginalized posteriors, expressed as a fraction of the span. Default is 0.02 (2% smoothing). If an integer is provided instead, this will instead default to a simple (weighted) histogram with bins=smooth.

thin : int, optional

Thin the samples so that only each thin-th sample is plotted. Default is 1 (no thinning).

dims : iterable of shape (ndim,), optional

The subset of dimensions that should be plotted. If not provided, all dimensions will be shown.

post_color : str or iterable with shape (ndim,), optional

A matplotlib-style color (either a single color or a different value for each subplot) used when plotting the histograms. Default is 'blue'.

post_kwargs : dict, optional

Extra keyword arguments that will be used for plotting the marginalized 1-D posteriors.

kde : bool, optional

Whether to use kernel density estimation to estimate and plot the PDF of the importance weights as a function of log-volume (as opposed to the importance weights themselves). Default is True.

nkde : int, optional

The number of grid points used when plotting the kernel density estimate. Default is 1000.

trace_cmap : str or iterable with shape (ndim,), optional

A matplotlib-style colormap (either a single colormap or a different colormap for each subplot) used when plotting the traces, where each point is colored according to its weight. Default is 'plasma'.

trace_color : str or iterable with shape (ndim,), optional

A matplotlib-style color (either a single color or a different color for each subplot) used when plotting the traces. This overrides the trace_cmap option by giving all points the same color. Default is None (not used).

trace_kwargs : dict, optional

Extra keyword arguments that will be used for plotting the traces.

connect : bool, optional

Whether to draw lines connecting the paths of unique particles. Default is False.

connect_highlight : int or iterable, optional

If connect=True, highlights the paths of a specific set of particles. If an integer is passed, connect_highlight random particle paths will be highlighted. If an iterable is passed, then the particle paths corresponding to the provided indices will be highlighted.

connect_color : str, optional

The color of the highlighted particle paths. Default is 'red'.

connect_kwargs : dict, optional

Extra keyword arguments used for plotting particle paths.

max_n_ticks : int, optional

Maximum number of ticks allowed. Default is 5.

use_math_text : bool, optional

Whether the axis tick labels for very large/small exponents should be displayed as powers of 10 rather than using e. Default is False.

labels : iterable with shape (ndim,), optional

A list of names for each parameter. If not provided, the default name used when plotting will follow \(x_i\) style.

label_kwargs : dict, optional

Extra keyword arguments that will be sent to the set_xlabel and set_ylabel methods.

show_titles : bool, optional

Whether to display a title above each 1-D marginalized posterior showing the 0.5 quantile along with the upper/lower bounds associated with the 0.025 and 0.975 (95%/2-sigma credible interval) quantiles. Default is True.

title_quantiles : iterable, optional

A list of fractional quantiles to use in the title. Default is [0.025, 0.5, 0.975] (median plus 95%/2-sigma credible interval).

title_fmt : str, optional

The format string for the quantiles provided in the title. Default is '.2f'.

title_kwargs : dict, optional

Extra keyword arguments that will be sent to the set_title command.

truths : iterable with shape (ndim,), optional

A list of reference values that will be overplotted on the traces and marginalized 1-D posteriors as solid horizontal/vertical lines. Individual values can be exempt using None. Default is None.

truth_color : str or iterable with shape (ndim,), optional

A matplotlib-style color (either a single color or a different value for each subplot) used when plotting truths. Default is 'red'.

truth_kwargs : dict, optional

Extra keyword arguments that will be used for plotting the vertical and horizontal lines with truths.

verbose : bool, optional

Whether to print the values of the computed quantiles associated with each parameter. Default is False.

fig : (Figure, Axes), optional

If provided, overplot the traces and marginalized 1-D posteriors onto the provided figure. Otherwise, by default an internal figure is generated.

Returns:
traceplot : (Figure, Axes)

Output trace plot.

dynesty.plotting.cornerpoints(results, dims=None, thin=1, span=None, cmap='plasma', color=None, kde=True, nkde=1000, plot_kwargs=None, labels=None, label_kwargs=None, truths=None, truth_color='red', truth_kwargs=None, max_n_ticks=5, use_math_text=False, fig=None)

Generate a (sub-)corner plot of (weighted) samples.

Parameters:
results : Results instance

A Results instance from a nested sampling run. Compatible with results derived from nestle.

dims : iterable of shape (ndim,), optional

The subset of dimensions that should be plotted. If not provided, all dimensions will be shown.

thin : int, optional

Thin the samples so that only each thin-th sample is plotted. Default is 1 (no thinning).

span : iterable with shape (ndim,), optional

A list where each element is either a length-2 tuple containing lower and upper bounds or a float from (0., 1.] giving the fraction of (weighted) samples to include. If a fraction is provided, the bounds are chosen to be equal-tailed. An example would be:

span = [(0., 10.), 0.95, (5., 6.)]

Default is 1. for all parameters (no bound).

cmap : str, optional

A matplotlib-style colormap used when plotting the points, where each point is colored according to its weight. Default is 'plasma'.

color : str, optional

A matplotlib-style color used when plotting the points. This overrides the cmap option by giving all points the same color. Default is None (not used).

kde : bool, optional

Whether to use kernel density estimation to estimate and plot the PDF of the importance weights as a function of log-volume (as opposed to the importance weights themselves). Default is True.

nkde : int, optional

The number of grid points used when plotting the kernel density estimate. Default is 1000.

plot_kwargs : dict, optional

Extra keyword arguments that will be used for plotting the points.

labels : iterable with shape (ndim,), optional

A list of names for each parameter. If not provided, the default name used when plotting will follow \(x_i\) style.

label_kwargs : dict, optional

Extra keyword arguments that will be sent to the set_xlabel and set_ylabel methods.

truths : iterable with shape (ndim,), optional

A list of reference values that will be overplotted on the traces and marginalized 1-D posteriors as solid horizontal/vertical lines. Individual values can be exempt using None. Default is None.

truth_color : str or iterable with shape (ndim,), optional

A matplotlib-style color (either a single color or a different value for each subplot) used when plotting truths. Default is 'red'.

truth_kwargs : dict, optional

Extra keyword arguments that will be used for plotting the vertical and horizontal lines with truths.

max_n_ticks : int, optional

Maximum number of ticks allowed. Default is 5.

use_math_text : bool, optional

Whether the axis tick labels for very large/small exponents should be displayed as powers of 10 rather than using e. Default is False.

fig : (Figure, Axes), optional

If provided, overplot the points onto the provided figure object. Otherwise, by default an internal figure is generated.

Returns:
cornerpoints : (Figure, Axes)

Output (sub-)corner plot of (weighted) samples.

dynesty.plotting.cornerplot(results, dims=None, span=None, quantiles=[0.025, 0.5, 0.975], color='black', smooth=0.02, quantiles_2d=None, hist_kwargs=None, hist2d_kwargs=None, labels=None, label_kwargs=None, show_titles=False, title_quantiles=[0.025, 0.5, 0.975], title_fmt='.2f', title_kwargs=None, truths=None, truth_color='red', truth_kwargs=None, max_n_ticks=5, top_ticks=False, use_math_text=False, verbose=False, fig=None)

Generate a corner plot of the 1-D and 2-D marginalized posteriors.

Parameters:
results : Results instance

A Results instance from a nested sampling run. Compatible with results derived from nestle.

dims : iterable of shape (ndim,), optional

The subset of dimensions that should be plotted. If not provided, all dimensions will be shown.

span : iterable with shape (ndim,), optional

A list where each element is either a length-2 tuple containing lower and upper bounds or a float from (0., 1.] giving the fraction of (weighted) samples to include. If a fraction is provided, the bounds are chosen to be equal-tailed. An example would be:

span = [(0., 10.), 0.95, (5., 6.)]

Default is 0.999999426697 (5-sigma credible interval).

quantiles : iterable, optional

A list of fractional quantiles to overplot on the 1-D marginalized posteriors as vertical dashed lines. Default is [0.025, 0.5, 0.975] (spanning the 95%/2-sigma credible interval).

color : str or iterable with shape (ndim,), optional

A matplotlib-style color (either a single color or a different value for each subplot) used when plotting the histograms. Default is 'black'.

smooth : float or iterable with shape (ndim,), optional

The standard deviation (either a single value or a different value for each subplot) for the Gaussian kernel used to smooth the 1-D and 2-D marginalized posteriors, expressed as a fraction of the span. Default is 0.02 (2% smoothing). If an integer is provided instead, this will instead default to a simple (weighted) histogram with bins=smooth.

quantiles_2d : iterable with shape (nquant,), optional

The quantiles used for plotting the smoothed 2-D distributions. If not provided, these default to 0.5, 1, 1.5, and 2-sigma contours roughly corresponding to quantiles of [0.1, 0.4, 0.65, 0.85].

hist_kwargs : dict, optional

Extra keyword arguments to send to the 1-D (smoothed) histograms.

hist2d_kwargs : dict, optional

Extra keyword arguments to send to the 2-D (smoothed) histograms.

labels : iterable with shape (ndim,), optional

A list of names for each parameter. If not provided, the default name used when plotting will follow \(x_i\) style.

label_kwargs : dict, optional

Extra keyword arguments that will be sent to the set_xlabel and set_ylabel methods.

show_titles : bool, optional

Whether to display a title above each 1-D marginalized posterior showing the 0.5 quantile along with the upper/lower bounds associated with the 0.025 and 0.975 (95%/2-sigma credible interval) quantiles. Default is True.

title_quantiles : iterable, optional

A list of fractional quantiles to use in the title. Default is [0.025, 0.5, 0.975] (median plus 95%/2-sigma credible interval).

title_fmt : str, optional

The format string for the quantiles provided in the title. Default is '.2f'.

title_kwargs : dict, optional

Extra keyword arguments that will be sent to the set_title command.

truths : iterable with shape (ndim,), optional

A list of reference values that will be overplotted on the traces and marginalized 1-D posteriors as solid horizontal/vertical lines. Individual values can be exempt using None. Default is None.

truth_color : str or iterable with shape (ndim,), optional

A matplotlib-style color (either a single color or a different value for each subplot) used when plotting truths. Default is 'red'.

truth_kwargs : dict, optional

Extra keyword arguments that will be used for plotting the vertical and horizontal lines with truths.

max_n_ticks : int, optional

Maximum number of ticks allowed. Default is 5.

top_ticks : bool, optional

Whether to label the top (rather than bottom) ticks. Default is False.

use_math_text : bool, optional

Whether the axis tick labels for very large/small exponents should be displayed as powers of 10 rather than using e. Default is False.

verbose : bool, optional

Whether to print the values of the computed quantiles associated with each parameter. Default is False.

fig : (Figure, Axes), optional

If provided, overplot the traces and marginalized 1-D posteriors onto the provided figure. Otherwise, by default an internal figure is generated.

Returns:
cornerplot : (Figure, Axes)

Output corner plot.

dynesty.plotting.boundplot(results, dims, it=None, idx=None, prior_transform=None, periodic=None, reflective=None, ndraws=5000, color='gray', plot_kwargs=None, labels=None, label_kwargs=None, max_n_ticks=5, use_math_text=False, show_live=False, live_color='darkviolet', live_kwargs=None, span=None, fig=None)

Return the bounding distribution used to propose either (1) live points at a given iteration or (2) a specific dead point during the course of a run, projected onto the two dimensions specified by dims.

Parameters:
results : Results instance

A Results instance from a nested sampling run.

dims : length-2 tuple

The dimensions used to plot the bounding.

it : int, optional

If provided, returns the bounding distribution at the specified iteration of the nested sampling run. Note that this option and `idx` are mutually exclusive.

idx : int, optional

If provided, returns the bounding distribution used to propose the dead point at the specified iteration of the nested sampling run. Note that this option and `it` are mutually exclusive.

prior_transform : func, optional

The function transforming samples within the unit cube back to samples in the native model space. If provided, the transformed bounding distribution will be plotted in the native model space.

periodic : iterable, optional

A list of indices for parameters with periodic boundary conditions. These parameters will not have their positions constrained to be within the unit cube, enabling smooth behavior for parameters that may wrap around the edge. Default is None (i.e. no periodic boundary conditions).

reflective : iterable, optional

A list of indices for parameters with reflective boundary conditions. These parameters will not have their positions constrained to be within the unit cube, enabling smooth behavior for parameters that may reflect at the edge. Default is None (i.e. no reflective boundary conditions).

ndraws : int, optional

The number of random samples to draw from the bounding distribution when plotting. Default is 5000.

color : str, optional

The color of the points randomly sampled from the bounding distribution. Default is 'gray'.

plot_kwargs : dict, optional

Extra keyword arguments used when plotting the bounding draws.

labels : iterable with shape (ndim,), optional

A list of names for each parameter. If not provided, the default name used when plotting will follow \(x_i\) style.

label_kwargs : dict, optional

Extra keyword arguments that will be sent to the set_xlabel and set_ylabel methods.

max_n_ticks : int, optional

Maximum number of ticks allowed. Default is 5.

use_math_text : bool, optional

Whether the axis tick labels for very large/small exponents should be displayed as powers of 10 rather than using e. Default is False.

show_live : bool, optional

Whether the live points at a given iteration (for it) or associated with the bounding (for idx) should be highlighted. Default is False. In the dynamic case, only the live points associated with the batch used to construct the relevant bound are plotted.

live_color : str, optional

The color of the live points. Default is 'darkviolet'.

live_kwargs : dict, optional

Extra keyword arguments used when plotting the live points.

span : iterable with shape (2,), optional

A list where each element is a length-2 tuple containing lower and upper bounds. Default is None (no bound).

fig : (Figure, Axes), optional

If provided, overplot the draws onto the provided figure. Otherwise, by default an internal figure is generated.

Returns:
bounding_plot : (Figure, Axes)

Output plot of the bounding distribution.

dynesty.plotting.cornerbound(results, it=None, idx=None, dims=None, prior_transform=None, periodic=None, reflective=None, ndraws=5000, color='gray', plot_kwargs=None, labels=None, label_kwargs=None, max_n_ticks=5, use_math_text=False, show_live=False, live_color='darkviolet', live_kwargs=None, span=None, fig=None)

Return the bounding distribution used to propose either (1) live points at a given iteration or (2) a specific dead point during the course of a run, projected onto all pairs of dimensions.

Parameters:
results : Results instance

A Results instance from a nested sampling run.

it : int, optional

If provided, returns the bounding distribution at the specified iteration of the nested sampling run. Note that this option and `idx` are mutually exclusive.

idx : int, optional

If provided, returns the bounding distribution used to propose the dead point at the specified iteration of the nested sampling run. Note that this option and `it` are mutually exclusive.

dims : iterable of shape (ndim,), optional

The subset of dimensions that should be plotted. If not provided, all dimensions will be shown.

prior_transform : func, optional

The function transforming samples within the unit cube back to samples in the native model space. If provided, the transformed bounding distribution will be plotted in the native model space.

periodic : iterable, optional

A list of indices for parameters with periodic boundary conditions. These parameters will not have their positions constrained to be within the unit cube, enabling smooth behavior for parameters that may wrap around the edge. Default is None (i.e. no periodic boundary conditions).

reflective : iterable, optional

A list of indices for parameters with reflective boundary conditions. These parameters will not have their positions constrained to be within the unit cube, enabling smooth behavior for parameters that may reflect at the edge. Default is None (i.e. no reflective boundary conditions).

ndraws : int, optional

The number of random samples to draw from the bounding distribution when plotting. Default is 5000.

color : str, optional

The color of the points randomly sampled from the bounding distribution. Default is 'gray'.

plot_kwargs : dict, optional

Extra keyword arguments used when plotting the bounding draws.

labels : iterable with shape (ndim,), optional

A list of names for each parameter. If not provided, the default name used when plotting will be in \(x_i\) style.

label_kwargs : dict, optional

Extra keyword arguments that will be sent to the set_xlabel and set_ylabel methods.

max_n_ticks : int, optional

Maximum number of ticks allowed. Default is 5.

use_math_text : bool, optional

Whether the axis tick labels for very large/small exponents should be displayed as powers of 10 rather than using e. Default is False.

show_live : bool, optional

Whether the live points at a given iteration (for it) or associated with the bounding (for idx) should be highlighted. Default is False. In the dynamic case, only the live points associated with the batch used to construct the relevant bound are plotted.

live_color : str, optional

The color of the live points. Default is 'darkviolet'.

live_kwargs : dict, optional

Extra keyword arguments used when plotting the live points.

span : iterable with shape (2,), optional

A list where each element is a length-2 tuple containing lower and upper bounds. Default is None (no bound).

fig : (Figure, Axes), optional

If provided, overplot the draws onto the provided figure. Otherwise, by default an internal figure is generated.

Returns:
cornerbound : (Figure, Axes)

Output corner plot of the bounding distribution.

dynesty.plotting._hist2d(x, y, smooth=0.02, span=None, weights=None, levels=None, ax=None, color='gray', plot_datapoints=False, plot_density=True, plot_contours=True, no_fill_contours=False, fill_contours=True, contour_kwargs=None, contourf_kwargs=None, data_kwargs=None, **kwargs)

Internal function called by cornerplot() used to generate a a 2-D histogram/contour of samples.

Parameters:
x : interable with shape (nsamps,)

Sample positions in the first dimension.

y : iterable with shape (nsamps,)

Sample positions in the second dimension.

span : iterable with shape (ndim,), optional

A list where each element is either a length-2 tuple containing lower and upper bounds or a float from (0., 1.] giving the fraction of (weighted) samples to include. If a fraction is provided, the bounds are chosen to be equal-tailed. An example would be:

span = [(0., 10.), 0.95, (5., 6.)]

Default is 0.999999426697 (5-sigma credible interval).

weights : iterable with shape (nsamps,)

Weights associated with the samples. Default is None (no weights).

levels : iterable, optional

The contour levels to draw. Default are [0.5, 1, 1.5, 2]-sigma.

ax : Axes, optional

An axes instance on which to add the 2-D histogram. If not provided, a figure will be generated.

color : str, optional

The matplotlib-style color used to draw lines and color cells and contours. Default is 'gray'.

plot_datapoints : bool, optional

Whether to plot the individual data points. Default is False.

plot_density : bool, optional

Whether to draw the density colormap. Default is True.

plot_contours : bool, optional

Whether to draw the contours. Default is True.

no_fill_contours : bool, optional

Whether to add absolutely no filling to the contours. This differs from fill_contours=False, which still adds a white fill at the densest points. Default is False.

fill_contours : bool, optional

Whether to fill the contours. Default is True.

contour_kwargs : dict

Any additional keyword arguments to pass to the contour method.

contourf_kwargs : dict

Any additional keyword arguments to pass to the contourf method.

data_kwargs : dict

Any additional keyword arguments to pass to the plot method when adding the individual data points.