Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • john-veitch/bilby
  • duncanmmacleod/bilby
  • colm.talbot/bilby
  • lscsoft/bilby
  • matthew-pitkin/bilby
  • salvatore-vitale/tupak
  • charlie.hoy/bilby
  • bfarr/bilby
  • virginia.demilio/bilby
  • vivien/bilby
  • eric-howell/bilby
  • sebastian-khan/bilby
  • rhys.green/bilby
  • moritz.huebner/bilby
  • joseph.mills/bilby
  • scott.coughlin/bilby
  • matthew.carney/bilby
  • hyungwon.lee/bilby
  • monica.rizzo/bilby
  • christopher-berry/bilby
  • lindsay.demarchi/bilby
  • kaushik.rao/bilby
  • charles.kimball/bilby
  • andrew.matas/bilby
  • juan.calderonbustillo/bilby
  • patrick-meyers/bilby
  • hannah.middleton/bilby
  • eve.chase/bilby
  • grant.meadors/bilby
  • khun.phukon/bilby
  • sumeet.kulkarni/bilby
  • daniel.reardon/bilby
  • cjhaster/bilby
  • sylvia.biscoveanu/bilby
  • james-clark/bilby
  • meg.millhouse/bilby
  • joshua.willis/bilby
  • nikhil.sarin/bilby
  • paul.easter/bilby
  • youngmin/bilby
  • daniel-williams/bilby
  • shanika.galaudage/bilby
  • bruce.edelman/bilby
  • avi.vajpeyi/bilby
  • isobel.romero-shaw/bilby
  • andrew.kim/bilby
  • dominika.zieba/bilby
  • jonathan.davies/bilby
  • marc.arene/bilby
  • srishti.tiwari/bilby-tidal-heating-eccentric
  • aditya.vijaykumar/bilby
  • michael.williams/bilby
  • cecilio.garcia-quiros/bilby
  • rory-smith/bilby
  • maite.mateu-lucena/bilby
  • wushichao/bilby
  • kaylee.desoto/bilby
  • brandon.piotrzkowski/bilby
  • rossella.gamba/bilby
  • hunter.gabbard/bilby
  • deep.chatterjee/bilby
  • tathagata.ghosh/bilby
  • arunava.mukherjee/bilby
  • philip.relton/bilby
  • reed.essick/bilby
  • pawan.gupta/bilby
  • francisco.hernandez/bilby
  • rhiannon.udall/bilby
  • leo.tsukada/bilby
  • will-farr/bilby
  • vijay.varma/bilby
  • jeremy.baier/bilby
  • joshua.brandt/bilby
  • ethan.payne/bilby
  • ka-lok.lo/bilby
  • antoni.ramos-buades/bilby
  • oliviastephany.wilk/bilby
  • jack.heinzel/bilby
  • samson.leong/bilby-psi4
  • viviana.caceres/bilby
  • nadia.qutob/bilby
  • michael-coughlin/bilby
  • hemantakumar.phurailatpam/bilby
  • boris.goncharov/bilby
  • sama.al-shammari/bilby
  • siqi.zhong/bilby
  • jocelyn-read/bilby
  • marc.penuliar/bilby
  • stephanie.letourneau/bilby
  • alexandresebastien.goettel/bilby
  • alec.gunny/bilby
  • serguei.ossokine/bilby
  • pratyusava.baral/bilby
  • sophie.hourihane/bilby
  • eunsub/bilby
  • james.hart/bilby
  • pratyusava.baral/bilby-tg
  • zhaozc/bilby
  • pratyusava.baral/bilby_SoG
  • tomasz.baka/bilby
  • nicogerardo.bers/bilby
  • soumen.roy/bilby
  • isaac.mcmahon/healpix-redundancy
  • asamakai.baker/bilby-frequency-dependent-antenna-pattern-functions
  • anna.puecher/bilby
  • pratyusava.baral/bilby-x-g
  • thibeau.wouters/bilby
  • christian.adamcewicz/bilby
  • raffi.enficiaud/bilby
109 results
Show changes
Showing
with 195 additions and 187 deletions
......@@ -181,25 +181,39 @@ class CubicSpline(Recalibrate):
self.maximum_frequency = maximum_frequency
self._log_spline_points = np.linspace(
np.log10(minimum_frequency), np.log10(maximum_frequency), n_points)
self._delta_log_spline_points = self._log_spline_points[1] - self._log_spline_points[0]
# Precompute matrix converting values at nodes to spline coefficients.
# The algorithm for interpolation is described in
# https://dcc.ligo.org/LIGO-T2300140, and the matrix calculated here is
# to solve Eq. (9) in the note.
tmp1 = np.zeros(shape=(n_points, n_points))
@property
def delta_log_spline_points(self):
if not hasattr(self, "_delta_log_spline_points"):
self._delta_log_spline_points = self._log_spline_points[1] - self._log_spline_points[0]
return self._delta_log_spline_points
@property
def nodes_to_spline_coefficients(self):
if not hasattr(self, "_nodes_to_spline_coefficients"):
self._setup_spline_coefficients()
return self._nodes_to_spline_coefficients
def _setup_spline_coefficients(self):
"""
Precompute matrix converting values at nodes to spline coefficients.
The algorithm for interpolation is described in
https://dcc.ligo.org/LIGO-T2300140, and the matrix calculated here is
to solve Eq. (9) in the note.
"""
tmp1 = np.zeros(shape=(self.n_points, self.n_points))
tmp1[0, 0] = -1
tmp1[0, 1] = 2
tmp1[0, 2] = -1
tmp1[-1, -3] = -1
tmp1[-1, -2] = 2
tmp1[-1, -1] = -1
for i in range(1, n_points - 1):
for i in range(1, self.n_points - 1):
tmp1[i, i - 1] = 1 / 6
tmp1[i, i] = 2 / 3
tmp1[i, i + 1] = 1 / 6
tmp2 = np.zeros(shape=(n_points, n_points))
for i in range(1, n_points - 1):
tmp2 = np.zeros(shape=(self.n_points, self.n_points))
for i in range(1, self.n_points - 1):
tmp2[i, i - 1] = 1
tmp2[i, i] = -2
tmp2[i, i + 1] = 1
......@@ -213,6 +227,18 @@ class CubicSpline(Recalibrate):
return self.__class__.__name__ + '(prefix=\'{}\', minimum_frequency={}, maximum_frequency={}, n_points={})'\
.format(self.prefix, self.minimum_frequency, self.maximum_frequency, self.n_points)
def _evaluate_spline(self, kind, a, b, c, d, previous_nodes):
"""Evaluate Eq. (1) in https://dcc.ligo.org/LIGO-T2300140"""
parameters = np.array([self.params[f"{kind}_{ii}"] for ii in range(self.n_points)])
next_nodes = previous_nodes + 1
spline_coefficients = self.nodes_to_spline_coefficients.dot(parameters)
return (
a * parameters[previous_nodes]
+ b * parameters[next_nodes]
+ c * spline_coefficients[previous_nodes]
+ d * spline_coefficients[next_nodes]
)
def get_calibration_factor(self, frequency_array, **params):
"""Apply calibration model
......@@ -233,25 +259,17 @@ class CubicSpline(Recalibrate):
"""
log10f_per_deltalog10f = (
np.log10(frequency_array) - self.log_spline_points[0]
) / self._delta_log_spline_points
) / self.delta_log_spline_points
previous_nodes = np.clip(np.floor(log10f_per_deltalog10f).astype(int), a_min=0, a_max=self.n_points - 2)
next_nodes = previous_nodes + 1
b = log10f_per_deltalog10f - previous_nodes
a = 1 - b
c = (a**3 - a) / 6
d = (b**3 - b) / 6
self.set_calibration_parameters(**params)
amplitude_parameters = np.array([self.params['amplitude_{}'.format(ii)] for ii in range(self.n_points)])
_spline_coefficients = self._nodes_to_spline_coefficients.dot(amplitude_parameters)
delta_amplitude = a * amplitude_parameters[previous_nodes] + b * amplitude_parameters[next_nodes] + \
c * _spline_coefficients[previous_nodes] + d * _spline_coefficients[next_nodes]
phase_parameters = np.array([self.params['phase_{}'.format(ii)] for ii in range(self.n_points)])
_spline_coefficients = self._nodes_to_spline_coefficients.dot(phase_parameters)
delta_phase = a * phase_parameters[previous_nodes] + b * phase_parameters[next_nodes] + \
c * _spline_coefficients[previous_nodes] + d * _spline_coefficients[next_nodes]
delta_amplitude = self._evaluate_spline("amplitude", a, b, c, d, previous_nodes)
delta_phase = self._evaluate_spline("phase", a, b, c, d, previous_nodes)
calibration_factor = (1 + delta_amplitude) * (2 + 1j * delta_phase) / (2 - 1j * delta_phase)
return calibration_factor
......
......@@ -521,6 +521,8 @@ class GravitationalWaveTransient(Likelihood):
new_calibration: dict
Sample set from the calibration posterior
"""
from ...core.utils.random import rng
if 'recalib_index' in self.parameters:
self.parameters.pop('recalib_index')
self.parameters.update(self.get_sky_frame_parameters())
......@@ -533,7 +535,7 @@ class GravitationalWaveTransient(Likelihood):
calibration_post = np.exp(log_like - max(log_like))
calibration_post /= np.sum(calibration_post)
new_calibration = np.random.choice(self.number_of_response_curves, p=calibration_post)
new_calibration = rng.choice(self.number_of_response_curves, p=calibration_post)
return new_calibration
......
......@@ -736,7 +736,7 @@ class MBGravitationalWaveTransient(GravitationalWaveTransient):
strain *= np.exp(-1j * 2. * np.pi * self.banded_frequency_points * ifo_time)
strain *= calib_factor
d_inner_h = np.dot(strain, self.linear_coeffs[interferometer.name])
d_inner_h = np.conj(np.dot(strain, self.linear_coeffs[interferometer.name]))
if self.linear_interpolation:
optimal_snr_squared = np.vdot(
......
......@@ -1151,6 +1151,8 @@ class ROQGravitationalWaveTransient(GravitationalWaveTransient):
signal[kind][mode] *= self._ref_dist / new_distance
def generate_time_sample_from_marginalized_likelihood(self, signal_polarizations=None):
from ...core.utils.random import rng
self.parameters.update(self.get_sky_frame_parameters())
if signal_polarizations is None:
signal_polarizations = \
......@@ -1180,7 +1182,7 @@ class ROQGravitationalWaveTransient(GravitationalWaveTransient):
time_prior_array = self.priors['geocent_time'].prob(times)
time_post = np.exp(time_log_like - max(time_log_like)) * time_prior_array
time_post /= np.sum(time_post)
return np.random.choice(times, p=time_post)
return rng.choice(times, p=time_post)
class BilbyROQParamsRangeError(Exception):
......
......@@ -12,7 +12,7 @@ from ..core.prior import (
ConditionalPriorDict, ConditionalBasePrior, BaseJointPriorDist, JointPrior,
JointPriorDistError,
)
from ..core.utils import infer_args_from_method, logger
from ..core.utils import infer_args_from_method, logger, random
from .conversion import (
convert_to_lal_binary_black_hole_parameters,
convert_to_lal_binary_neutron_star_parameters, generate_mass_parameters,
......@@ -292,20 +292,15 @@ class Cosmological(Interped):
else:
return cls._from_repr(string)
@property
def _repr_dict(self):
"""
Get a dictionary containing the arguments needed to reproduce this object.
"""
from astropy.cosmology.core import Cosmology
def get_instantiation_dict(self):
from astropy import units
dict_with_properties = super(Cosmological, self)._repr_dict
if isinstance(dict_with_properties['cosmology'], Cosmology):
if dict_with_properties['cosmology'].name is not None:
dict_with_properties['cosmology'] = dict_with_properties['cosmology'].name
if isinstance(dict_with_properties['unit'], units.Unit):
dict_with_properties['unit'] = dict_with_properties['unit'].to_string()
return dict_with_properties
from astropy.cosmology.realizations import available
instantiation_dict = super().get_instantiation_dict()
if self.cosmology.name in available:
instantiation_dict['cosmology'] = self.cosmology.name
if isinstance(self.unit, units.Unit):
instantiation_dict['unit'] = self.unit.to_string()
return instantiation_dict
class UniformComovingVolume(Cosmological):
......@@ -1508,7 +1503,7 @@ class HealPixMapPriorDist(BaseJointPriorDist):
"""
pixel_choices = np.arange(self.npix)
pixel_probs = self._check_norm(self.prob)
sample_pix = np.random.choice(pixel_choices, size=size, p=pixel_probs, replace=True)
sample_pix = random.rng.choice(pixel_choices, size=size, p=pixel_probs, replace=True)
sample = np.empty((size, self.num_vars))
for samp in range(size):
theta, ra = self.hp.pix2ang(self.nside, sample_pix[samp])
......@@ -1540,7 +1535,7 @@ class HealPixMapPriorDist(BaseJointPriorDist):
"""
if self.distmu[pix] == np.inf or self.distmu[pix] <= 0:
return 0
dist = self.distance_icdf(np.random.uniform(0, 1))
dist = self.distance_icdf(random.rng.uniform(0, 1))
name = self.names[-1]
if (dist > self.bounds[name][1]) | (dist < self.bounds[name][0]):
self.draw_distance(pix)
......@@ -1569,8 +1564,8 @@ class HealPixMapPriorDist(BaseJointPriorDist):
self.draw_from_pixel(ra, dec, pix)
return np.array(
[
np.random.uniform(ra - self.pixel_length, ra + self.pixel_length),
np.random.uniform(dec - self.pixel_length, dec + self.pixel_length),
random.rng.uniform(ra - self.pixel_length, ra + self.pixel_length),
random.rng.uniform(dec - self.pixel_length, dec + self.pixel_length),
]
)
......
......@@ -9,7 +9,6 @@ between luminosity distances of 100Mpc and 5Gpc, the cosmology is Planck15.
"""
import bilby
import numpy as np
# Set the duration and sampling frequency of the data segment that we're
# going to inject the signal into
......@@ -23,7 +22,7 @@ label = "fast_tutorial"
bilby.core.utils.setup_logger(outdir=outdir, label=label)
# Set up a random seed for result reproducibility. This is optional!
np.random.seed(88170235)
bilby.core.utils.random.seed(88170235)
# We are going to inject a binary black hole waveform. We first establish a
# dictionary of parameters that includes all of the different waveform
......
......@@ -27,7 +27,7 @@ class MultiGaussian(bilby.Likelihood):
class TestGrid(unittest.TestCase):
def setUp(self):
np.random.seed(7)
bilby.core.utils.random.seed(7)
# set 2D multivariate Gaussian (zero mean, unit variance)
self.mus = [0.0, 0.0]
......
......@@ -275,20 +275,22 @@ class TestConditionalPriorDict(unittest.TestCase):
self.conditional_priors.ln_prob(sample=self.test_sample)
def test_sample_subset_all_keys(self):
with mock.patch("numpy.random.uniform") as m:
m.return_value = 0.5
self.assertDictEqual(
dict(var_0=0.5, var_1=0.5 ** 2, var_2=0.5 ** 3, var_3=0.5 ** 4),
self.conditional_priors.sample_subset(
keys=["var_0", "var_1", "var_2", "var_3"]
),
)
bilby.core.utils.random.seed(5)
self.assertDictEqual(
dict(
var_0=0.8050029237453802,
var_1=0.6503946979510289,
var_2=0.33516501262044845,
var_3=0.09579062316418356,
),
self.conditional_priors.sample_subset(
keys=["var_0", "var_1", "var_2", "var_3"]
),
)
def test_sample_illegal_subset(self):
with mock.patch("numpy.random.uniform") as m:
m.return_value = 0.5
with self.assertRaises(bilby.core.prior.IllegalConditionsException):
self.conditional_priors.sample_subset(keys=["var_1"])
with self.assertRaises(bilby.core.prior.IllegalConditionsException):
self.conditional_priors.sample_subset(keys=["var_1"])
def test_sample_multiple(self):
def condition_func(reference_params, a):
......
......@@ -258,11 +258,11 @@ class TestPriorDict(unittest.TestCase):
def test_sample(self):
size = 7
np.random.seed(42)
bilby.core.utils.random.seed(42)
samples1 = self.prior_set_from_dict.sample_subset(
keys=self.prior_set_from_dict.keys(), size=size
)
np.random.seed(42)
bilby.core.utils.random.seed(42)
samples2 = self.prior_set_from_dict.sample(size=size)
self.assertEqual(set(samples1.keys()), set(samples2.keys()))
for key in samples1:
......@@ -305,12 +305,12 @@ class TestPriorDict(unittest.TestCase):
Note that the format of inputs/outputs is different between the two methods.
"""
sample = self.prior_set_from_dict.sample()
self.assertEqual(
self.prior_set_from_dict.rescale(
sample.keys(),
self.prior_set_from_dict.cdf(sample=sample).values()
), list(sample.values())
)
original = np.array(list(sample.values()))
new = np.array(self.prior_set_from_dict.rescale(
sample.keys(),
self.prior_set_from_dict.cdf(sample=sample).values()
))
self.assertLess(max(abs(original - new)), 1e-10)
def test_redundancy(self):
for key in self.prior_set_from_dict.keys():
......
import unittest
from unittest import mock
import random
import numpy as np
import bilby
from bilby.core import prior
from bilby.core.sampler import proposal
......@@ -132,6 +132,7 @@ class TestNormJump(unittest.TestCase):
)
)
self.jump_proposal = proposal.NormJump(step_size=3.0, priors=self.priors)
bilby.core.utils.random.seed(5)
def tearDown(self):
del self.priors
......@@ -145,12 +146,14 @@ class TestNormJump(unittest.TestCase):
self.assertEqual(1.0, self.jump_proposal.step_size)
def test_jump_proposal_call(self):
with mock.patch("numpy.random.normal") as m:
m.return_value = 0.5
sample = proposal.Sample(dict(reflective=0.0, periodic=0.0, default=0.0))
new_sample = self.jump_proposal(sample)
expected = proposal.Sample(dict(reflective=0.5, periodic=0.5, default=0.5))
self.assertDictEqual(expected, new_sample)
sample = proposal.Sample(dict(reflective=0.0, periodic=0.0, default=0.0))
new_sample = self.jump_proposal(sample)
expected = proposal.Sample(dict(
reflective=0.5942057242396577,
periodic=-0.02692301311556511,
default=-0.7450848662857457,
))
self.assertDictEqual(expected, new_sample)
class TestEnsembleWalk(unittest.TestCase):
......@@ -164,9 +167,11 @@ class TestEnsembleWalk(unittest.TestCase):
default=prior.Uniform(minimum=-0.5, maximum=1),
)
)
bilby.core.utils.random.seed(5)
self.jump_proposal = proposal.EnsembleWalk(
random_number_generator=random.random, n_points=4, priors=self.priors
random_number_generator=bilby.core.utils.random.rng.uniform, n_points=4, priors=self.priors
)
self.coordinates = [proposal.Sample(self.priors.sample()) for _ in range(10)]
def tearDown(self):
del self.priors
......@@ -180,7 +185,7 @@ class TestEnsembleWalk(unittest.TestCase):
self.assertEqual(3, self.jump_proposal.n_points)
def test_random_number_generator_init(self):
self.assertEqual(random.random, self.jump_proposal.random_number_generator)
self.assertEqual(bilby.core.utils.random.rng.uniform, self.jump_proposal.random_number_generator)
def test_get_center_of_mass(self):
samples = [
......@@ -193,17 +198,15 @@ class TestEnsembleWalk(unittest.TestCase):
self.assertAlmostEqual(expected[key], actual[key])
def test_jump_proposal_call(self):
with mock.patch("random.sample") as m:
self.jump_proposal.random_number_generator = lambda: 2
m.return_value = [
proposal.Sample(dict(periodic=0.3, reflective=0.3, default=0.3)),
proposal.Sample(dict(periodic=0.1, reflective=0.1, default=0.1)),
]
sample = proposal.Sample(dict(periodic=0.1, reflective=0.1, default=0.1))
new_sample = self.jump_proposal(sample, coordinates=None)
expected = proposal.Sample(dict(periodic=0.1, reflective=0.1, default=0.1))
for key, value in new_sample.items():
self.assertAlmostEqual(expected[key], value)
sample = proposal.Sample(dict(periodic=0.1, reflective=0.1, default=0.1))
new_sample = self.jump_proposal(sample, coordinates=self.coordinates)
expected = proposal.Sample(dict(
periodic=0.437075089594473,
reflective=-0.18027731528487945,
default=-0.17570046901727415,
))
for key, value in new_sample.items():
self.assertAlmostEqual(expected[key], value)
class TestEnsembleEnsembleStretch(unittest.TestCase):
......@@ -217,7 +220,9 @@ class TestEnsembleEnsembleStretch(unittest.TestCase):
default=prior.Uniform(minimum=-0.5, maximum=1),
)
)
bilby.core.utils.random.seed(5)
self.jump_proposal = proposal.EnsembleStretch(scale=3.0, priors=self.priors)
self.coordinates = [proposal.Sample(self.priors.sample()) for _ in range(10)]
def tearDown(self):
del self.priors
......@@ -231,47 +236,24 @@ class TestEnsembleEnsembleStretch(unittest.TestCase):
self.assertEqual(5.0, self.jump_proposal.scale)
def test_jump_proposal_call(self):
with mock.patch("random.choice") as m:
with mock.patch("random.uniform") as n:
second_sample = proposal.Sample(
dict(periodic=0.3, reflective=0.3, default=0.3)
)
random_number = 0.5
m.return_value = second_sample
n.return_value = random_number
sample = proposal.Sample(
dict(periodic=0.1, reflective=0.1, default=0.1)
)
new_sample = self.jump_proposal(sample, coordinates=None)
coords = 0.3 - 0.2 * np.exp(
random_number * np.log(self.jump_proposal.scale)
)
expected = proposal.Sample(
dict(periodic=coords, reflective=coords, default=coords)
)
for key, value in new_sample.items():
self.assertAlmostEqual(expected[key], value)
sample = proposal.Sample(
dict(periodic=0.1, reflective=0.1, default=0.1)
)
new_sample = self.jump_proposal(sample, coordinates=self.coordinates)
expected = proposal.Sample(dict(
periodic=0.5790181653312239,
reflective=-0.028378746842481914,
default=-0.23534241783479043,
))
for key, value in new_sample.items():
self.assertAlmostEqual(expected[key], value)
def test_log_j_after_call(self):
with mock.patch("random.uniform") as m1:
with mock.patch("numpy.log") as m2:
with mock.patch("numpy.exp") as m3:
m1.return_value = 1
m2.return_value = 1
m3.return_value = 1
coordinates = [
proposal.Sample(
dict(periodic=0.3, reflective=0.3, default=0.3)
),
proposal.Sample(
dict(periodic=0.3, reflective=0.3, default=0.3)
),
]
sample = proposal.Sample(
dict(periodic=0.2, reflective=0.2, default=0.2)
)
self.jump_proposal(sample=sample, coordinates=coordinates)
self.assertEqual(3, self.jump_proposal.log_j)
sample = proposal.Sample(
dict(periodic=0.2, reflective=0.2, default=0.2)
)
self.jump_proposal(sample=sample, coordinates=self.coordinates)
self.assertAlmostEqual(-3.2879289432183088, self.jump_proposal.log_j, 10)
class TestDifferentialEvolution(unittest.TestCase):
......@@ -285,9 +267,11 @@ class TestDifferentialEvolution(unittest.TestCase):
default=prior.Uniform(minimum=-0.5, maximum=1),
)
)
bilby.core.utils.random.seed(5)
self.jump_proposal = proposal.DifferentialEvolution(
sigma=1e-3, mu=0.5, priors=self.priors
)
self.coordinates = [proposal.Sample(self.priors.sample()) for _ in range(10)]
def tearDown(self):
del self.priors
......@@ -305,22 +289,17 @@ class TestDifferentialEvolution(unittest.TestCase):
self.assertEqual(2, self.jump_proposal.sigma)
def test_jump_proposal_call(self):
with mock.patch("random.sample") as m:
with mock.patch("random.gauss") as n:
m.return_value = (
proposal.Sample(dict(periodic=0.2, reflective=0.2, default=0.2)),
proposal.Sample(dict(periodic=0.3, reflective=0.3, default=0.3)),
)
n.return_value = 1
sample = proposal.Sample(
dict(periodic=0.1, reflective=0.1, default=0.1)
)
expected = proposal.Sample(
dict(periodic=0.2, reflective=0.2, default=0.2)
)
new_sample = self.jump_proposal(sample, coordinates=None)
for key, value in new_sample.items():
self.assertAlmostEqual(expected[key], value)
sample = proposal.Sample(
dict(periodic=0.1, reflective=0.1, default=0.1)
)
expected = proposal.Sample(dict(
periodic=0.09440864471444077,
reflective=0.567962015300636,
default=0.0657296821780595,
))
new_sample = self.jump_proposal(sample, coordinates=self.coordinates)
for key, value in new_sample.items():
self.assertAlmostEqual(expected[key], value)
class TestEnsembleEigenVector(unittest.TestCase):
......@@ -334,7 +313,9 @@ class TestEnsembleEigenVector(unittest.TestCase):
default=prior.Uniform(minimum=-0.5, maximum=1),
)
)
bilby.core.utils.random.seed(5)
self.jump_proposal = proposal.EnsembleEigenVector(priors=self.priors)
self.coordinates = [proposal.Sample(self.priors.sample()) for _ in range(10)]
def tearDown(self):
del self.priors
......@@ -386,26 +367,17 @@ class TestEnsembleEigenVector(unittest.TestCase):
self.assertEqual(2, self.jump_proposal.eigen_vectors)
def test_jump_proposal_call(self):
self.jump_proposal.update_eigenvectors = lambda x: None
self.jump_proposal.eigen_values = np.array([1, np.nan, np.nan])
self.jump_proposal.eigen_vectors = np.array(
[[0.1, np.nan, np.nan], [0.4, np.nan, np.nan], [0.7, np.nan, np.nan]]
)
with mock.patch("random.randrange") as m:
with mock.patch("random.gauss") as n:
m.return_value = 0
n.return_value = 1
expected = proposal.Sample()
expected["periodic"] = 0.2
expected["reflective"] = 0.5
expected["default"] = 0.8
sample = proposal.Sample()
sample["periodic"] = 0.1
sample["reflective"] = 0.1
sample["default"] = 0.1
new_sample = self.jump_proposal(sample, coordinates=None)
for key, value in new_sample.items():
self.assertAlmostEqual(expected[key], value)
expected = proposal.Sample()
expected["periodic"] = 0.10318172002873117
expected["reflective"] = 0.11177972036165257
expected["default"] = 0.10053457100669783
sample = proposal.Sample()
sample["periodic"] = 0.1
sample["reflective"] = 0.1
sample["default"] = 0.1
new_sample = self.jump_proposal(sample, coordinates=self.coordinates)
for key, value in new_sample.items():
self.assertAlmostEqual(expected[key], value)
if __name__ == "__main__":
......
......@@ -14,7 +14,7 @@ from scipy.special import logsumexp
class TestMarginalizedLikelihood(unittest.TestCase):
def setUp(self):
np.random.seed(500)
bilby.core.utils.random.seed(500)
self.duration = 4
self.sampling_frequency = 2048
self.parameters = dict(
......@@ -177,7 +177,7 @@ class TestMarginalizations(unittest.TestCase):
path_to_roq_weights = "weights.npz"
def setUp(self):
np.random.seed(500)
bilby.core.utils.random.seed(200)
self.duration = 4
self.sampling_frequency = 2048
self.parameters = dict(
......@@ -215,7 +215,7 @@ class TestMarginalizations(unittest.TestCase):
waveform_arguments=dict(
reference_frequency=20.0,
minimum_frequency=20.0,
approximant="IMRPhenomPv2",
waveform_approximant="IMRPhenomPv2",
)
)
self.interferometers.inject_signal(
......@@ -249,7 +249,7 @@ class TestMarginalizations(unittest.TestCase):
waveform_arguments=dict(
reference_frequency=20.0,
minimum_frequency=20.0,
approximant="IMRPhenomPv2",
waveform_approximant="IMRPhenomPv2",
frequency_nodes_linear=np.load(f"{roq_dir}/fnodes_linear.npy"),
frequency_nodes_quadratic=np.load(f"{roq_dir}/fnodes_quadratic.npy"),
)
......@@ -265,7 +265,7 @@ class TestMarginalizations(unittest.TestCase):
waveform_arguments=dict(
reference_frequency=20.0,
minimum_frequency=20.0,
approximant="IMRPhenomPv2",
waveform_approximant="IMRPhenomPv2",
)
)
......@@ -333,7 +333,7 @@ class TestMarginalizations(unittest.TestCase):
cls_ = bilby.gw.likelihood.ROQGravitationalWaveTransient
elif kind == "relbin":
cls_ = bilby.gw.likelihood.RelativeBinningGravitationalWaveTransient
kwargs["epsilon"] = 0.3
kwargs["epsilon"] = 0.1
self.parameters["fiducial"] = 0
else:
raise ValueError(f"kind {kind} not understood")
......@@ -366,7 +366,15 @@ class TestMarginalizations(unittest.TestCase):
marg_like, marginalized.log_likelihood_ratio(), delta=0.5
)
@parameterized.expand(_parameters)
@parameterized.expand(
_parameters,
name_func=lambda func, num, param: (
f"{func.__name__}_{num}__{param.args[0]}_{param.args[1]}_" + "_".join([
["D", "T", "P"][ii] for ii, val
in enumerate(param.args[-3:]) if val
])
)
)
def test_marginalisation(self, kind, key, distance, time, phase):
if all([distance, time, phase]):
pytest.skip()
......
......@@ -12,7 +12,7 @@ from bilby.gw.likelihood import BilbyROQParamsRangeError
class TestBasicGWTransient(unittest.TestCase):
def setUp(self):
np.random.seed(500)
bilby.core.utils.random.seed(500)
self.parameters = dict(
mass_1=31.0,
mass_2=29.0,
......@@ -56,13 +56,13 @@ class TestBasicGWTransient(unittest.TestCase):
"""Test noise log likelihood matches precomputed value"""
self.likelihood.noise_log_likelihood()
self.assertAlmostEqual(
-4037.0994372143414, self.likelihood.noise_log_likelihood(), 3
-4014.1787704539474, self.likelihood.noise_log_likelihood(), 3
)
def test_log_likelihood(self):
"""Test log likelihood matches precomputed value"""
self.likelihood.log_likelihood()
self.assertAlmostEqual(self.likelihood.log_likelihood(), -4054.047229508672, 3)
self.assertAlmostEqual(self.likelihood.log_likelihood(), -4032.4397343470005, 3)
def test_log_likelihood_ratio(self):
"""Test log likelihood ratio returns the correct value"""
......@@ -87,7 +87,7 @@ class TestBasicGWTransient(unittest.TestCase):
class TestGWTransient(unittest.TestCase):
def setUp(self):
np.random.seed(500)
bilby.core.utils.random.seed(500)
self.duration = 4
self.sampling_frequency = 2048
self.parameters = dict(
......@@ -141,14 +141,14 @@ class TestGWTransient(unittest.TestCase):
"""Test noise log likelihood matches precomputed value"""
self.likelihood.noise_log_likelihood()
self.assertAlmostEqual(
-4037.0994372143414, self.likelihood.noise_log_likelihood(), 3
-4014.1787704539474, self.likelihood.noise_log_likelihood(), 3
)
def test_log_likelihood(self):
"""Test log likelihood matches precomputed value"""
self.likelihood.log_likelihood()
self.assertAlmostEqual(self.likelihood.log_likelihood(),
-4054.047229508673, 3)
-4032.4397343470005, 3)
def test_log_likelihood_ratio(self):
"""Test log likelihood ratio returns the correct value"""
......@@ -760,7 +760,8 @@ class TestROQLikelihoodHDF5(unittest.TestCase):
if add_cal_errors:
spline_calibration_nodes = 10
np.random.seed(170817)
bilby.core.utils.random.seed(170817)
rng = bilby.core.utils.random.rng
for ifo in interferometers:
prefix = f"recalib_{ifo.name}_"
ifo.calibration_model = bilby.gw.calibration.CubicSpline(
......@@ -772,9 +773,9 @@ class TestROQLikelihoodHDF5(unittest.TestCase):
for i in range(spline_calibration_nodes):
# 5% in amplitude, 5deg in phase
self.injection_parameters[f"{prefix}amplitude_{i}"] = \
np.random.normal(loc=0, scale=0.05)
rng.normal(loc=0, scale=0.05)
self.injection_parameters[f"{prefix}phase_{i}"] = \
np.random.normal(loc=0, scale=5 * np.pi / 180)
rng.normal(loc=0, scale=5 * np.pi / 180)
waveform_generator = bilby.gw.WaveformGenerator(
duration=self.duration,
......@@ -1171,7 +1172,8 @@ class TestMBLikelihood(unittest.TestCase):
) # Network SNR is ~50
self.ifos = bilby.gw.detector.InterferometerList(["H1", "L1", "V1"])
np.random.seed(170817)
bilby.core.utils.random.seed(70817)
rng = bilby.core.utils.random.rng
self.ifos.set_strain_data_from_power_spectral_densities(
sampling_frequency=self.sampling_frequency, duration=self.duration,
start_time=self.test_parameters['geocent_time'] - self.duration + 2.
......@@ -1193,9 +1195,9 @@ class TestMBLikelihood(unittest.TestCase):
self.test_parameters[f"recalib_{ifo.name}_phase_{i}"] = 0
# Calibration errors of 5% in amplitude and 5 degrees in phase
self.calibration_parameters[f"recalib_{ifo.name}_amplitude_{i}"] = \
np.random.normal(loc=0, scale=0.05)
rng.normal(loc=0, scale=0.05)
self.calibration_parameters[f"recalib_{ifo.name}_phase_{i}"] = \
np.random.normal(loc=0, scale=5 * np.pi / 180)
rng.normal(loc=0, scale=5 * np.pi / 180)
self.priors = bilby.gw.prior.BBHPriorDict()
self.priors.pop("mass_1")
......@@ -1230,7 +1232,7 @@ class TestMBLikelihood(unittest.TestCase):
duration=self.duration, sampling_frequency=self.sampling_frequency,
frequency_domain_source_model=bilby.gw.source.lal_binary_black_hole,
waveform_arguments=dict(
reference_frequency=self.fmin, approximant=approximant
reference_frequency=self.fmin, waveform_approximant=approximant
)
)
self.ifos.inject_signal(parameters=self.test_parameters, waveform_generator=wfg)
......@@ -1239,7 +1241,7 @@ class TestMBLikelihood(unittest.TestCase):
duration=self.duration, sampling_frequency=self.sampling_frequency,
frequency_domain_source_model=bilby.gw.source.binary_black_hole_frequency_sequence,
waveform_arguments=dict(
reference_frequency=self.fmin, approximant=approximant
reference_frequency=self.fmin, waveform_approximant=approximant
)
)
likelihood = bilby.gw.likelihood.GravitationalWaveTransient(
......@@ -1270,7 +1272,7 @@ class TestMBLikelihood(unittest.TestCase):
duration=self.duration, sampling_frequency=self.sampling_frequency,
frequency_domain_source_model=bilby.gw.source.lal_binary_black_hole,
waveform_arguments=dict(
reference_frequency=self.fmin, approximant=approximant
reference_frequency=self.fmin, waveform_approximant=approximant
)
)
self.ifos.inject_signal(parameters=self.test_parameters, waveform_generator=wfg)
......@@ -1279,7 +1281,7 @@ class TestMBLikelihood(unittest.TestCase):
duration=self.duration, sampling_frequency=self.sampling_frequency,
frequency_domain_source_model=bilby.gw.source.binary_black_hole_frequency_sequence,
waveform_arguments=dict(
reference_frequency=self.fmin, approximant=approximant
reference_frequency=self.fmin, waveform_approximant=approximant
)
)
likelihood = bilby.gw.likelihood.GravitationalWaveTransient(
......
......@@ -37,6 +37,14 @@ class TestBBHPriorDict(unittest.TestCase):
del self.bbh_prior_dict
del self.base_directory
def test_read_write_default_prior(self):
filename = "test_prior.prior"
self.bbh_prior_dict.to_file(outdir=".", label="test_prior")
new_prior = bilby.gw.prior.BBHPriorDict(filename=filename)
for key in self.bbh_prior_dict:
self.assertEqual(self.bbh_prior_dict[key], new_prior[key])
os.remove(filename)
def test_create_default_prior(self):
default = bilby.gw.prior.BBHPriorDict()
minima = all(
......
......@@ -5,7 +5,7 @@ import numpy as np
import bilby
from bilby.gw.waveform_generator import WaveformGenerator
np.random.seed(10)
bilby.core.utils.random.seed(10)
time_duration = 4.0
sampling_frequency = 4096.0
......
......@@ -4,7 +4,6 @@ import logging
from packaging import version
import unittest
import numpy as np
import bilby
import scipy
from scipy.stats import ks_2samp, kstest
......@@ -40,7 +39,7 @@ class Test(unittest.TestCase):
duration = 4.0
sampling_frequency = 2048.0
label = "full_15_parameters"
np.random.seed(8817021)
bilby.core.utils.random.seed(8817021)
waveform_arguments = dict(
waveform_approximant="IMRPhenomPv2",
......
......@@ -79,12 +79,13 @@ def model(x, m, c):
class TestRunningSamplers(unittest.TestCase):
def setUp(self):
np.random.seed(42)
bilby.core.utils.random.seed(42)
bilby.core.utils.command_line_args.bilby_test_mode = False
rng = bilby.core.utils.random.rng
self.x = np.linspace(0, 1, 11)
self.injection_parameters = dict(m=0.5, c=0.2)
self.sigma = 0.1
self.y = model(self.x, **self.injection_parameters) + np.random.normal(
self.y = model(self.x, **self.injection_parameters) + rng.normal(
0, self.sigma, len(self.x)
)
self.likelihood = bilby.likelihood.GaussianLikelihood(
......