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
import unittest
import mock
from unittest import mock
import numpy as np
......
import unittest
import numpy as np
from copy import copy
import bilby
import lal
import lalsimulation
import numpy as np
from copy import copy
class TestLalBBH(unittest.TestCase):
def setUp(self):
......@@ -95,6 +95,86 @@ class TestLalBBH(unittest.TestCase):
self.assertFalse(np.all(out_v223["plus"] == out_v102["plus"]))
class TestGWSignalBBH(unittest.TestCase):
def setUp(self):
self.parameters = dict(
mass_1=30.0,
mass_2=30.0,
luminosity_distance=400.0,
a_1=0.4,
tilt_1=0.2,
phi_12=1.0,
a_2=0.8,
tilt_2=2.7,
phi_jl=2.9,
theta_jn=0.3,
phase=0.0,
)
self.waveform_kwargs = dict(
waveform_approximant="IMRPhenomXPHM",
reference_frequency=50.0,
minimum_frequency=20.0,
catch_waveform_errors=True,
)
self.frequency_array = bilby.core.utils.create_frequency_series(2048, 4)
self.bad_parameters = copy(self.parameters)
self.bad_parameters["mass_1"] = -30.0
def tearDown(self):
del self.parameters
del self.waveform_kwargs
del self.frequency_array
del self.bad_parameters
def test_gwsignal_bbh_works_runs_valid_parameters(self):
self.parameters.update(self.waveform_kwargs)
self.assertIsInstance(
bilby.gw.source.gwsignal_binary_black_hole(
self.frequency_array, **self.parameters
),
dict,
)
def test_waveform_error_catching(self):
self.bad_parameters.update(self.waveform_kwargs)
self.assertIsNone(
bilby.gw.source.gwsignal_binary_black_hole(
self.frequency_array, **self.bad_parameters
)
)
def test_waveform_error_raising(self):
raise_error_parameters = copy(self.bad_parameters)
raise_error_parameters.update(self.waveform_kwargs)
raise_error_parameters["catch_waveform_errors"] = False
with self.assertRaises(Exception):
bilby.gw.source.gwsignal_binary_black_hole(
self.frequency_array, **raise_error_parameters
)
# def test_gwsignal_bbh_works_without_waveform_parameters(self):
# self.assertIsInstance(
# bilby.gw.source.gwsignal_binary_black_hole(
# self.frequency_array, **self.parameters
# ),
# dict,
# )
def test_gwsignal_lal_bbh_consistency(self):
self.parameters.update(self.waveform_kwargs)
hpc_gwsignal = bilby.gw.source.gwsignal_binary_black_hole(
self.frequency_array, **self.parameters
)
hpc_lal = bilby.gw.source.lal_binary_black_hole(
self.frequency_array, **self.parameters
)
self.assertTrue(
np.allclose(hpc_gwsignal["plus"], hpc_lal["plus"], atol=0, rtol=1e-7)
)
self.assertTrue(
np.allclose(hpc_gwsignal["cross"], hpc_lal["cross"], atol=0, rtol=1e-7)
)
class TestLalBNS(unittest.TestCase):
def setUp(self):
self.parameters = dict(
......@@ -225,8 +305,7 @@ class TestROQBBH(unittest.TestCase):
frequency_nodes_linear=fnodes_linear,
frequency_nodes_quadratic=fnodes_quadratic,
reference_frequency=50.0,
minimum_frequency=20.0,
approximant="IMRPhenomPv2",
waveform_approximant="IMRPhenomPv2",
)
self.frequency_array = bilby.core.utils.create_frequency_series(2048, 4)
......@@ -264,15 +343,14 @@ class TestBBHfreqseq(unittest.TestCase):
theta_jn=0.3,
phase=0.0
)
minimum_frequency = 20.0
self.minimum_frequency = 20.0
self.frequency_array = bilby.core.utils.create_frequency_series(2048, 8)
self.full_frequencies_to_sequence = self.frequency_array >= minimum_frequency
self.full_frequencies_to_sequence = self.frequency_array >= self.minimum_frequency
self.frequencies = self.frequency_array[self.full_frequencies_to_sequence]
self.waveform_kwargs = dict(
waveform_approximant="IMRPhenomHM",
reference_frequency=50.0,
minimum_frequency=minimum_frequency,
catch_waveform_errors=True,
frequencies=self.frequency_array[self.full_frequencies_to_sequence]
)
self.bad_parameters = copy(self.parameters)
self.bad_parameters["mass_1"] = -30.0
......@@ -282,12 +360,13 @@ class TestBBHfreqseq(unittest.TestCase):
del self.waveform_kwargs
del self.frequency_array
del self.bad_parameters
del self.minimum_frequency
def test_valid_parameters(self):
self.parameters.update(self.waveform_kwargs)
self.assertIsInstance(
bilby.gw.source.binary_black_hole_frequency_sequence(
self.frequency_array, **self.parameters
self.frequency_array, frequencies=self.frequencies, **self.parameters
),
dict
)
......@@ -296,7 +375,7 @@ class TestBBHfreqseq(unittest.TestCase):
self.bad_parameters.update(self.waveform_kwargs)
self.assertIsNone(
bilby.gw.source.binary_black_hole_frequency_sequence(
self.frequency_array, **self.bad_parameters
self.frequency_array, frequencies=self.frequencies, **self.bad_parameters
)
)
......@@ -306,16 +385,16 @@ class TestBBHfreqseq(unittest.TestCase):
raise_error_parameters["catch_waveform_errors"] = False
with self.assertRaises(Exception):
bilby.gw.source.binary_black_hole_frequency_sequence(
self.frequency_array, **raise_error_parameters
self.frequency_array, frequencies=self.frequencies, **raise_error_parameters
)
def test_match_LalBBH(self):
self.parameters.update(self.waveform_kwargs)
freqseq = bilby.gw.source.binary_black_hole_frequency_sequence(
self.frequency_array, **self.parameters
self.frequency_array, frequencies=self.frequencies, **self.parameters
)
lalbbh = bilby.gw.source.lal_binary_black_hole(
self.frequency_array, **self.parameters
self.frequency_array, minimum_frequency=self.minimum_frequency, **self.parameters
)
self.assertEqual(freqseq.keys(), lalbbh.keys())
for mode in freqseq:
......@@ -328,10 +407,10 @@ class TestBBHfreqseq(unittest.TestCase):
parameters.update(self.waveform_kwargs)
parameters['mode_array'] = [[2, 2]]
freqseq = bilby.gw.source.binary_black_hole_frequency_sequence(
self.frequency_array, **parameters
self.frequency_array, frequencies=self.frequencies, **parameters
)
lalbbh = bilby.gw.source.lal_binary_black_hole(
self.frequency_array, **parameters
self.frequency_array, minimum_frequency=self.minimum_frequency, **parameters
)
self.assertEqual(freqseq.keys(), lalbbh.keys())
for mode in freqseq:
......@@ -346,10 +425,10 @@ class TestBBHfreqseq(unittest.TestCase):
lalsimulation.SimInspiralWaveformParamsInsertNonGRDChi0(wf_dict, 1.)
parameters['lal_waveform_dictionary'] = wf_dict
freqseq = bilby.gw.source.binary_black_hole_frequency_sequence(
self.frequency_array, **parameters
self.frequency_array, frequencies=self.frequencies, **parameters
)
lalbbh = bilby.gw.source.lal_binary_black_hole(
self.frequency_array, **parameters
self.frequency_array, minimum_frequency=self.minimum_frequency, **parameters
)
self.assertEqual(freqseq.keys(), lalbbh.keys())
for mode in freqseq:
......@@ -375,26 +454,26 @@ class TestBNSfreqseq(unittest.TestCase):
lambda_1=1000.0,
lambda_2=1000.0
)
minimum_frequency = 50.0
self.minimum_frequency = 50.0
self.frequency_array = bilby.core.utils.create_frequency_series(2048, 16)
self.full_frequencies_to_sequence = self.frequency_array >= minimum_frequency
self.full_frequencies_to_sequence = self.frequency_array >= self.minimum_frequency
self.frequencies = self.frequency_array[self.full_frequencies_to_sequence]
self.waveform_kwargs = dict(
waveform_approximant="IMRPhenomPv2_NRTidal",
reference_frequency=50.0,
minimum_frequency=minimum_frequency,
frequencies=self.frequency_array[self.full_frequencies_to_sequence]
)
def tearDown(self):
del self.parameters
del self.waveform_kwargs
del self.frequency_array
del self.minimum_frequency
def test_with_valid_parameters(self):
self.parameters.update(self.waveform_kwargs)
self.assertIsInstance(
bilby.gw.source.binary_neutron_star_frequency_sequence(
self.frequency_array, **self.parameters
self.frequency_array, frequencies=self.frequencies, **self.parameters
),
dict
)
......@@ -405,16 +484,16 @@ class TestBNSfreqseq(unittest.TestCase):
self.parameters.update(self.waveform_kwargs)
with self.assertRaises(TypeError):
bilby.gw.source.binary_neutron_star_frequency_sequence(
self.frequency_array, **self.parameters
self.frequency_array, frequencies=self.frequencies, **self.parameters
)
def test_match_LalBNS(self):
self.parameters.update(self.waveform_kwargs)
freqseq = bilby.gw.source.binary_neutron_star_frequency_sequence(
self.frequency_array, **self.parameters
self.frequency_array, frequencies=self.frequencies, **self.parameters
)
lalbns = bilby.gw.source.lal_binary_neutron_star(
self.frequency_array, **self.parameters
self.frequency_array, minimum_frequency=self.minimum_frequency, **self.parameters
)
self.assertEqual(freqseq.keys(), lalbns.keys())
for mode in freqseq:
......@@ -423,5 +502,199 @@ class TestBNSfreqseq(unittest.TestCase):
self.assertLess(diff / norm, 1e-5)
class TestRelbinBBH(unittest.TestCase):
def setUp(self):
self.parameters = dict(
mass_1=30.0,
mass_2=30.0,
luminosity_distance=400.0,
a_1=0.4,
tilt_1=0.2,
phi_12=1.0,
a_2=0.8,
tilt_2=2.7,
phi_jl=2.9,
theta_jn=0.3,
phase=0.0,
)
self.waveform_kwargs_fiducial = dict(
waveform_approximant="IMRPhenomPv2",
reference_frequency=50.0,
minimum_frequency=20.0,
catch_waveform_errors=True,
fiducial=True,
)
self.waveform_kwargs_binned = dict(
waveform_approximant="IMRPhenomPv2",
reference_frequency=50.0,
minimum_frequency=20.0,
catch_waveform_errors=True,
fiducial=False,
frequency_bin_edges=np.arange(20, 1500, 50)
)
self.frequency_array = bilby.core.utils.create_frequency_series(2048, 4)
self.bad_parameters = copy(self.parameters)
self.bad_parameters["mass_1"] = -30.0
def tearDown(self):
del self.parameters
del self.waveform_kwargs_fiducial
del self.waveform_kwargs_binned
del self.frequency_array
del self.bad_parameters
def test_relbin_fiducial_bbh_works_runs_valid_parameters(self):
self.parameters.update(self.waveform_kwargs_fiducial)
self.assertIsInstance(
bilby.gw.source.lal_binary_black_hole_relative_binning(
self.frequency_array, **self.parameters
),
dict,
)
def test_relbin_binned_bbh_works_runs_valid_parameters(self):
self.parameters.update(self.waveform_kwargs_binned)
self.assertIsInstance(
bilby.gw.source.lal_binary_black_hole_relative_binning(
self.frequency_array, **self.parameters
),
dict,
)
def test_waveform_error_catching_fiducial(self):
self.bad_parameters.update(self.waveform_kwargs_fiducial)
self.assertIsNone(
bilby.gw.source.lal_binary_black_hole_relative_binning(
self.frequency_array, **self.bad_parameters
)
)
def test_waveform_error_catching_binned(self):
self.bad_parameters.update(self.waveform_kwargs_binned)
self.assertIsNone(
bilby.gw.source.lal_binary_black_hole_relative_binning(
self.frequency_array, **self.bad_parameters
)
)
def test_waveform_error_raising_fiducial(self):
raise_error_parameters = copy(self.bad_parameters)
raise_error_parameters.update(self.waveform_kwargs_fiducial)
raise_error_parameters["catch_waveform_errors"] = False
with self.assertRaises(Exception):
bilby.gw.source.lal_binary_black_hole_relative_binning(
self.frequency_array, **raise_error_parameters
)
def test_waveform_error_raising_binned(self):
raise_error_parameters = copy(self.bad_parameters)
raise_error_parameters.update(self.waveform_kwargs_binned)
raise_error_parameters["catch_waveform_errors"] = False
with self.assertRaises(Exception):
bilby.gw.source.lal_binary_black_hole_relative_binning(
self.frequency_array, **raise_error_parameters
)
def test_relbin_bbh_fails_without_fiducial_option(self):
with self.assertRaises(TypeError):
bilby.gw.source.lal_binary_black_hole_relative_binning(
self.frequency_array, **self.parameters
)
def test_relbin_bbh_xpprecession_version(self):
self.parameters.update(self.waveform_kwargs_fiducial)
self.parameters["waveform_approximant"] = "IMRPhenomXP"
# Test that we can modify the XP precession version
out_v223 = bilby.gw.source.lal_binary_black_hole_relative_binning(
self.frequency_array, PhenomXPrecVersion=223, **self.parameters
)
out_v102 = bilby.gw.source.lal_binary_black_hole_relative_binning(
self.frequency_array, PhenomXPrecVersion=102, **self.parameters
)
self.assertFalse(np.all(out_v223["plus"] == out_v102["plus"]))
class TestRelbinBNS(unittest.TestCase):
def setUp(self):
self.parameters = dict(
mass_1=1.4,
mass_2=1.4,
luminosity_distance=400.0,
a_1=0.4,
a_2=0.3,
tilt_1=0.2,
tilt_2=1.7,
phi_jl=0.2,
phi_12=0.9,
theta_jn=1.7,
phase=0.0,
lambda_1=100.0,
lambda_2=100.0,
)
self.waveform_kwargs_fiducial = dict(
waveform_approximant="IMRPhenomPv2_NRTidal",
reference_frequency=50.0,
minimum_frequency=20.0,
fiducial=True,
)
self.waveform_kwargs_binned = dict(
waveform_approximant="IMRPhenomPv2_NRTidal",
reference_frequency=50.0,
minimum_frequency=20.0,
fiducial=False,
frequency_bin_edges=np.arange(20, 1500, 50),
)
self.frequency_array = bilby.core.utils.create_frequency_series(2048, 4)
def tearDown(self):
del self.parameters
del self.waveform_kwargs_fiducial
del self.waveform_kwargs_binned
del self.frequency_array
def test_relbin_fiducial_bns_runs_with_valid_parameters(self):
self.parameters.update(self.waveform_kwargs_fiducial)
self.assertIsInstance(
bilby.gw.source.lal_binary_neutron_star_relative_binning(
self.frequency_array, **self.parameters
),
dict,
)
def test_relbin_binned_bns_runs_with_valid_parameters(self):
self.parameters.update(self.waveform_kwargs_binned)
self.assertIsInstance(
bilby.gw.source.lal_binary_neutron_star_relative_binning(
self.frequency_array, **self.parameters
),
dict,
)
def test_relbin_bns_fails_without_fiducial_option(self):
with self.assertRaises(TypeError):
bilby.gw.source.lal_binary_neutron_star_relative_binning(
self.frequency_array, **self.parameters
)
def test_fiducial_fails_without_tidal_parameters(self):
self.parameters.pop("lambda_1")
self.parameters.pop("lambda_2")
self.parameters.update(self.waveform_kwargs_fiducial)
with self.assertRaises(TypeError):
bilby.gw.source.lal_binary_neutron_star_relative_binning(
self.frequency_array, **self.parameters
)
def test_binned_fails_without_tidal_parameters(self):
self.parameters.pop("lambda_1")
self.parameters.pop("lambda_2")
self.parameters.update(self.waveform_kwargs_binned)
with self.assertRaises(TypeError):
bilby.gw.source.lal_binary_neutron_star_relative_binning(
self.frequency_array, **self.parameters
)
if __name__ == "__main__":
unittest.main()
import unittest
import os
from shutil import rmtree
from importlib.metadata import version
import numpy as np
import lal
......@@ -8,6 +9,7 @@ import lalsimulation as lalsim
from gwpy.timeseries import TimeSeries
from gwpy.detector import Channel
from scipy.stats import ks_2samp
import pytest
import bilby
from bilby.gw import utils as gwutils
......@@ -36,34 +38,6 @@ class TestGWUtils(unittest.TestCase):
psd = gwutils.psd_from_freq_series(freq_data, df)
self.assertTrue(np.all(psd == (freq_data * 2 * df ** 0.5) ** 2))
def test_time_delay_from_geocenter(self):
"""
The difference in the two detector case is due to rounding error.
Different hardware gives different numbers in the last decimal place.
"""
det1 = np.array([0.1, 0.2, 0.3])
det2 = np.array([0.1, 0.2, 0.5])
ra = 0.5
dec = 0.2
time = 10
self.assertEqual(gwutils.time_delay_geocentric(det1, det1, ra, dec, time), 0)
self.assertAlmostEqual(
gwutils.time_delay_geocentric(det1, det2, ra, dec, time),
1.3253791114055397e-10,
14,
)
def test_get_polarization_tensor(self):
ra = 1
dec = 2.0
time = 10
psi = 0.1
for mode in ["plus", "cross", "breathing", "longitudinal", "x", "y"]:
p = gwutils.get_polarization_tensor(ra, dec, time, psi, mode)
self.assertEqual(p.shape, (3, 3))
with self.assertRaises(ValueError):
gwutils.get_polarization_tensor(ra, dec, time, psi, "not-a-mode")
def test_inner_product(self):
aa = np.array([1, 2, 3])
bb = np.array([5, 6, 7])
......@@ -100,31 +74,44 @@ class TestGWUtils(unittest.TestCase):
)
self.assertEqual(mfsnr, 25.510869054168282)
@pytest.mark.skip(reason="GWOSC unstable: avoiding this test")
def test_get_event_time(self):
from urllib3.exceptions import NewConnectionError
events = [
"GW150914",
"GW151012",
"GW151226",
"GW170104",
"GW170608",
"GW170729",
"GW170809",
"GW170814",
"GW170817",
"GW170818",
"GW170823",
]
for event in events:
self.assertTrue(isinstance(gwutils.get_event_time(event), float))
try:
self.assertTrue(isinstance(gwutils.get_event_time(event), float))
except NewConnectionError:
return
self.assertTrue(gwutils.get_event_time("GW010290") is None)
with self.assertRaises(ValueError):
gwutils.get_event_time("GW010290")
@pytest.mark.skipif(version("gwpy") < "3.0.8", reason="GWpy version < 3.0.8")
def test_read_frame_file(self):
"""
Test that reading a frame file works as expected
for a few conditions.
1. Reading without time limits returns the full data
2. Reading with time limits returns the expected data
(inclusive of start time if present, exclusive of end time)
3. Reading without the channel name provided finds a standard name
4. Reading without the channel with a non-standard name returns None.
Notes
=====
There was a longstanding bug in gwpy that we previously tested for
here, but this has been fixed in gwpy 3.0.8.
"""
start_time = 0
end_time = 10
channel = "H1:GDS-CALIB_STRAIN"
N = 100
times = np.linspace(start_time, end_time, N)
times = np.linspace(start_time, end_time, N, endpoint=False)
data = np.random.normal(0, 1, N)
ts = TimeSeries(data=data, times=times, t0=0)
ts.channel = Channel(channel)
......@@ -136,8 +123,8 @@ class TestGWUtils(unittest.TestCase):
strain = gwutils.read_frame_file(
filename, start_time=None, end_time=None, channel=channel
)
self.assertEqual(strain.channel.name, channel)
self.assertTrue(np.all(strain.value == data[:-1]))
self.assertEqual(strain.name, channel)
self.assertTrue(np.all(strain.value == data))
# Check reading with time limits
start_cut = 2
......@@ -145,19 +132,18 @@ class TestGWUtils(unittest.TestCase):
strain = gwutils.read_frame_file(
filename, start_time=start_cut, end_time=end_cut, channel=channel
)
idxs = (times > start_cut) & (times < end_cut)
# Dropping the last element - for some reason gwpy drops the last element when reading in data
self.assertTrue(np.all(strain.value == data[idxs][:-1]))
idxs = (times >= start_cut) & (times < end_cut)
self.assertTrue(np.all(strain.value == data[idxs]))
# Check reading with unknown channels
strain = gwutils.read_frame_file(filename, start_time=None, end_time=None)
self.assertTrue(np.all(strain.value == data[:-1]))
self.assertTrue(np.all(strain.value == data))
# Check reading with incorrect channel
strain = gwutils.read_frame_file(
filename, start_time=None, end_time=None, channel="WRONG"
)
self.assertTrue(np.all(strain.value == data[:-1]))
self.assertTrue(np.all(strain.value == data))
ts = TimeSeries(data=data, times=times, t0=0)
ts.name = "NOT-A-KNOWN-CHANNEL"
......
import unittest
from unittest import mock
import bilby
import lalsimulation
import numpy as np
import mock
from mock import MagicMock
def dummy_func_array_return_value(
......@@ -160,6 +161,69 @@ class TestWaveformArgumentsSetting(unittest.TestCase):
)
class TestLALCBCWaveformArgumentsSetting(unittest.TestCase):
def setUp(self):
self.kwargs = dict(
duration=4,
frequency_domain_source_model=bilby.gw.source.lal_binary_black_hole,
sampling_frequency=2048,
)
def tearDown(self):
del self.kwargs
def test_spin_reference_enumeration(self):
"""
Verify that the value of the reference enumerator hasn't changed by comparing
against a known approximant.
"""
self.assertEqual(
lalsimulation.SimInspiralGetSpinFreqFromApproximant(lalsimulation.SEOBNRv3),
bilby.gw.waveform_generator.LALCBCWaveformGenerator.LAL_SIM_INSPIRAL_SPINS_FLOW,
)
def test_create_waveform_generator_non_precessing(self):
self.kwargs["waveform_arguments"] = dict(
minimum_frequency=20.0,
reference_frequency=50.0,
waveform_approximant="TaylorF2",
)
wfg = bilby.gw.waveform_generator.LALCBCWaveformGenerator(**self.kwargs)
self.assertDictEqual(
wfg.waveform_arguments,
dict(
minimum_frequency=20.0,
reference_frequency=50.0,
waveform_approximant="TaylorF2",
),
)
def test_create_waveform_generator_eob_succeeds(self):
self.kwargs["waveform_arguments"] = dict(
minimum_frequency=20.0,
reference_frequency=20.0,
waveform_approximant="SEOBNRv3",
)
wfg = bilby.gw.waveform_generator.LALCBCWaveformGenerator(**self.kwargs)
self.assertDictEqual(
wfg.waveform_arguments,
dict(
minimum_frequency=20.0,
reference_frequency=20.0,
waveform_approximant="SEOBNRv3",
),
)
def test_create_waveform_generator_eob_fails(self):
self.kwargs["waveform_arguments"] = dict(
minimum_frequency=20.0,
reference_frequency=50.0,
waveform_approximant="SEOBNRv3",
)
with self.assertRaises(ValueError):
_ = bilby.gw.waveform_generator.LALCBCWaveformGenerator(**self.kwargs)
class TestSetters(unittest.TestCase):
def setUp(self):
self.waveform_generator = bilby.gw.waveform_generator.WaveformGenerator(
......@@ -259,7 +323,7 @@ class TestFrequencyDomainStrainMethod(unittest.TestCase):
del self.simulation_parameters
def test_parameter_conversion_is_called(self):
self.waveform_generator.parameter_conversion = MagicMock(
self.waveform_generator.parameter_conversion = mock.MagicMock(
side_effect=KeyError("test")
)
with self.assertRaises(KeyError):
......@@ -328,7 +392,7 @@ class TestFrequencyDomainStrainMethod(unittest.TestCase):
)
def test_key_popping(self):
self.waveform_generator.parameter_conversion = MagicMock(
self.waveform_generator.parameter_conversion = mock.MagicMock(
return_value=(
dict(
amplitude=1e-21,
......@@ -374,42 +438,42 @@ class TestFrequencyDomainStrainMethod(unittest.TestCase):
def test_frequency_domain_caching_and_using_time_domain_strain_without_parameters(
self,
):
original_waveform = self.waveform_generator.frequency_domain_strain(
parameters=self.simulation_parameters
)
new_waveform = self.waveform_generator.time_domain_strain()
self.assertNotEqual(original_waveform, new_waveform)
self.assertFalse(_test_caching_different_domain(
self.waveform_generator.frequency_domain_strain,
self.waveform_generator.time_domain_strain,
self.simulation_parameters,
None,
))
def test_frequency_domain_caching_and_using_time_domain_strain_with_parameters(
self,
):
original_waveform = self.waveform_generator.frequency_domain_strain(
parameters=self.simulation_parameters
)
new_waveform = self.waveform_generator.time_domain_strain(
parameters=self.simulation_parameters
)
self.assertNotEqual(original_waveform, new_waveform)
self.assertFalse(_test_caching_different_domain(
self.waveform_generator.frequency_domain_strain,
self.waveform_generator.time_domain_strain,
self.simulation_parameters,
self.simulation_parameters,
))
def test_time_domain_caching_and_using_frequency_domain_strain_without_parameters(
self,
):
original_waveform = self.waveform_generator.time_domain_strain(
parameters=self.simulation_parameters
)
new_waveform = self.waveform_generator.frequency_domain_strain()
self.assertNotEqual(original_waveform, new_waveform)
self.assertFalse(_test_caching_different_domain(
self.waveform_generator.time_domain_strain,
self.waveform_generator.frequency_domain_strain,
self.simulation_parameters,
None,
))
def test_time_domain_caching_and_using_frequency_domain_strain_with_parameters(
self,
):
original_waveform = self.waveform_generator.time_domain_strain(
parameters=self.simulation_parameters
)
new_waveform = self.waveform_generator.frequency_domain_strain(
parameters=self.simulation_parameters
)
self.assertNotEqual(original_waveform, new_waveform)
self.assertFalse(_test_caching_different_domain(
self.waveform_generator.time_domain_strain,
self.waveform_generator.frequency_domain_strain,
self.simulation_parameters,
self.simulation_parameters,
))
def test_frequency_domain_caching_changing_model(self):
original_waveform = self.waveform_generator.frequency_domain_strain(
......@@ -465,7 +529,7 @@ class TestTimeDomainStrainMethod(unittest.TestCase):
del self.simulation_parameters
def test_parameter_conversion_is_called(self):
self.waveform_generator.parameter_conversion = MagicMock(
self.waveform_generator.parameter_conversion = mock.MagicMock(
side_effect=KeyError("test")
)
with self.assertRaises(KeyError):
......@@ -538,7 +602,7 @@ class TestTimeDomainStrainMethod(unittest.TestCase):
)
def test_key_popping(self):
self.waveform_generator.parameter_conversion = MagicMock(
self.waveform_generator.parameter_conversion = mock.MagicMock(
return_value=(
dict(
amplitude=1e-2,
......@@ -584,42 +648,51 @@ class TestTimeDomainStrainMethod(unittest.TestCase):
def test_frequency_domain_caching_and_using_time_domain_strain_without_parameters(
self,
):
original_waveform = self.waveform_generator.frequency_domain_strain(
parameters=self.simulation_parameters
)
new_waveform = self.waveform_generator.time_domain_strain()
self.assertNotEqual(original_waveform, new_waveform)
self.assertFalse(_test_caching_different_domain(
self.waveform_generator.frequency_domain_strain,
self.waveform_generator.time_domain_strain,
self.simulation_parameters,
None,
))
def test_frequency_domain_caching_and_using_time_domain_strain_with_parameters(
self,
):
original_waveform = self.waveform_generator.frequency_domain_strain(
parameters=self.simulation_parameters
)
new_waveform = self.waveform_generator.time_domain_strain(
parameters=self.simulation_parameters
)
self.assertNotEqual(original_waveform, new_waveform)
self.assertFalse(_test_caching_different_domain(
self.waveform_generator.frequency_domain_strain,
self.waveform_generator.time_domain_strain,
self.simulation_parameters,
self.simulation_parameters,
))
def test_time_domain_caching_and_using_frequency_domain_strain_without_parameters(
self,
):
original_waveform = self.waveform_generator.time_domain_strain(
parameters=self.simulation_parameters
)
new_waveform = self.waveform_generator.frequency_domain_strain()
self.assertNotEqual(original_waveform, new_waveform)
self.assertFalse(_test_caching_different_domain(
self.waveform_generator.time_domain_strain,
self.waveform_generator.frequency_domain_strain,
self.simulation_parameters,
None,
))
def test_time_domain_caching_and_using_frequency_domain_strain_with_parameters(
self,
):
original_waveform = self.waveform_generator.time_domain_strain(
parameters=self.simulation_parameters
)
new_waveform = self.waveform_generator.frequency_domain_strain(
parameters=self.simulation_parameters
)
self.assertNotEqual(original_waveform, new_waveform)
self.assertFalse(_test_caching_different_domain(
self.waveform_generator.time_domain_strain,
self.waveform_generator.frequency_domain_strain,
self.simulation_parameters,
self.simulation_parameters,
))
def _test_caching_different_domain(func1, func2, params1, params2):
original_waveform = func1(parameters=params1)
new_waveform = func2(parameters=params2)
output = True
for key in original_waveform:
output &= np.array_equal(original_waveform[key], new_waveform[key])
return output
if __name__ == "__main__":
......
import unittest
import numpy as np
import pandas as pd
from parameterized import parameterized
import bilby.hyper as hyp
def _toy_function(data, dataset, self, cls, a, b, c):
return a
class _ToyClassNoVariableNames:
def __call__(self, a, b, c):
return a
class _ToyClassVariableNames:
variable_names = ["a", "b", "c"]
def __call__(self, **kwargs):
return kwargs.get("a", 1)
class TestHyperLikelihood(unittest.TestCase):
def setUp(self):
self.keys = ["a", "b", "c"]
......@@ -38,6 +57,18 @@ class TestHyperLikelihood(unittest.TestCase):
)
self.assertTrue(np.isnan(like.evidence_factor))
@parameterized.expand([
("func", _toy_function),
("class_no_names", _ToyClassNoVariableNames()),
("class_with_names", _ToyClassVariableNames()),
])
def test_get_function_parameters(self, _, model):
expected = dict(a=1, b=2, c=3)
model = hyp.model.Model([model])
model.parameters.update(expected)
result = model._get_function_parameters(model.models[0])
self.assertDictEqual(expected, result)
def test_len_samples_with_max_samples(self):
like = hyp.likelihood.HyperparameterLikelihood(
self.posteriors,
......
"""
Tests the number of packages imported with a top-level :code:`import bilby`
statement.
"""
import sys
import bilby # noqa
......
import matplotlib
matplotlib.use("Agg")
matplotlib.use("Agg") # noqa
import glob
import importlib.util
import unittest
import os
import parameterized
import pytest
import shutil
import logging
# Required to run the tests
from past.builtins import execfile
import bilby.core.utils
# Imported to ensure the examples run
import numpy as np # noqa: F401
import inspect # noqa: F401
bilby.core.utils.command_line_args.clean = True
core_examples = glob.glob("examples/core_examples/*.py")
core_examples += glob.glob("examples/core_examples/*/*.py")
core_args = [(fname.split("/")[-1][:-3], fname) for fname in core_examples]
bilby.core.utils.command_line_args.bilby_test_mode = True
gw_examples = [
"examples/gw_examples/injection_examples/fast_tutorial.py",
"examples/gw_examples/data_examples/GW150914.py",
]
gw_args = [(fname.split("/")[-1][:-3], fname) for fname in gw_examples]
def _execute_file(name, fname):
dname, fname = os.path.split(fname)
old_directory = os.getcwd()
os.chdir(dname)
spec = importlib.util.spec_from_file_location(name, fname)
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
os.chdir(old_directory)
class ExampleTest(unittest.TestCase):
......@@ -23,6 +40,17 @@ class ExampleTest(unittest.TestCase):
dir_path = os.path.dirname(os.path.realpath(__file__))
dir_path = os.path.abspath(os.path.join(dir_path, os.path.pardir))
def setUp(self):
self.init_dir = os.getcwd()
def tearDown(self):
if os.path.isdir(self.outdir):
try:
shutil.rmtree(self.outdir)
except OSError:
logging.warning("{} not removed after tests".format(self.outdir))
os.chdir(self.init_dir)
@classmethod
def setUpClass(cls):
if os.path.isdir(cls.outdir):
......@@ -39,25 +67,20 @@ class ExampleTest(unittest.TestCase):
except OSError:
logging.warning("{} not removed prior to tests".format(cls.outdir))
def test_examples(self):
@parameterized.parameterized.expand(core_args)
def test_core_examples(self, name, fname):
""" Loop over examples to check they run """
examples = [
"examples/core_examples/linear_regression.py",
"examples/core_examples/linear_regression_unknown_noise.py",
]
for filename in examples:
print("Testing {}".format(filename))
execfile(filename)
def test_gw_examples(self):
bilby.core.utils.command_line_args.bilby_test_mode = False
ignore = ["15d_gaussian"]
if any([item in fname for item in ignore]):
pytest.skip()
_execute_file(name, fname)
@parameterized.parameterized.expand(gw_args)
def test_gw_examples(self, name, fname):
""" Loop over examples to check they run """
examples = [
"examples/gw_examples/injection_examples/fast_tutorial.py",
"examples/gw_examples/data_examples/GW150914.py",
]
for filename in examples:
print("Testing {}".format(filename))
execfile(filename)
bilby.core.utils.command_line_args.bilby_test_mode = True
_execute_file(name, fname)
if __name__ == "__main__":
......
......@@ -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",
......
import multiprocessing
import os
import sys
import threading
import time
from signal import SIGINT
multiprocessing.set_start_method("fork") # noqa
import unittest
import pytest
from parameterized import parameterized
import shutil
import sys
import bilby
import numpy as np
_sampler_kwargs = dict(
bilby_mcmc=dict(nsamples=200, printdt=1),
cpnest=dict(nlive=100),
dnest4=dict(
max_num_levels=2,
num_steps=10,
new_level_interval=10,
num_per_step=10,
thread_steps=1,
num_particles=50,
max_pool=1,
),
dynesty=dict(nlive=10, sample="acceptance-walk", nact=5, proposals=["diff"]),
dynamic_dynesty=dict(
nlive_init=10,
nlive_batch=10,
dlogz_init=1.0,
maxbatch=0,
maxcall=100,
sample="act-walk",
),
emcee=dict(iterations=1000, nwalkers=10),
kombine=dict(iterations=200, nwalkers=10, autoburnin=False),
nessai=dict(
nlive=100,
poolsize=100,
max_iteration=500,
),
nestle=dict(nlive=100),
ptemcee=dict(
nsamples=100,
nwalkers=50,
burn_in_act=1,
ntemps=1,
frac_threshold=0.5,
),
PTMCMCSampler=dict(Niter=101, burn=100, covUpdate=100, isave=100),
pymc=dict(draws=50, tune=50, n_init=250),
pymultinest=dict(nlive=100),
ultranest=dict(nlive=100, temporary_directory=False),
zeus=dict(nwalkers=10, iterations=100)
)
sampler_imports = dict(
bilby_mcmc="bilby",
dynamic_dynesty="dynesty"
)
no_pool_test = ["dnest4", "pymultinest", "nestle", "ptmcmcsampler", "ultranest", "pymc"]
loaded_samplers = {k: v.load() for k, v in bilby.core.sampler.IMPLEMENTED_SAMPLERS.items()}
def slow_func(x, m, c):
time.sleep(0.01)
return m * x + c
def model(x, m, c):
return m * x + 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.model = lambda x, m, c: m * x + c
self.injection_parameters = dict(m=0.5, c=0.2)
self.sigma = 0.1
self.y = self.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(
self.x, self.y, self.model, self.sigma
self.x, self.y, model, self.sigma
)
self.priors = bilby.core.prior.PriorDict()
self.priors["m"] = bilby.core.prior.Uniform(0, 5, boundary="periodic")
self.priors["c"] = bilby.core.prior.Uniform(-2, 2, boundary="reflective")
self._remove_tree()
bilby.core.utils.check_directory_exists_and_if_not_mkdir("outdir")
@staticmethod
def conversion_function(parameters, likelihood, prior):
converted = parameters.copy()
if "derived" not in converted:
converted["derived"] = converted["m"] * converted["c"]
return converted
def tearDown(self):
del self.likelihood
del self.priors
bilby.core.utils.command_line_args.bilby_test_mode = False
shutil.rmtree("outdir")
def test_run_cpnest(self):
_ = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="cpnest",
nlive=100,
save=False,
resume=False,
)
def test_run_dnest4(self):
_ = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="dnest4",
max_num_levels=2,
num_steps=10,
new_level_interval=10,
num_per_step=10,
thread_steps=1,
num_particles=50,
save=False,
)
def test_run_dynesty(self):
_ = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="dynesty",
nlive=100,
save=False,
)
def test_run_dynamic_dynesty(self):
_ = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="dynamic_dynesty",
nlive_init=100,
nlive_batch=100,
dlogz_init=1.0,
maxbatch=0,
maxcall=100,
bound="single",
save=False,
)
def test_run_emcee(self):
_ = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="emcee",
iterations=1000,
nwalkers=10,
save=False,
)
def test_run_kombine(self):
_ = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="kombine",
iterations=2000,
nwalkers=20,
save=False,
autoburnin=False,
)
def test_run_nestle(self):
_ = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="nestle",
nlive=100,
save=False,
)
def test_run_nessai(self):
_ = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="nessai",
nlive=100,
poolsize=1000,
max_iteration=1000,
save=False,
)
def test_run_pypolychord(self):
pytest.importorskip("pypolychord")
_ = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="pypolychord",
nlive=100,
save=False,
)
def test_run_ptemcee(self):
_ = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="ptemcee",
nsamples=100,
nwalkers=50,
burn_in_act=1,
ntemps=1,
frac_threshold=0.5,
save=False,
)
@pytest.mark.skipif(sys.version_info[1] <= 6, reason="pymc3 is broken in py36")
def test_run_pymc3(self):
_ = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="pymc3",
draws=50,
tune=50,
n_init=250,
save=False,
)
def test_run_pymultinest(self):
_ = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="pymultinest",
nlive=100,
save=False,
)
def test_run_PTMCMCSampler(self):
_ = bilby.run_sampler(
self._remove_tree()
def _remove_tree(self):
try:
shutil.rmtree("outdir")
except OSError:
pass
@parameterized.expand(_sampler_kwargs.keys())
def test_run_sampler_single(self, sampler):
self._run_sampler(sampler, pool_size=1)
@parameterized.expand(_sampler_kwargs.keys())
def test_run_sampler_pool(self, sampler):
self._run_sampler(sampler, pool_size=2)
def _run_sampler(self, sampler, pool_size, **extra_kwargs):
pytest.importorskip(sampler_imports.get(sampler, sampler))
if pool_size > 1 and sampler.lower() in no_pool_test:
pytest.skip(f"{sampler} cannot be parallelized")
bilby.core.utils.check_directory_exists_and_if_not_mkdir("outdir")
kwargs = _sampler_kwargs[sampler]
res = bilby.run_sampler(
likelihood=self.likelihood,
priors=self.priors,
sampler="PTMCMCsampler",
Niter=101,
burn=2,
isave=100,
save=False,
)
def test_run_ultranest(self):
# run using NestedSampler (with nlive specified)
_ = bilby.run_sampler(
likelihood=self.likelihood, priors=self.priors,
sampler="ultranest", nlive=100, save=False,
)
# run using ReactiveNestedSampler (with no nlive given)
_ = bilby.run_sampler(
likelihood=self.likelihood, priors=self.priors,
sampler='ultranest', save=False,
)
def test_run_bilby_mcmc(self):
_ = bilby.run_sampler(
likelihood=self.likelihood, priors=self.priors,
sampler="bilby_mcmc", nsamples=200, save=False,
printdt=1,
)
sampler=sampler,
save="hdf5",
npool=pool_size,
conversion_function=self.conversion_function,
**kwargs,
**extra_kwargs,
)
assert "derived" in res.posterior
if sampler != "dnest4":
assert res.log_likelihood_evaluations is not None
@parameterized.expand(_sampler_kwargs.keys())
def test_interrupt_sampler_single(self, sampler):
self._run_with_signal_handling(sampler, pool_size=1)
@parameterized.expand(_sampler_kwargs.keys())
def test_interrupt_sampler_pool(self, sampler):
self._run_with_signal_handling(sampler, pool_size=2)
def _run_with_signal_handling(self, sampler, pool_size=1):
pytest.importorskip(sampler_imports.get(sampler, sampler))
if loaded_samplers[sampler.lower()].hard_exit:
pytest.skip(f"{sampler} hard exits, can't test signal handling.")
if pool_size > 1 and sampler.lower() in no_pool_test:
pytest.skip(f"{sampler} cannot be parallelized")
if sys.version_info.minor == 8 and sampler.lower == "cpnest":
pytest.skip("Pool interrupting broken for cpnest with py3.8")
pid = os.getpid()
print(sampler)
def trigger_signal():
# You could do something more robust, e.g. wait until port is listening
time.sleep(4)
os.kill(pid, SIGINT)
thread = threading.Thread(target=trigger_signal)
thread.daemon = True
thread.start()
self.likelihood._func = slow_func
with self.assertRaises((SystemExit, KeyboardInterrupt)):
try:
while True:
self._run_sampler(sampler=sampler, pool_size=pool_size, exit_code=5)
except SystemExit as error:
self.assertEqual(error.code, 5)
raise
if __name__ == "__main__":
......
import bilby
import pytest
@pytest.mark.parametrize(
"sampler_name", bilby.core.sampler.IMPLEMENTED_SAMPLERS.keys()
)
def test_sampler_import(sampler_name):
"""
Tests that all of the implemented samplers can be initialized.
Do not test :code:`FakeSampler` since it requires an additional argument.
"""
if sampler_name in ["fake_sampler", "pypolychord"]:
pytest.skip(f"Skipping import test for {sampler_name}")
bilby.core.utils.logger.setLevel("ERROR")
likelihood = bilby.core.likelihood.Likelihood(dict())
priors = bilby.core.prior.PriorDict(dict(a=bilby.core.prior.Uniform(0, 1)))
sampler_class = bilby.core.sampler.IMPLEMENTED_SAMPLERS[sampler_name].load()
sampler = sampler_class(likelihood=likelihood, priors=priors)
assert sampler is not None