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)
-
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
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
-
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
-
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
-
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
- usermodel:
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
- Return type
point
-
in_bounds
(param)[source]¶ Checks whether param lies within the bounds
- Parameters
param –
cpnest.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
= []¶
-
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:
param:
cpnest.parameter.LivePoint
- 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 adefault_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)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned iflow
andhigh
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 oflow
will be returned. Ifhigh
<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. Thehigh
limit may be included in the returned array of floats due to floating-point rounding in the equationlow + (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.
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 adefault_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)
, thenm * n * k
samples are drawn. If size isNone
(default), a single value is returned iflow
andhigh
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 oflow
will be returned. Ifhigh
<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. Thehigh
limit may be included in the returned array of floats due to floating-point rounding in the equationlow + (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.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
q0 (
cpnest.parameter.LivePoint
) –position –
logLmin (
numpy.float64
) –constraint (loglikelihood) –
- Returns
c
- Return type
numpy.float64
value of the constraint
-
evolve_trajectory
(p0, q0, logLmin)[source]¶ Evolve point according to Hamiltonian method in https://arxiv.org/pdf/1005.0157.pdf
- Parameters
p0 (
numpy.ndarray
) – momentumq0 (
cpnest.parameter.LivePoint
) – position
- Returns
p (
numpy.ndarray
updated momentum vector)q (
cpnest.parameter.LivePoint
position)
-
evolve_trajectory_one_step_momentum
(p, q, logLmin, half=False)[source]¶ One leap frog step in momentum
- Parameters
p0 (
numpy.ndarray
) – momentumq0 (
cpnest.parameter.LivePoint
) – positionlogLmin (
numpy.float64
) – loglikelihood constraint
- Returns
p (
numpy.ndarray
updated momentum vector)q (
cpnest.parameter.LivePoint
position)
-
evolve_trajectory_one_step_position
(p, q)[source]¶ One leap frog step in position
- Parameters
p0 (
numpy.ndarray
) – momentumq0 (
cpnest.parameter.LivePoint
) – position
- Returns
p (
numpy.ndarray
updated momentum vector)q (
cpnest.parameter.LivePoint
position)
-
get_sample
(q0, logLmin=- inf)[source]¶ Generate new sample with constrained HMC, starting at q0.
- Parameters
q0 (
cpnest.parameter.LivePoint
) – positionlogLmin (hard likelihood boundary) –
- Returns
q – position
- Return type
-
-
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
-
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
-
log_J
= 0.0¶
-
-
class
cpnest.proposal.
EnsembleProposal
[source]¶ Bases:
cpnest.proposal.Proposal
Base class for ensemble proposals
-
ensemble
= None¶
-
-
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¶
-
Bases:
cpnest.proposal.EnsembleSlice
The Ensemble Slice Correlated Gaussian move from Karamanis & Beutler https://arxiv.org/pdf/2002.06212v1.pdf
Draws a random gaussian direction
Over-ride default set_ensemble so that the mean and covariance matrix are recomputed when it is updated
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
-
class
cpnest.proposal.
EnsembleSliceGaussian
[source]¶ Bases:
cpnest.proposal.EnsembleSlice
The Ensemble Slice Gaussian move from Karamanis & Beutler https://arxiv.org/pdf/2002.06212v1.pdf
-
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
-
-
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
-
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
-
-
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
p0 (
numpy.ndarray
) – momentumq0 (
cpnest.parameter.LivePoint
) – position
- Returns
p (
numpy.ndarray
updated momentum vector)q (
cpnest.parameter.LivePoint
) – position
-
get_sample
(q0, *args)[source]¶ Propose a new sample, starting at q0
- Parameters
q0 (
cpnest.parameter.LivePoint
) – position- Returns
q – position
- Return type
-
-
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
-
log_J
= 0.0¶
-
abstract
-
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¶
-
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
-
idx
= 0¶
-
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
-
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
-
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
-
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
-
reset
()[source]¶ Initialise the sampler by generating :int:`poolsize` cpnest.parameter.LivePoint and distributing them according to
cpnest.model.Model.log_prior
-
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)
-
reset
()[source]¶ Initialise the sampler by generating :int:`poolsize` cpnest.parameter.LivePoint
-
-
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
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’ …
-
class
cpnest.utils.
StreamHandler
(verbose=0, **kwargs)[source]¶ Bases:
cpnest.utils._Handler
,logging.StreamHandler