Skip to content
This repository has been archived by the owner on Apr 11, 2023. It is now read-only.

Add vectorize option for Numpy arraywise evaluation of like/prior #6

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 25 additions & 10 deletions ptemcee/sampler.py
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -128,19 +128,22 @@ def __init__(self, logl, logp,
self.logpkwargs = logpkwargs

def __call__(self, x):
s = x.shape
x = x.reshape((-1, x.shape[-1]))

lp = self.logp(x, *self.logpargs, **self.logpkwargs)
if np.isnan(lp):
if np.any(np.isnan(lp)):
raise ValueError('Prior function returned NaN.')

if lp == float('-inf'):
# Can't return -inf, since this messes with beta=0 behaviour.
ll = 0
else:
ll = self.logl(x, *self.loglargs, **self.loglkwargs)
if np.isnan(ll).any():
raise ValueError('Log likelihood function returned NaN.')
# Can't return -inf, since this messes with beta=0 behaviour.
ll = np.empty_like(lp)
bad = (lp == -np.inf)
ll[bad] = 0
ll[~bad] = self.logl(x[~bad], *self.loglargs, **self.loglkwargs)
if np.any(np.isnan(ll)):
raise ValueError('Log likelihood function returned NaN.')

return ll, lp
return ll.reshape(s[:-1]), lp.reshape(s[:-1])

class Sampler(object):
"""
Expand Down Expand Up @@ -198,14 +201,23 @@ class Sampler(object):
:param adaptation_time: (optional)
Time-scale for temperature dynamics. Default: 100.

:param vectorize: (optional)
If ``True``, ``logl`` and ``logp`` are expected to accept a list of
position vectors instead of just one. Note that ``pool`` will be
ignored if this is ``True``. (default: ``False``)

"""
def __init__(self, nwalkers, dim, logl, logp,
ntemps=None, Tmax=None, betas=None,
threads=1, pool=None, a=2.0,
loglargs=[], logpargs=[],
loglkwargs={}, logpkwargs={},
adaptation_lag=10000, adaptation_time=100,
random=None):
random=None, vectorize=False):
self._vectorize = vectorize
if vectorize:
pool = None

if random is None:
self._random = np.random.mtrand.RandomState()
else:
Expand Down Expand Up @@ -447,6 +459,9 @@ def _stretch(self, p, logpost, logl):
self.nprop_accepted[:, jupdate::2] += accepts

def _evaluate(self, ps):
if self._vectorize:
return self._likeprior(ps)

mapf = map if self.pool is None else self.pool.map
results = list(mapf(self._likeprior, ps.reshape((-1, self.dim))))

Expand Down