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 140 additions and 212 deletions
......@@ -32,15 +32,7 @@ RUN conda install -n ${conda_env} -c conda-forge scikit-image celerite george
# Install dependencies and samplers
RUN pip install corner healpy cython tables
RUN conda install -n ${conda_env} -c conda-forge dynesty emcee nestle ptemcee
RUN conda install -n ${conda_env} -c conda-forge pymultinest ultranest
RUN conda install -n ${conda_env} -c conda-forge cpnest kombine dnest4 zeus-mcmc
RUN conda install -n ${conda_env} -c conda-forge ptmcmcsampler
RUN conda install -n ${conda_env} -c conda-forge pytorch
RUN conda install -n ${conda_env} -c conda-forge theano-pymc
RUN conda install -n ${conda_env} -c conda-forge pymc3
RUN conda install -n ${conda_env} -c conda-forge pymc pymc-base
RUN pip install nessai
RUN conda install -n ${conda_env} dynesty emcee nestle ptemcee pymultinest ultranest cpnest kombine dnest4 zeus-mcmc pytorch pymc nessai ptmcmcsampler -c conda-forge -c pytorch
# Install Polychord
RUN apt-get update --allow-releaseinfo-change
......
......@@ -32,15 +32,7 @@ RUN conda install -n ${conda_env} -c conda-forge scikit-image celerite george
# Install dependencies and samplers
RUN pip install corner healpy cython tables
RUN conda install -n ${conda_env} -c conda-forge dynesty emcee nestle ptemcee
RUN conda install -n ${conda_env} -c conda-forge pymultinest ultranest
RUN conda install -n ${conda_env} -c conda-forge cpnest kombine dnest4 zeus-mcmc
RUN conda install -n ${conda_env} -c conda-forge ptmcmcsampler
RUN conda install -n ${conda_env} -c conda-forge pytorch
RUN conda install -n ${conda_env} -c conda-forge theano-pymc
RUN conda install -n ${conda_env} -c conda-forge pymc3
RUN conda install -n ${conda_env} -c conda-forge pymc pymc-base
RUN pip install nessai
RUN conda install -n ${conda_env} dynesty emcee nestle ptemcee pymultinest ultranest cpnest kombine dnest4 zeus-mcmc pytorch pymc nessai ptmcmcsampler -c conda-forge -c pytorch
# Install Polychord
RUN apt-get update --allow-releaseinfo-change
......
......@@ -3,13 +3,31 @@ from datetime import date
with open("dockerfile-template", "r") as ff:
template = ff.read()
python_versions = [(3, 8), (3, 9)]
python_versions = [(3, 8), (3, 9), (3, 10)]
today = date.today().strftime("%Y%m%d")
conda_sampler_dict = dict(
python38=[
"dynesty", "emcee", "nestle", "ptemcee", "pymultinest", "ultranest",
"cpnest", "kombine", "dnest4", "zeus-mcmc",
"pytorch", "pymc", "nessai", "ptmcmcsampler",
],
python39=[
"dynesty", "emcee", "nestle", "ptemcee", "pymultinest", "ultranest",
"cpnest", "kombine", "dnest4", "zeus-mcmc",
"pytorch", "pymc", "nessai", "ptmcmcsampler",
],
python310=[
"dynesty", "emcee", "nestle", "ptemcee", "pymultinest", "ultranest",
"cpnest", "kombine", "dnest4", "zeus-mcmc",
"pytorch", "pymc", "nessai", "ptmcmcsampler",
]
)
for python_major_version, python_minor_version in python_versions:
key = f"python{python_major_version}{python_minor_version}"
with open(
"v3-dockerfile-test-suite-python"
f"{python_major_version}{python_minor_version}",
f"v3-dockerfile-test-suite-{key}",
"w"
) as ff:
ff.write(
......@@ -19,5 +37,6 @@ for python_major_version, python_minor_version in python_versions:
ff.write(template.format(
date=today,
python_major_version=python_major_version,
python_minor_version=python_minor_version
python_minor_version=python_minor_version,
conda_samplers=" ".join(conda_sampler_dict[key])
))
......@@ -10,7 +10,7 @@ Installation
$ conda install -c conda-forge bilby
Supported python versions: 3.6+.
Supported python versions: 3.8-3.10.
.. tab:: Pip
......@@ -18,7 +18,7 @@ Installation
$ pip install bilby
Supported python versions: 3.6+.
Supported python versions: 3.8-3.10.
This will install all requirements for running :code:`bilby` for general
......@@ -47,7 +47,7 @@ wave inference, please additionally run the following commands.
Install bilby from source
-------------------------
:code:`bilby` is developed and tested with Python 3.6+. In the
:code:`bilby` is developed and tested with Python 3.8-3.10. In the
following, we assume you have a working python installation, `python pip
<https://packaging.python.org/tutorials/installing-packages/#use-pip-for-installing)>`_,
and `git <https://git-scm.com/>`_. See :ref:`installing-python` for our
......@@ -65,6 +65,15 @@ Clone the repository, install the requirements, and then install the software:
Once you have run these steps, you have :code:`bilby` installed. You can now
try to run the examples.
.. note::
The bilby version is determined by the tags in the git repository. Therefore, you may need to run
.. code-block:: console
git fetch --all --tags
to fetch the tags so that when you install from source your version information is up to date.
.. note::
If you do not have a git.ligo account, and receive an error message:
......@@ -116,7 +125,7 @@ file, you can do this from the link above, or run the command
$ wget https://repo.anaconda.com/archive/Anaconda3-5.2.0-Linux-x86_64.sh
this will download an installer for python 3.6, for other versions check
this will download a linux installer for python, for other versions check
the `anaconda page <https://www.anaconda.com/download/#linux>`_.
Then, `run the command
<https://conda.io/docs/user-guide/install/linux.html>`_
......
......@@ -69,7 +69,7 @@ MCMC samplers
- bilby-mcmc :code:`bilby.bilby_mcmc.sampler.Bilby_MCMC`
- emcee :code:`bilby.core.sampler.emcee.Emcee`
- ptemcee :code:`bilby.core.sampler.ptemcee.Ptemcee`
- pymc3 :code:`bilby.core.sampler.pymc3.Pymc3`
- pymc :code:`bilby.core.sampler.pymc.Pymc`
- zeus :code:`bilby.core.sampler.zeus.Zeus`
......
......@@ -11,7 +11,7 @@ import numpy as np
from bilby.core.likelihood import GaussianLikelihood
# A few simple setup steps
label = "linear_regression_pymc3"
label = "linear_regression_pymc"
outdir = "outdir"
bilby.utils.check_directory_exists_and_if_not_mkdir(outdir)
......@@ -58,7 +58,7 @@ priors["c"] = bilby.core.prior.Uniform(-2, 2, "c")
result = bilby.run_sampler(
likelihood=likelihood,
priors=priors,
sampler="pymc3",
sampler="pymc",
injection_parameters=injection_parameters,
outdir=outdir,
draws=2000,
......
......@@ -11,10 +11,10 @@ would give equivalent results as using the pre-defined 'Gaussian Likelihood'
import bilby
import matplotlib.pyplot as plt
import numpy as np
import pymc3 as pm
import pymc as pm
# A few simple setup steps
label = "linear_regression_pymc3_custom_likelihood"
label = "linear_regression_pymc_custom_likelihood"
outdir = "outdir"
bilby.utils.check_directory_exists_and_if_not_mkdir(outdir)
......@@ -50,7 +50,7 @@ fig.savefig("{}/{}_data.png".format(outdir, label))
# Parameter estimation: we now define a Gaussian Likelihood class relevant for
# our model.
class GaussianLikelihoodPyMC3(bilby.core.likelihood.GaussianLikelihood):
class GaussianLikelihoodPyMC(bilby.core.likelihood.GaussianLikelihood):
def __init__(self, x, y, sigma, func):
"""
A general Gaussian likelihood - the parameters are inferred from the
......@@ -68,45 +68,44 @@ class GaussianLikelihoodPyMC3(bilby.core.likelihood.GaussianLikelihood):
will require a prior and will be sampled over (unless a fixed
value is given).
"""
super(GaussianLikelihoodPyMC3, self).__init__(x=x, y=y, func=func, sigma=sigma)
super(GaussianLikelihoodPyMC, self).__init__(x=x, y=y, func=func, sigma=sigma)
def log_likelihood(self, sampler=None):
"""
Parameters
----------
sampler: :class:`bilby.core.sampler.Pymc3`
sampler: :class:`bilby.core.sampler.Pymc`
A Sampler object must be passed containing the prior distributions
and PyMC3 :class:`~pymc3.Model` to use as a context manager.
If this is not passed, the super class is called and the regular
likelihood is evaluated.
"""
from bilby.core.sampler import Pymc3
from bilby.core.sampler import Pymc
if not isinstance(sampler, Pymc3):
print(sampler, type(sampler))
return super(GaussianLikelihoodPyMC3, self).log_likelihood()
if not isinstance(sampler, Pymc):
return super(GaussianLikelihoodPyMC, self).log_likelihood()
if not hasattr(sampler, "pymc3_model"):
raise AttributeError("Sampler has not PyMC3 model attribute")
if not hasattr(sampler, "pymc_model"):
raise AttributeError("Sampler has not PyMC model attribute")
with sampler.pymc3_model:
mdist = sampler.pymc3_priors["m"]
cdist = sampler.pymc3_priors["c"]
with sampler.pymc_model:
mdist = sampler.pymc_priors["m"]
cdist = sampler.pymc_priors["c"]
mu = model(time, mdist, cdist)
# set the likelihood distribution
pm.Normal("likelihood", mu=mu, sd=self.sigma, observed=self.y)
pm.Normal("likelihood", mu=mu, sigma=self.sigma, observed=self.y)
# Now lets instantiate a version of our GaussianLikelihood, giving it
# the time, data and signal model
likelihood = GaussianLikelihoodPyMC3(time, data, sigma, model)
likelihood = GaussianLikelihoodPyMC(time, data, sigma, model)
# Define a custom prior for one of the parameter for use with PyMC3
class PyMC3UniformPrior(bilby.core.prior.Uniform):
# Define a custom prior for one of the parameter for use with PyMC
class PyMCUniformPrior(bilby.core.prior.Uniform):
def __init__(self, minimum, maximum, name=None, latex_label=None):
"""
Uniform prior with bounds (should be equivalent to bilby.prior.Uniform)
......@@ -124,10 +123,10 @@ class PyMC3UniformPrior(bilby.core.prior.Uniform):
float or array to be passed to the superclass.
"""
from bilby.core.sampler import Pymc3
from bilby.core.sampler import Pymc
if not isinstance(sampler, Pymc3):
return super(PyMC3UniformPrior, self).ln_prob(sampler)
if not isinstance(sampler, Pymc):
return super(PyMCUniformPrior, self).ln_prob(sampler)
return pm.Uniform(self.name, lower=self.minimum, upper=self.maximum)
......@@ -136,13 +135,13 @@ class PyMC3UniformPrior(bilby.core.prior.Uniform):
# We make a prior
priors = dict()
priors["m"] = bilby.core.prior.Uniform(0, 5, "m")
priors["c"] = PyMC3UniformPrior(-2, 2, "c")
priors["c"] = PyMCUniformPrior(-2, 2, "c")
# And run sampler
result = bilby.run_sampler(
likelihood=likelihood,
priors=priors,
sampler="pymc3",
sampler="pymc",
draws=1000,
tune=1000,
discard_tuned_samples=True,
......
%% Cell type:markdown id: tags:
# Fitting a model to data with both x and y errors with `Bilby`
Usually when we fit a model to data with a Gaussian Likelihood we assume that we know x values exactly. This is almost never the case. Here we show how to fit a model with errors in both x and y.
Since we are using a very simple model we will use the `nestle` sampler.
This can be installed using
```console
$ conda install -c conda-forge nestle
```
or
```console
$ pip install nestle
```
%% Cell type:code id: tags:
```
import bilby
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
```
%% Cell type:markdown id: tags:
### Simulate data
First we create the data and plot it
%% Cell type:code id: tags:
```
# define our model, a line
def model(x, m, c, **kwargs):
y = m * x + c
return y
# make a function to create and plot our data
def make_data(points, m, c, xerr, yerr, seed):
np.random.seed(int(seed))
xtrue = np.linspace(0, 100, points)
ytrue = model(x=xtrue, m=m, c=c)
xerr = xerr * np.random.randn(points)
yerr = yerr * np.random.randn(points)
xobs = xtrue + xerr
yobs = ytrue + yerr
xerr_vals = xerr * np.random.randn(points)
yerr_vals = yerr * np.random.randn(points)
xobs = xtrue + xerr_vals
yobs = ytrue + yerr_vals
plt.errorbar(xobs, yobs, xerr=xerr, yerr=yerr, fmt="x")
plt.errorbar(xtrue, ytrue, yerr=yerr, color="black", alpha=0.5)
plt.xlim(0, 100)
plt.show()
plt.close()
data = {
"xtrue": xtrue,
"ytrue": ytrue,
"xobs": xobs,
"yobs": yobs,
"xerr": xerr,
"yerr": yerr,
}
return data
data = make_data(points=30, m=5, c=10, xerr=5, yerr=5, seed=123)
```
%% Cell type:markdown id: tags:
### Define our prior and sampler settings
Now lets set up the prior and bilby output directory/sampler settings
%% Cell type:code id: tags:
```
# setting up bilby priors
priors = dict(
m=bilby.core.prior.Uniform(0, 30, "m"), c=bilby.core.prior.Uniform(0, 30, "c")
)
sampler_kwargs = dict(priors=priors, sampler="nestle", nlive=1000, outdir="outdir", verbose=False)
sampler_kwargs = dict(priors=priors, sampler="bilby_mcmc", nsamples=1000, printdt=5, outdir="outdir", verbose=False, clean=True)
```
%% Cell type:markdown id: tags:
### Fit with exactly known x-values
Our first step is to recover the straight line using a simple Gaussian Likelihood that only takes into account the y errors. Under the assumption we know x exactly. In this case, we pass in xtrue for x
%% Cell type:code id: tags:
```
known_x = bilby.core.likelihood.GaussianLikelihood(
x=data["xtrue"], y=data["yobs"], func=model, sigma=data["yerr"]
)
result_known_x = bilby.run_sampler(
likelihood=known_x,
label="known_x",
**sampler_kwargs,
)
```
%% Cell type:code id: tags:
```
_ = result_known_x.plot_corner(truth=dict(m=5, c=10), titles=True, save=False)
plt.show()
plt.close()
```
%% Cell type:markdown id: tags:
### Fit with unmodeled uncertainty in the x-values
As expected this is easy to recover and the sampler does a good job. However this was made too easy - by passing in the 'true' values of x. Lets see what happens when we pass in the observed values of x
%% Cell type:code id: tags:
```
incorrect_x = bilby.core.likelihood.GaussianLikelihood(
x=data["xobs"], y=data["yobs"], func=model, sigma=data["yerr"]
)
result_incorrect_x = bilby.run_sampler(
likelihood=incorrect_x,
label="incorrect_x",
**sampler_kwargs,
)
```
%% Cell type:code id: tags:
```
_ = result_incorrect_x.plot_corner(truth=dict(m=5, c=10), titles=True, save=False)
plt.show()
plt.close()
```
%% Cell type:markdown id: tags:
### Fit with modeled uncertainty in x-values
This is not good as there is unmodelled uncertainty in our `x` values.
Getting around this requires marginalisation of the true x values or sampling over them.
See discussion in section 7 of https://arxiv.org/pdf/1008.4686.pdf.
For this, we will have to define a new likelihood class.
By subclassing the base `bilby.core.likelihood.Likelihood` class we can do this fairly simply.
%% Cell type:code id: tags:
```
class GaussianLikelihoodUncertainX(bilby.core.likelihood.Likelihood):
def __init__(self, xobs, yobs, xerr, yerr, function):
"""
Parameters
----------
xobs, yobs: array_like
The data to analyse
xerr, yerr: array_like
The standard deviation of the noise
function:
The python function to fit to the data
"""
super(GaussianLikelihoodUncertainX, self).__init__(dict())
self.xobs = xobs
self.yobs = yobs
self.yerr = yerr
self.xerr = xerr
self.function = function
def log_likelihood(self):
variance = (self.xerr * self.parameters["m"]) ** 2 + self.yerr**2
model_y = self.function(self.xobs, **self.parameters)
residual = self.yobs - model_y
ll = -0.5 * np.sum(residual**2 / variance + np.log(variance))
return -0.5 * np.sum(residual**2 / variance + np.log(variance))
```
%% Cell type:code id: tags:
```
gaussian_unknown_x = GaussianLikelihoodUncertainX(
xobs=data["xobs"],
yobs=data["yobs"],
xerr=data["xerr"],
yerr=data["yerr"],
function=model,
)
result_unknown_x = bilby.run_sampler(
likelihood=gaussian_unknown_x,
label="unknown_x",
**sampler_kwargs,
)
```
%% Cell type:code id: tags:
```
_ = result_unknown_x.plot_corner(truth=dict(m=5, c=10), titles=True, save=False)
plt.show()
plt.close()
```
%% Cell type:markdown id: tags:
Success! The inferred posterior is consistent with the true values.
......
......@@ -3,7 +3,7 @@ dynesty
emcee
nestle
ptemcee
pymc3>=3.6
pymc>=4.0.0
pymultinest
kombine
ultranest>=3.0.0
......
......@@ -87,6 +87,7 @@ setup(
classifiers=[
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
......
......@@ -165,29 +165,33 @@ class TestProposals(TestBaseProposals):
def test_NF_proposal(self):
priors = self.create_priors()
chain = self.create_chain(10000)
prop = proposals.NormalizingFlowProposal(priors, first_fit=10000)
prop.steps_since_refit = 9999
start = time.time()
p, w = prop(chain)
dt = time.time() - start
print(f"Training for {prop.__class__.__name__} took dt~{dt:0.2g} [s]")
self.assertTrue(prop.trained)
self.proposal_check(prop)
if proposals.NormalizingFlowProposal.check_dependencies():
prop = proposals.NormalizingFlowProposal(priors, first_fit=10000)
prop.steps_since_refit = 9999
start = time.time()
p, w = prop(chain)
dt = time.time() - start
print(f"Training for {prop.__class__.__name__} took dt~{dt:0.2g} [s]")
self.assertTrue(prop.trained)
self.proposal_check(prop)
else:
print("nflows not installed, unable to test NormalizingFlowProposal")
def test_NF_proposal_15D(self):
ndim = 15
priors = self.create_priors(ndim)
chain = self.create_chain(10000, ndim=ndim)
prop = proposals.NormalizingFlowProposal(priors, first_fit=10000)
prop.steps_since_refit = 9999
start = time.time()
p, w = prop(chain)
dt = time.time() - start
print(f"Training for {prop.__class__.__name__} took dt~{dt:0.2g} [s]")
self.assertTrue(prop.trained)
self.proposal_check(prop, ndim=ndim)
if proposals.NormalizingFlowProposal.check_dependencies():
prop = proposals.NormalizingFlowProposal(priors, first_fit=10000)
prop.steps_since_refit = 9999
start = time.time()
p, w = prop(chain)
dt = time.time() - start
print(f"Training for {prop.__class__.__name__} took dt~{dt:0.2g} [s]")
self.assertTrue(prop.trained)
self.proposal_check(prop, ndim=ndim)
else:
print("nflows not installed, unable to test NormalizingFlowProposal")
if __name__ == "__main__":
......
......@@ -3,7 +3,7 @@
import re
import subprocess
special_cases = ["plasky", "thomas", "mj-will"]
special_cases = ["plasky", "thomas", "mj-will", "richard"]
AUTHORS_list = []
with open("AUTHORS.md", "r") as f:
AUTHORS_list = " ".join([line for line in f]).lower()
......
......@@ -21,6 +21,7 @@ class TestNessai(unittest.TestCase):
plot=False,
skip_import_verification=True,
sampling_seed=150914,
npool=None, # TODO: remove when support for nessai<0.7.0 is dropped
)
self.expected = self.sampler.default_kwargs
self.expected['output'] = 'outdir/label_nessai/'
......@@ -59,10 +60,13 @@ class TestNessai(unittest.TestCase):
assert self.expected["seed"] == 150914
def test_npool_max_threads(self):
# TODO: remove when support for nessai<0.7.0 is dropped
expected = self.expected.copy()
expected["n_pool"] = None
expected["max_threads"] = 1
new_kwargs = self.sampler.kwargs.copy()
new_kwargs["n_pool"] = 1
new_kwargs["max_threads"] = 1
self.sampler.kwargs = new_kwargs
self.assertDictEqual(expected, self.sampler.kwargs)
......
import unittest
from unittest.mock import MagicMock
import pytest
import bilby
@pytest.mark.xfail(
raises=AttributeError,
reason="Dependency issue with pymc3 causes attribute error on import",
)
class TestPyMC3(unittest.TestCase):
class TestPyMC(unittest.TestCase):
def setUp(self):
self.likelihood = MagicMock()
self.priors = bilby.core.prior.PriorDict(
dict(a=bilby.core.prior.Uniform(0, 1), b=bilby.core.prior.Uniform(0, 1))
)
self.sampler = bilby.core.sampler.Pymc3(
self.sampler = bilby.core.sampler.Pymc(
self.likelihood,
self.priors,
outdir="outdir",
......@@ -37,9 +31,8 @@ class TestPyMC3(unittest.TestCase):
step=None,
init="auto",
n_init=200000,
start=None,
initvals=None,
trace=None,
chain_idx=0,
chains=2,
cores=1,
tune=500,
......@@ -61,9 +54,8 @@ class TestPyMC3(unittest.TestCase):
step=None,
init="auto",
n_init=200000,
start=None,
initvals=None,
trace=None,
chain_idx=0,
chains=2,
cores=1,
tune=500,
......
......@@ -138,81 +138,56 @@ class TestInterferometerGeometry(unittest.TestCase):
self.geometry.latitude = 0
self.assertTrue(np.array_equal(self.geometry.y, np.array([1])))
def test_detector_tensor_without_update(self):
_ = self.geometry.detector_tensor
with mock.patch("numpy.einsum") as m:
m.return_value = 1
expected = np.array(
[
[-9.24529394e-06, 1.02425803e-04, 3.24550668e-04],
[1.02425803e-04, 1.37390844e-03, -8.61137566e-03],
[3.24550668e-04, -8.61137566e-03, -1.36466315e-03],
]
)
self.assertTrue(np.allclose(expected, self.geometry.detector_tensor))
def test_detector_tensor_with_x_azimuth_update(self):
_ = self.geometry.detector_tensor
with mock.patch("numpy.einsum") as m:
m.return_value = 1
self.geometry.xarm_azimuth = 1
self.assertEqual(0, self.geometry.detector_tensor)
original = self.geometry.detector_tensor
self.geometry.xarm_azimuth += 1
self.assertNotEqual(np.max(abs(self.geometry.detector_tensor - original)), 0)
def test_detector_tensor_with_y_azimuth_update(self):
_ = self.geometry.detector_tensor
with mock.patch("numpy.einsum") as m:
m.return_value = 1
self.geometry.yarm_azimuth = 1
self.assertEqual(0, self.geometry.detector_tensor)
original = self.geometry.detector_tensor
self.geometry.yarm_azimuth += 1
self.assertNotEqual(np.max(abs(self.geometry.detector_tensor - original)), 0)
def test_detector_tensor_with_x_tilt_update(self):
_ = self.geometry.detector_tensor
with mock.patch("numpy.einsum") as m:
m.return_value = 1
self.geometry.xarm_tilt = 1
self.assertEqual(0, self.geometry.detector_tensor)
original = self.geometry.detector_tensor
self.geometry.xarm_tilt += 1
self.assertNotEqual(np.max(abs(self.geometry.detector_tensor - original)), 0)
def test_detector_tensor_with_y_tilt_update(self):
_ = self.geometry.detector_tensor
with mock.patch("numpy.einsum") as m:
m.return_value = 1
self.geometry.yarm_tilt = 1
self.assertEqual(0, self.geometry.detector_tensor)
original = self.geometry.detector_tensor
self.geometry.yarm_tilt += 1
self.assertNotEqual(np.max(abs(self.geometry.detector_tensor - original)), 0)
def test_detector_tensor_with_longitude_update(self):
with mock.patch("numpy.einsum") as m:
m.return_value = 1
self.geometry.longitude = 1
self.assertEqual(0, self.geometry.detector_tensor)
original = self.geometry.detector_tensor
self.geometry.longitude += 1
self.assertNotEqual(np.max(abs(self.geometry.detector_tensor - original)), 0)
def test_detector_tensor_with_latitude_update(self):
with mock.patch("numpy.einsum") as m:
_ = self.geometry.detector_tensor
m.return_value = 1
self.geometry.latitude = 1
self.assertEqual(self.geometry.detector_tensor, 0)
original = self.geometry.detector_tensor
self.geometry.latitude += 1
self.assertNotEqual(np.max(abs(self.geometry.detector_tensor - original)), 0)
def test_unit_vector_along_arm_default(self):
with self.assertRaises(ValueError):
self.geometry.unit_vector_along_arm("z")
def test_unit_vector_along_arm_x(self):
with mock.patch("numpy.array") as m:
m.return_value = 1
self.geometry.xarm_tilt = 0
self.geometry.xarm_azimuth = 0
self.geometry.yarm_tilt = 0
self.geometry.yarm_azimuth = 90
self.assertAlmostEqual(self.geometry.unit_vector_along_arm("x"), 1)
self.geometry.longitude = 0
self.geometry.latitude = 0
self.geometry.xarm_tilt = 0
self.geometry.xarm_azimuth = 0
arm = self.geometry.unit_vector_along_arm("x")
self.assertTrue(np.allclose(arm, np.array([0, 1, 0])))
def test_unit_vector_along_arm_y(self):
with mock.patch("numpy.array") as m:
m.return_value = 1
self.geometry.xarm_tilt = 0
self.geometry.xarm_azimuth = 90
self.geometry.yarm_tilt = 0
self.geometry.yarm_azimuth = 180
self.assertAlmostEqual(self.geometry.unit_vector_along_arm("y"), -1)
self.geometry.longitude = 0
self.geometry.latitude = 0
self.geometry.yarm_tilt = 0
self.geometry.yarm_azimuth = 90
arm = self.geometry.unit_vector_along_arm("y")
print(arm)
self.assertTrue(np.allclose(arm, np.array([0, 0, 1])))
def test_repr(self):
expected = (
......
......@@ -97,21 +97,6 @@ class TestInterferometer(unittest.TestCase):
def test_max_freq_setting(self):
self.assertEqual(self.ifo.strain_data.maximum_frequency, self.maximum_frequency)
def test_antenna_response_default(self):
with mock.patch("bilby.gw.utils.get_polarization_tensor") as m:
with mock.patch("numpy.einsum") as n:
m.return_value = 0
n.return_value = 1
self.assertEqual(self.ifo.antenna_response(234, 52, 54, 76, "plus"), 1)
def test_antenna_response_einsum(self):
with mock.patch("bilby.gw.utils.get_polarization_tensor") as m:
m.return_value = np.ones((3, 3))
self.assertAlmostEqual(
self.ifo.antenna_response(234, 52, 54, 76, "plus"),
self.ifo.detector_tensor.sum(),
)
def test_get_detector_response_default_behaviour(self):
self.ifo.antenna_response = mock.MagicMock(return_value=1)
self.ifo.time_delay_from_geocenter = mock.MagicMock(return_value=0)
......@@ -315,16 +300,6 @@ class TestInterferometer(unittest.TestCase):
with self.assertRaises(ValueError):
self.ifo.inject_signal(injection_polarizations=None, parameters=None)
def test_time_delay_from_geocenter(self):
with mock.patch("bilby.gw.utils.time_delay_geocentric") as m:
m.return_value = 1
self.assertEqual(self.ifo.time_delay_from_geocenter(1, 2, 3), 1)
def test_vertex_position_geocentric(self):
with mock.patch("bilby.gw.utils.get_vertex_position_geocentric") as m:
m.return_value = 1
self.assertEqual(self.ifo.vertex_position_geocentric(), 1)
def test_optimal_snr_squared(self):
"""
Merely checks parameters are given in the right order and the frequency
......
......@@ -222,6 +222,7 @@ class TestGWTransient(unittest.TestCase):
waveform_generator_class=self.waveform_generator.__class__,
waveform_arguments=self.waveform_generator.waveform_arguments,
frequency_domain_source_model=self.waveform_generator.frequency_domain_source_model,
time_domain_source_model=self.waveform_generator.time_domain_source_model,
parameter_conversion=self.waveform_generator.parameter_conversion,
sampling_frequency=self.waveform_generator.sampling_frequency,
duration=self.waveform_generator.duration,
......
......@@ -36,34 +36,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])
......@@ -132,7 +104,7 @@ 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.assertEqual(strain.name, channel)
self.assertTrue(np.all(strain.value == data[:-1]))
# Check reading with time limits
......
"""
Tests the number of packages imported with a top-level :code:`import bilby`
statement.
"""
import sys
import bilby # noqa
......