Skip to content
Open
Show file tree
Hide file tree
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
3 changes: 2 additions & 1 deletion cosmosis/getdist.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from . import table as cosmosis_table
from . import postprocessing
from .runtime import Inifile
from . import utils


def cosmosis_to_getdist(filename, name, burn=0, nchain=0):
Expand Down Expand Up @@ -90,7 +91,7 @@ def _extract_getdist_inputs(table, latex_names):
if "weight" in table.colnames:
weights = table["weight"]
elif "log_weight" in table.colnames:
weights = np.exp(table["log_weight"] - np.max(table["log_weight"]))
weights = utils.normalized_log_weights(table["log_weight"])
else:
weights = None

Expand Down
4 changes: 2 additions & 2 deletions cosmosis/postprocessing/postprocess.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,8 @@ def weight_col(self):
old_logw = MetropolisHastingsProcessor.reduced_col(self, "old_log_weight").copy()
logw += old_logw
print("Including old_log_weight in weight")
logw-=np.nanmax(logw)
self._weight_col = np.exp(logw)
from .. import utils
self._weight_col = utils.normalized_log_weights(logw)
return self._weight_col

def posterior_sample(self):
Expand Down
5 changes: 3 additions & 2 deletions cosmosis/samplers/hints.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import numpy as np
from .. import utils

class Hints(object):
def __init__(self):
Expand All @@ -12,7 +13,7 @@ def set_from_sample(self, samples, posts, weights=None, log_weights=None):
if log_weights is not None:
if weights is not None:
raise ValueError("You must provide either weights or log_weights, not both")
weights = np.exp(log_weights - log_weights.max())
weights = utils.normalized_log_weights(log_weights)
self.set_cov(np.cov(samples.T, aweights=weights))

def has_peak(self):
Expand Down Expand Up @@ -44,4 +45,4 @@ def update(self, other):
if other.has_peak():
self.set_peak(other.get_peak(), other._peak_post)
if other.has_cov():
self.set_cov(other.get_cov())
self.set_cov(other.get_cov())
3 changes: 2 additions & 1 deletion cosmosis/samplers/sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,8 @@ def start_estimate(self, method=None, input_source=None, prefer_random=False, qu
weight = data[:, weight_index]
elif 'log_weight' in maybe_colnames:
log_weight_index = maybe_colnames.index('log_weight')
weight = np.exp(data[:, log_weight_index] - data[:, log_weight_index].max())
from .. import utils
weight = utils.normalized_log_weights(data[:, log_weight_index])
else:
weight = np.ones(len(data))
weight /= weight.sum()
Expand Down
13 changes: 13 additions & 0 deletions cosmosis/test/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,17 @@
import cosmosis.utils
import numpy as np
import pytest


def test_normalized_log_weights_handles_zero_weight_samples():
weights = cosmosis.utils.normalized_log_weights(np.array([-np.inf, 0.0, -2.0]))
np.testing.assert_allclose(weights, [0.0, 1.0, np.exp(-2.0)])


@pytest.mark.parametrize("log_weights", [np.array([]), np.array([np.nan, 0.0]), np.array([-np.inf, -np.inf])])
def test_normalized_log_weights_rejects_invalid_inputs(log_weights):
with pytest.raises(ValueError):
cosmosis.utils.normalized_log_weights(log_weights)
import tempfile
import os
import contextlib
Expand Down
21 changes: 21 additions & 0 deletions cosmosis/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,27 @@ def symmetric_positive_definite_inverse(M):
M = symmetrized_matrix(M)
return M


def normalized_log_weights(log_weights):
"""Convert log-weights to finite, max-scaled weights.

``-inf`` is allowed for samples with zero weight, but NaN, positive
infinity, empty input, and an all-zero result are rejected explicitly.
"""
log_weights = np.asarray(log_weights, dtype=float)
if log_weights.ndim != 1 or log_weights.size == 0:
raise ValueError("log weights must be a non-empty one-dimensional array")
if np.any(np.isnan(log_weights)) or np.any(np.isposinf(log_weights)):
raise ValueError("log weights must not contain NaN or positive infinity")
finite = np.isfinite(log_weights)
if not np.any(finite):
raise ValueError("at least one log weight must be finite")
weights = np.exp(log_weights - np.max(log_weights[finite]))
total = weights.sum()
if not np.isfinite(total) or total <= 0:
raise ValueError("normalized weights must have a positive finite sum")
return weights

# These parts from:
# https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python

Expand Down
Loading