cpnest package

Submodules

cpnest.NestedSampling module

class cpnest.NestedSampling.NestedSampler(model, manager=None, nlive=1024, output=None, verbose=1, seed=1, prior_sampling=False, stopping=0.1, n_periodic_checkpoint=None)[source]

Bases: object

Nested Sampler class. Initialisation arguments:

model: cpnest.Model user defined model

manager: multiprocessing manager instance which controls

the shared objects. Default: None

Nlive: int

number of live points to be used for the integration Default: 1024

output: string

folder where the output will be stored Default: None

verbose: int

0: Nothing 1: display information on screen 2: (1) + diagnostic plots Default: 1

seed: int

seed for the initialisation of the pseudorandom chain Default: 1234

prior_sampling: boolean

produce Nlive samples from the prior. Default: False

stopping: float

Stop when remaining samples wouldn’t change logZ estimate by this much. Deafult: 0.1

n_periodic_checkpoint: int

deprecated This parameter should not be used, it should be set by the manager instead. checkpoint the sampler every n_periodic_checkpoint iterations Default: None (disabled)

checkpoint()[source]

Checkpoint its internal state

consume_sample()[source]

consumes a sample from the consumer_pipes and updates the evidence logZ

get_worst_n_live_points(n)[source]

selects the lowest likelihood N live points for evolution

nested_sampling_loop()[source]

main nested sampling loop

reset()[source]

Initialise the pool of cpnest.parameter.LivePoint by sampling them from the cpnest.model.log_prior distribution

classmethod resume(filename, manager, usermodel)[source]

Resumes the interrupted state from a checkpoint pickle file.

setup_output(output)[source]

Set up the output folder

Parameters: output: string

folder where the results will be stored

Returns

tuple

output_file: file where the nested samples will be written evidence_file: file where the evidence will be written resume_file: file used for checkpointing the algorithm

Return type

output_file, evidence_file, resume_file

setup_random_seed(seed)[source]

initialise the random seed

write_chain_to_file()[source]

Outputs a cpnest.parameter.LivePoint to the output_file

write_evidence_to_file()[source]

Write the evidence logZ and maximum likelihood to the evidence_file

cpnest.cpnest module

class cpnest.cpnest.CPNest(usermodel, nlive=100, poolsize=100, output='./', verbose=0, seed=None, maxmcmc=100, nthreads=None, nhamiltonian=0, nslice=0, resume=False, proposals=None, n_periodic_checkpoint=None, periodic_checkpoint_interval=None, prior_sampling=False)[source]

Bases: object

Class to control CPNest sampler cp = CPNest(usermodel,nlive=100,output=’./’,verbose=0,seed=None,maxmcmc=100,nthreads=None,balanced_sampling = True)

usermodel: cpnest.Model

a user-defined model to analyse

nlive: int

Number of live points (100)

poolsize: int

Number of objects in the sampler pool (100)

outputstr

output directory (./)

verbose: int
Verbosity:

0: no display of information on screen, save the NS chain and evidence 1: 0 + display progress on screen 2: 1 + display diagnostics (ACL), save the posterior samples and trace plots and posterior plots 3: 2 + save chains from individual samplers default: 0

seed: int

random seed (default: 1234)

maxmcmc: int

maximum MCMC points for sampling chains (100)

nthreads: int or None

number of parallel samplers. Default (None) uses mp.cpu_count() to autodetermine

nhamiltonian: int

number of sampler threads using an hamiltonian samplers. Default: 0

nslice: int

number of sampler threads using an ensemble slice samplers. Default: 0

resume: boolean

determines whether cpnest will resume a run or run from scratch. Default: False.

proposal: dict

dictionary of lists with custom jump proposals. key ‘mhs’ for the Metropolis-Hastings sampler, ‘hmc’ for the Hamiltonian Monte-Carlo sampler, ‘sli’ for the slice sampler. ‘hmc’ for the Hamiltonian Monte-Carlo sampler. Default: None

prior_sampling: boolean

generates samples from the prior

n_periodic_checkpoint: int

deprecated checkpoint the sampler every n_periodic_checkpoint iterations Default: None (disabled)

periodic_checkpoint_interval: float

checkpoing the sampler every periodic_checkpoint_interval seconds Default: None (disabled)

prior_sampling: boolean

produce nlive samples from the prior. Default: False

checkpoint()[source]
get_mcmc_samples(filename='mcmc.dat')[source]

Returns resampled mcmc samples

Parameters

filename (string) – If given, file to save posterior samples to

Returns

pos

Return type

numpy.ndarray

get_nested_samples(filename='nested_samples.dat')[source]

returns nested sampling chain :param filename: If given, file to save nested samples to :type filename: string

Returns

pos

Return type

numpy.ndarray

get_posterior_samples(filename='posterior.dat')[source]

Returns posterior samples

Parameters

filename (string) – If given, file to save posterior samples to

Returns

pos

Return type

numpy.ndarray

get_prior_samples(filename='prior.dat')[source]

Returns prior samples

Parameters

filename (string) – If given, file to save posterior samples to

Returns

pos

Return type

numpy.ndarray

plot(corner=True)[source]

Make diagnostic plots of the posterior and nested samples

profile()[source]
run()[source]

Run the sampler

worker_ns()[source]
worker_sampler(producer_pipe, logLmin)[source]
exception cpnest.cpnest.CheckPoint[source]

Bases: Exception

class cpnest.cpnest.RunManager(nthreads=None, **kwargs)[source]

Bases: multiprocessing.managers.SyncManager

connect_producer()[source]

Returns the producer’s end of the pipe

start()[source]

Spawn a server process for this manager object

cpnest.cpnest.sighandler(signal, frame)[source]

cpnest.model module

class cpnest.model.Model[source]

Bases: object

Base class for user’s model. User should subclass this and implement log_likelihood, names and bounds

bounds = []
force(param)[source]

returns the force (-grad potential) Required for Hamiltonian sampling

Parameter: param: cpnest.parameter.LivePoint

from_normalised(normalised_value)[source]

Maps from [0,1]^Ndim to the full range of the parameters Inverse of to_normalised() ———- Parameter:

normalised_vaue: array-like values in range (0,1)

Returns

cpnest.parameter.LivePoint

Return type

point

header()[source]

Return a string with the output file header

in_bounds(param)[source]

Checks whether param lies within the bounds

Parameters

paramcpnest.parameter.LivePoint

Returns

if all dimensions are within the bounds False: otherwise

Return type

True

abstract log_likelihood(param)[source]

returns log likelihood of given parameter

Parameter:

param: cpnest.parameter.LivePoint

log_prior(param)[source]

Returns log of prior. Default is flat prior within bounds

Parameter:

param: cpnest.parameter.LivePoint

Returns

0 if param is in bounds -np.inf otherwise

names = []
new_point()[source]

Create a new LivePoint, drawn from within bounds

Returns

cpnest.parameter.LivePoint

Return type

p

potential(param)[source]

Parameter: param: cpnest.parameter.LivePoint

Returns

obj: -cpnest.model.log_prior

strsample(sample)[source]

Return a string representation for the sample to be written to the output file. User may overload for additional output ———- Parameter:

Returns

string

Return type

line

to_normalised(point)[source]
Parameter:

point: cpnest.parameter.LivePoint

Returns

array.array

The values of the parameter mapped into the Ndim-cube

Return type

normalised_value

cpnest.model.uniform(low=0.0, high=1.0, size=None)

Draw samples from a uniform distribution.

Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform.

Note

New code should use the uniform method of a default_rng() instance instead; see random-quick-start.

Parameters
  • low (float or array_like of floats, optional) – Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0.

  • high (float or array_like of floats) – Upper boundary of the output interval. All values generated will be less than or equal to high. The default value is 1.0.

  • size (int or tuple of ints, optional) – Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if low and high are both scalars. Otherwise, np.broadcast(low, high).size samples are drawn.

Returns

out – Drawn samples from the parameterized uniform distribution.

Return type

ndarray or scalar

See also

randint

Discrete uniform distribution, yielding integers.

random_integers

Discrete uniform distribution over the closed interval [low, high].

random_sample

Floats uniformly distributed over [0, 1).

random

Alias for random_sample.

rand

Convenience function that accepts dimensions as input, e.g., rand(2,2) would generate a 2-by-2 array of floats, uniformly distributed over [0, 1).

Generator.uniform

which should be used for new code.

Notes

The probability density function of the uniform distribution is

\[p(x) = \frac{1}{b - a}\]

anywhere within the interval [a, b), and zero elsewhere.

When high == low, values of low will be returned. If high < low, the results are officially undefined and may eventually raise an error, i.e. do not rely on this function to behave when passed arguments satisfying that inequality condition. The high limit may be included in the returned array of floats due to floating-point rounding in the equation low + (high-low) * random_sample(). For example:

>>> x = np.float32(5*0.99999999)
>>> x
5.0

Examples

Draw samples from the distribution:

>>> s = np.random.uniform(-1,0,1000)

All values are within the given interval:

>>> np.all(s >= -1)
True
>>> np.all(s < 0)
True

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 15, density=True)
>>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
>>> plt.show()

cpnest.nest2pos module

cpnest.nest2pos.acl(x, tolerance=0.01)[source]

Compute autocorrelation time for x

cpnest.nest2pos.autocorrelation(x)[source]

Compute the autocorrelation of the chain using an FFT

cpnest.nest2pos.compute_weights(data, Nlive)[source]

Returns log_ev, log_wts for the log-likelihood samples in data, assumed to be a result of nested sampling with Nlive live points.

cpnest.nest2pos.draw_N_posterior(data, log_wts, N, verbose=False)[source]

Draw N samples from the input data, weighted by log_wt. For large N there may be repeated samples

cpnest.nest2pos.draw_N_posterior_many(datas, Nlives, Npost, verbose=False)[source]

Draw Npost samples from the posteriors represented by the (Nruns, Nsamples, Nparams)-shaped array datas, each sampled with the corresponding number of live points Nlive. The returned number of samples may not be exactly Npost due to rounding

cpnest.nest2pos.draw_posterior(data, log_wts, verbose=False)[source]

Draw points from the given data (of shape (Nsamples, Ndim)) with associated log(weight) (of shape (Nsamples,)). Draws uniquely so there are no repeated samples

cpnest.nest2pos.draw_posterior_many(datas, Nlives, verbose=False)[source]

Draw samples from the posteriors represented by the (Nruns, Nsamples, Nparams)-shaped array datas, each sampled with the corresponding Nlive number of live points. Will draw without repetition, and weight according to the evidence in each input run

cpnest.nest2pos.log_integrate_log_trap(log_func, log_support)[source]

Trapezoidal integration of given log(func) Returns log of the integral

cpnest.nest2pos.logsubexp(x, y)[source]

Helper function to compute the exponential of a difference between two numbers

Parameter:

x: :float: y: :float:

Return

z: :float: x + np.log1p(-np.exp(y-x))

cpnest.nest2pos.resample_mcmc_chain(chain, verbose=False, burnin=False)[source]

Draw samples from the mcmc chains posteriors by redrawing each one of them against the Metropolis-Hastings rule

cpnest.nest2pos.uniform(low=0.0, high=1.0, size=None)

Draw samples from a uniform distribution.

Samples are uniformly distributed over the half-open interval [low, high) (includes low, but excludes high). In other words, any value within the given interval is equally likely to be drawn by uniform.

Note

New code should use the uniform method of a default_rng() instance instead; see random-quick-start.

Parameters
  • low (float or array_like of floats, optional) – Lower boundary of the output interval. All values generated will be greater than or equal to low. The default value is 0.

  • high (float or array_like of floats) – Upper boundary of the output interval. All values generated will be less than or equal to high. The default value is 1.0.

  • size (int or tuple of ints, optional) – Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. If size is None (default), a single value is returned if low and high are both scalars. Otherwise, np.broadcast(low, high).size samples are drawn.

Returns

out – Drawn samples from the parameterized uniform distribution.

Return type

ndarray or scalar

See also

randint

Discrete uniform distribution, yielding integers.

random_integers

Discrete uniform distribution over the closed interval [low, high].

random_sample

Floats uniformly distributed over [0, 1).

random

Alias for random_sample.

rand

Convenience function that accepts dimensions as input, e.g., rand(2,2) would generate a 2-by-2 array of floats, uniformly distributed over [0, 1).

Generator.uniform

which should be used for new code.

Notes

The probability density function of the uniform distribution is

\[p(x) = \frac{1}{b - a}\]

anywhere within the interval [a, b), and zero elsewhere.

When high == low, values of low will be returned. If high < low, the results are officially undefined and may eventually raise an error, i.e. do not rely on this function to behave when passed arguments satisfying that inequality condition. The high limit may be included in the returned array of floats due to floating-point rounding in the equation low + (high-low) * random_sample(). For example:

>>> x = np.float32(5*0.99999999)
>>> x
5.0

Examples

Draw samples from the distribution:

>>> s = np.random.uniform(-1,0,1000)

All values are within the given interval:

>>> np.all(s >= -1)
True
>>> np.all(s < 0)
True

Display the histogram of the samples, along with the probability density function:

>>> import matplotlib.pyplot as plt
>>> count, bins, ignored = plt.hist(s, 15, density=True)
>>> plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
>>> plt.show()

cpnest.parameter module

class cpnest.parameter.LivePoint

Bases: object

Class defining a live point. Initialisation arguments: names: names of parameters d: (optional) an array for initialisation logL: (optional) log likelihood of this sample logP: (optional) log prior of this sample

asnparray()

Return the sample as a numpy record array

bounds
copy()

Returns a copy of the current live point

dimension
keys()
logL
logP
names
values
cpnest.parameter.rebuild_livepoint()

cpnest.plot module

cpnest.plot.init_plotting()[source]
cpnest.plot.plot_chain(x, name=None, filename=None)[source]

Produce a trace plot

cpnest.plot.plot_corner(xs, ps=None, ms=None, filename=None, **kwargs)[source]

Produce a corner plot

cpnest.plot.plot_hist(x, name=None, prior_samples=None, mcmc_samples=None, filename=None)[source]

Produce a histogram

cpnest.proposal module

class cpnest.proposal.ConstrainedLeapFrog(model=None, **kwargs)[source]

Bases: cpnest.proposal.LeapFrog

Leap frog integrator proposal for a costrained (logLmin defines a reflective boundary) Hamiltonian Monte Carlo step.

check_constraint(q, logLmin)[source]

Check the likelihood

Parameters
Returns

c

Return type

numpy.float64 value of the constraint

counter()[source]
evolve_trajectory(p0, q0, logLmin)[source]

Evolve point according to Hamiltonian method in https://arxiv.org/pdf/1005.0157.pdf

Parameters
Returns

evolve_trajectory_one_step_momentum(p, q, logLmin, half=False)[source]

One leap frog step in momentum

Parameters
Returns

evolve_trajectory_one_step_position(p, q)[source]

One leap frog step in position

Parameters
Returns

get_sample(q0, logLmin=- inf)[source]

Generate new sample with constrained HMC, starting at q0.

Parameters
Returns

q – position

Return type

cpnest.parameter.LivePoint

sample_trajectory(trajectory)[source]
save_trajectory(trajectory, logLmin, filename=None)[source]

save trajectory for diagnostic purposes

class cpnest.proposal.DefaultProposalCycle[source]

Bases: cpnest.proposal.ProposalCycle

A default proposal cycle that uses the cpnest.proposal.EnsembleWalk, cpnest.proposal.EnsembleStretch, cpnest.proposal.DifferentialEvolution, cpnest.proposal.EnsembleEigenVector ensemble proposals.

class cpnest.proposal.DifferentialEvolution[source]

Bases: cpnest.proposal.EnsembleProposal

Differential evolution move: Draws a step by taking the difference vector between two points in the ensemble and adding it to the current point. See e.g. Exercise 30.12, p.398 in MacKay’s book http://www.inference.phy.cam.ac.uk/mackay/itila/

We add a small perturbation around the exact step

get_sample(old)[source]
Parameters

old (cpnest.parameter.LivePoint) –

Returns

out

Return type

cpnest.parameter.LivePoint

log_J = 0.0
class cpnest.proposal.EnsembleEigenVector[source]

Bases: cpnest.proposal.EnsembleProposal

A jump along a randomly-chosen eigenvector of the covariance matrix of the ensemble

covariance = None
eigen_values = None
eigen_vectors = None
get_sample(old)[source]

Propose a jump along a random eigenvector :param old: :type old: cpnest.parameter.LivePoint

Returns

out

Return type

cpnest.parameter.LivePoint

log_J = 0.0
set_ensemble(ensemble)[source]

Over-ride default set_ensemble so that the eigenvectors are recomputed when it is updated

update_eigenvectors()[source]

Recompute the eigenvectors and eigevalues of the covariance matrix of the ensemble

class cpnest.proposal.EnsembleProposal[source]

Bases: cpnest.proposal.Proposal

Base class for ensemble proposals

ensemble = None
set_ensemble(ensemble)[source]

Set the ensemble of points to use

class cpnest.proposal.EnsembleSlice[source]

Bases: cpnest.proposal.EnsembleProposal

The Ensemble Slice proposal from Karamanis & Beutler https://arxiv.org/pdf/2002.06212v1.pdf

log_J = 0.0
class cpnest.proposal.EnsembleSliceCorrelatedGaussian[source]

Bases: cpnest.proposal.EnsembleSlice

The Ensemble Slice Correlated Gaussian move from Karamanis & Beutler https://arxiv.org/pdf/2002.06212v1.pdf

covariance = None
get_direction(mu=1.0)[source]

Draws a random gaussian direction

mean = None
set_ensemble(ensemble)[source]

Over-ride default set_ensemble so that the mean and covariance matrix are recomputed when it is updated

update_mean_covariance()[source]

Recompute mean and covariance matrix of the ensemble

class cpnest.proposal.EnsembleSliceDifferential[source]

Bases: cpnest.proposal.EnsembleSlice

The Ensemble Slice Differential move from Karamanis & Beutler https://arxiv.org/pdf/2002.06212v1.pdf

get_direction(mu=1.0)[source]

Draws two random points and returns their direction

class cpnest.proposal.EnsembleSliceGaussian[source]

Bases: cpnest.proposal.EnsembleSlice

The Ensemble Slice Gaussian move from Karamanis & Beutler https://arxiv.org/pdf/2002.06212v1.pdf

get_direction(mu=1.0)[source]

Draw a random gaussian direction

class cpnest.proposal.EnsembleSliceProposalCycle(model=None)[source]

Bases: cpnest.proposal.ProposalCycle

get_direction(mu=1.0, **kwargs)[source]

Get a direction for the slice jump

class cpnest.proposal.EnsembleStretch[source]

Bases: cpnest.proposal.EnsembleProposal

The Ensemble “stretch” move from Goodman & Weare http://dx.doi.org/10.2140/camcos.2010.5.65

get_sample(old)[source]
Parameters

old (cpnest.parameter.LivePoint) –

Returns

out

Return type

cpnest.parameter.LivePoint

class cpnest.proposal.EnsembleWalk[source]

Bases: cpnest.proposal.EnsembleProposal

The Ensemble “walk” move from Goodman & Weare http://dx.doi.org/10.2140/camcos.2010.5.65

Draws a step by evolving along the direction of the center of mass of 3 points in the ensemble.

Npoints = 3
get_sample(old)[source]
Parameters

old (cpnest.parameter.LivePoint) –

Returns

out

Return type

cpnest.parameter.LivePoint

log_J = 0.0
class cpnest.proposal.HamiltonianProposal(model=None, **kwargs)[source]

Bases: cpnest.proposal.EnsembleEigenVector

Base class for hamiltonian proposals

gradient(q)[source]

return the gradient of the potential function as numpy ndarray :param q: position :type q: cpnest.parameter.LivePoint

Returns

dV

Return type

numpy.ndarray gradient evaluated at q

hamiltonian(p, q)[source]

Hamiltonian. :param p: momentum :type p: numpy.ndarray :param q: position :type q: cpnest.parameter.LivePoint

Returns

H

Return type

float

hamiltonian

inverse_mass_matrix = None
kinetic_energy(p)[source]

kinetic energy part for the Hamiltonian. :param p: momentum :type p: numpy.ndarray

Returns

T

Return type

float

kinetic energy

mass_matrix = None
momenta_distribution = None
set_ensemble(ensemble)[source]

override the set ensemble method to update masses, momenta distribution and to heuristically estimate the normal vector to the hard boundary defined by logLmin.

set_integration_parameters()[source]

Set the integration length according to the N-dimensional ellipsoid shortest and longest principal axes. The former sets to base time step while the latter sets the trajectory length

unit_normal(q)[source]

Returns the unit normal to the iso-Likelihood surface at x, obtained from the spline interpolation of the directional derivatives of the likelihood :param q: position :type q: cpnest.parameter.LivePoint

Returns

n

Return type

numpy.ndarray unit normal to the logLmin contour evaluated at q

update_mass()[source]

Update the mass matrix (covariance matrix) and inverse mass matrix (precision matrix) from the ensemble, allowing for correlated momenta

update_momenta_distribution()[source]

update the momenta distribution using the mass matrix (precision matrix of the ensemble).

update_normal_vector()[source]

update the constraint by approximating the loglikelihood hypersurface as a spline in each dimension. This is an approximation which improves as the algorithm proceeds

update_time_step(acceptance)[source]

Update the time step according to the acceptance rate :param acceptance: :type acceptance: :obj:’numpy.float’

update_trajectory_length(nmcmc)[source]

Update the trajectory length according to the estimated ACL :param nmcmc: :type nmcmc: obj:: int

class cpnest.proposal.HamiltonianProposalCycle(model=None)[source]

Bases: cpnest.proposal.ProposalCycle

class cpnest.proposal.LeapFrog(model=None, **kwargs)[source]

Bases: cpnest.proposal.HamiltonianProposal

Leap frog integrator proposal for an unconstrained Hamiltonian Monte Carlo step

evolve_trajectory(p0, q0, *args)[source]

Hamiltonian leap frog trajectory subject to the hard boundary defined by the parameters prior bounds. https://arxiv.org/pdf/1206.1901.pdf

Parameters
Returns

get_sample(q0, *args)[source]

Propose a new sample, starting at q0

Parameters

q0 (cpnest.parameter.LivePoint) – position

Returns

q – position

Return type

cpnest.parameter.LivePoint

class cpnest.proposal.Proposal[source]

Bases: object

Base abstract class for jump proposals

abstract get_sample(old)[source]

Returns a new proposed sample given the old one. Must be implemented by user

Parameters

old (cpnest.parameter.LivePoint) –

Returns

out

Return type

cpnest.parameter.LivePoint

log_J = 0.0
class cpnest.proposal.ProposalCycle(proposals, weights, cyclelength=100, *args, **kwargs)[source]

Bases: cpnest.proposal.EnsembleProposal

A proposal that cycles through a list of jumps.

Initialisation arguments:

proposals : A list of jump proposals weights : Weights for each type of jump

Optional arguments: cyclelength : length of the proposal cycle. Default: 100

N = 0
add_proposal(proposal, weight)[source]
get_sample(old, **kwargs)[source]

Returns a new proposed sample given the old one. Must be implemented by user

Parameters

old (cpnest.parameter.LivePoint) –

Returns

out

Return type

cpnest.parameter.LivePoint

idx = 0
normalise_weights(weights)[source]
set_cycle()[source]
set_ensemble(ensemble)[source]

Updates the ensemble statistics by calling it on each EnsembleProposal

property weights

cpnest.sampler module

class cpnest.sampler.HamiltonianMonteCarloSampler(model, maxmcmc, seed=None, output=None, verbose=False, sample_prior=False, poolsize=1000, proposal=None, resume_file=None, manager=None)[source]

Bases: cpnest.sampler.Sampler

HamiltonianMonteCarlo acceptance rule for cpnest.proposal.HamiltonianProposal

insert_sample(p)[source]
yield_sample(logLmin)[source]
class cpnest.sampler.MetropolisHastingsSampler(model, maxmcmc, seed=None, output=None, verbose=False, sample_prior=False, poolsize=1000, proposal=None, resume_file=None, manager=None)[source]

Bases: cpnest.sampler.Sampler

metropolis-hastings acceptance rule for cpnest.proposal.EnembleProposal

yield_sample(logLmin)[source]
class cpnest.sampler.Sampler(model, maxmcmc, seed=None, output=None, verbose=False, sample_prior=False, poolsize=1000, proposal=None, resume_file=None, manager=None)[source]

Bases: object

Initialisation arguments:

args: model: cpnest.Model user defined model to sample

maxmcmc:
int

maximum number of mcmc steps to be used in the cnest.sampler.Sampler

kwargs:

verbose:
int

display debug information on screen

Default: 0

poolsize:
int

number of objects for the affine invariant sampling

Default: 1000

seed:
int

random seed to initialise the pseudo-random chain

Default: None

proposal:

cpnest.proposals.Proposal to use Defaults: cpnest.proposals.DefaultProposalCycle)

resume_file:

File for checkpointing Default: None

manager:

multiprocessing.Manager hosting all communication objects Default: None

checkpoint()[source]

Checkpoint its internal state

estimate_nmcmc(safety=20)[source]

Estimate autocorrelation length of the chain

estimate_nmcmc_on_the_fly(safety=5, tau=None)[source]

Estimate autocorrelation length of chain using acceptance fraction ACL = (2/acc) - 1 multiplied by a safety margin of 5 Uses moving average with decay time tau iterations (default: :int:`self.poolsize`)

Taken from http://github.com/farr/Ensemble.jl

produce_sample()[source]
reset()[source]

Initialise the sampler by generating :int:`poolsize` cpnest.parameter.LivePoint and distributing them according to cpnest.model.Model.log_prior

classmethod resume(resume_file, manager, model)[source]

Resumes the interrupted state from a checkpoint pickle file.

class cpnest.sampler.SliceSampler(model, maxmcmc, seed=None, output=None, verbose=False, sample_prior=False, poolsize=1000, proposal=None, resume_file=None, manager=None)[source]

Bases: cpnest.sampler.Sampler

The Ensemble Slice sampler from Karamanis & Beutler https://arxiv.org/pdf/2002.06212v1.pdf

adapt_length_scale()[source]

adapts the length scale of the expansion/contraction following the rule in (Robbins and Monro, 1951) of Tibbits et al. (2014)

increase_left_boundary()[source]

increase the left boundary and counts by one unit

increase_right_boundary()[source]

increase the right boundary and counts by one unit

reset()[source]

Initialise the sampler by generating :int:`poolsize` cpnest.parameter.LivePoint

reset_boundaries()[source]

resets the boundaries and counts for the slicing

yield_sample(logLmin)[source]
cpnest.sampler.random()x in the interval [0, 1).

cpnest.utils module

class cpnest.utils.FileHandler(filename, verbose=0, **kwargs)[source]

Bases: cpnest.utils._Handler, logging.FileHandler

class cpnest.utils.LogFile(filename, verbose=0, loggername='cpnest')[source]

Bases: object

Context manager for file logging. It logs everything from logger in some file at a given filename.

Parameters
  • filename (str) – Filename under which to save the log.

  • verbose (int, optional) – Logging level verbosity 0=’CRITICAL’ 1=’WARNING’ 2=’INFO’ 3=’DEBUG’.

  • loggername (str, optional) – Name of the logger to send to file at path. Default is ‘cpnest’ so all cpnest logs are recorded. E.g. specify ‘cpnest.cpnest’ to only record logs from the cpnest.py module.

handler

File handler object.

Type

logging.FileHandler

Examples

```python from cpnest.utils import LogFile

with LogFile(‘example.log’) as flog:

# Do some stuff here and it will be logged to ‘example.log’ …

# Do some stuff here and it won’t be logged to ‘example.log’

with flog:

# Do some stuff here and it will be logged to ‘example.log’ …

```

close()[source]
open()[source]
class cpnest.utils.StreamHandler(verbose=0, **kwargs)[source]

Bases: cpnest.utils._Handler, logging.StreamHandler

Module contents