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
Commits on Source (73)
Showing
with 824 additions and 492 deletions
...@@ -10,11 +10,13 @@ ...@@ -10,11 +10,13 @@
# before the next stage begins # before the next stage begins
stages: stages:
- initial
- test - test
- docs
- deploy - deploy
.test-python: &test-python .test-python: &test-python
stage: test stage: initial
image: python image: python
before_script: before_script:
# this is required because pytables doesn't use a wheel on py37 # this is required because pytables doesn't use a wheel on py37
...@@ -43,7 +45,8 @@ basic-3.7: ...@@ -43,7 +45,8 @@ basic-3.7:
# test example on python 3.7 # test example on python 3.7
python-3.7: python-3.7:
stage: test stage: test
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen needs: ["basic-3.7", "precommits-py3.7"]
image: quay.io/bilbydev/v2-dockerfile-test-suite-python37
script: script:
- python -m pip install . - python -m pip install .
...@@ -55,21 +58,38 @@ python-3.7: ...@@ -55,21 +58,38 @@ python-3.7:
- coverage html - coverage html
- coverage-badge -o coverage_badge.svg -f - coverage-badge -o coverage_badge.svg -f
artifacts:
paths:
- coverage_badge.svg
- htmlcov/
docs:
stage: docs
needs: ["basic-3.7"]
image: quay.io/bilbydev/v2-dockerfile-test-suite-python37
script:
# Make the documentation # Make the documentation
- apt-get -yqq install pandoc
- python -m pip install .
- cd docs - cd docs
- pip install ipykernel ipython jupyter
- cp ../examples/tutorials/*.ipynb ./
- rm basic_ptmcmc_tutorial.ipynb
- rm compare_samplers.ipynb
- rm visualising_the_results.ipynb
- jupyter nbconvert --to notebook --execute *.ipynb --inplace
- make clean - make clean
- make html - make html
artifacts: artifacts:
paths: paths:
- htmlcov/
- coverage_badge.svg
- docs/_build/html/ - docs/_build/html/
# test example on python 3.8 # test example on python 3.8
python-3.8: python-3.8:
stage: test stage: test
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python38-frozen needs: ["basic-3.7", "precommits-py3.7"]
image: quay.io/bilbydev/v2-dockerfile-test-suite-python38
script: script:
- python -m pip install . - python -m pip install .
...@@ -78,7 +98,8 @@ python-3.8: ...@@ -78,7 +98,8 @@ python-3.8:
# test example on python 3.6 # test example on python 3.6
python-3.6: python-3.6:
stage: test stage: test
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python36-frozen needs: ["basic-3.7", "precommits-py3.7"]
image: quay.io/bilbydev/v2-dockerfile-test-suite-python36
script: script:
- python -m pip install . - python -m pip install .
...@@ -87,7 +108,8 @@ python-3.6: ...@@ -87,7 +108,8 @@ python-3.6:
# test samplers on python 3.7 # test samplers on python 3.7
python-3.7-samplers: python-3.7-samplers:
stage: test stage: test
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen needs: ["basic-3.7", "precommits-py3.7"]
image: quay.io/bilbydev/v2-dockerfile-test-suite-python37
script: script:
- python -m pip install . - python -m pip install .
...@@ -97,7 +119,8 @@ python-3.7-samplers: ...@@ -97,7 +119,8 @@ python-3.7-samplers:
# test samplers on python 3.6 # test samplers on python 3.6
python-3.6-samplers: python-3.6-samplers:
stage: test stage: test
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python36-frozen needs: ["basic-3.7", "precommits-py3.7"]
image: quay.io/bilbydev/v2-dockerfile-test-suite-python36
script: script:
- python -m pip install . - python -m pip install .
...@@ -105,8 +128,8 @@ python-3.6-samplers: ...@@ -105,8 +128,8 @@ python-3.6-samplers:
# Test containers are up to date # Test containers are up to date
containers: containers:
stage: test stage: initial
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen image: quay.io/bilbydev/v2-dockerfile-test-suite-python37
script: script:
- cd containers - cd containers
- python write_dockerfiles.py - python write_dockerfiles.py
...@@ -117,7 +140,7 @@ containers: ...@@ -117,7 +140,7 @@ containers:
# Tests run at a fixed schedule rather than on push # Tests run at a fixed schedule rather than on push
scheduled-python-3.7: scheduled-python-3.7:
stage: test stage: test
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen image: quay.io/bilbydev/v2-dockerfile-test-suite-python37
only: only:
- schedules - schedules
script: script:
...@@ -129,7 +152,7 @@ scheduled-python-3.7: ...@@ -129,7 +152,7 @@ scheduled-python-3.7:
plotting: plotting:
stage: test stage: test
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen image: quay.io/bilbydev/v2-dockerfile-test-suite-python37
only: only:
- schedules - schedules
script: script:
...@@ -139,14 +162,16 @@ plotting: ...@@ -139,14 +162,16 @@ plotting:
- pytest test/gw/plot_test.py - pytest test/gw/plot_test.py
authors: authors:
stage: test stage: initial
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen image: quay.io/bilbydev/v2-dockerfile-test-suite-python37
script: script:
- python test/check_author_list.py - python test/check_author_list.py
pages: pages:
stage: deploy stage: deploy
needs: ["docs", "python-3.7"]
dependencies: dependencies:
- docs
- python-3.7 - python-3.7
script: script:
- mkdir public/ - mkdir public/
...@@ -162,7 +187,7 @@ pages: ...@@ -162,7 +187,7 @@ pages:
deploy_release: deploy_release:
stage: deploy stage: deploy
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen image: quay.io/bilbydev/v2-dockerfile-test-suite-python37
variables: variables:
TWINE_USERNAME: $PYPI_USERNAME TWINE_USERNAME: $PYPI_USERNAME
TWINE_PASSWORD: $PYPI_PASSWORD TWINE_PASSWORD: $PYPI_PASSWORD
...@@ -176,8 +201,8 @@ deploy_release: ...@@ -176,8 +201,8 @@ deploy_release:
precommits-py3.7: precommits-py3.7:
stage: test stage: initial
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen image: quay.io/bilbydev/v2-dockerfile-test-suite-python37
script: script:
- source activate python37 - source activate python37
- mkdir -p .pip37 - mkdir -p .pip37
......
# All notable changes will be documented in this file # All notable changes will be documented in this file
## [1.0.3] 2020-11-23 ## [1.1.0] 2021-03-15
Version 1.1.0 release of bilby
### Added
- Calibration marginalisation using a discrete set of realisations (!856)
- Nessai sampler (!921, !926)
- Capability to sample in aligned spin and spin magnitude (!868)
- Information gain now stored in the result (!907)
- Added option to save result/interferometers as pickle (!925)
- Added functionality to notch data (!898)
- Added LIGO India Aundha (A1) coordinates (!886)
### Changes
- Fixed periodic keys not working when constrained priors are present in pymultinest (!927)
- Some changes to reweighting likelihoods (!851)
- `CBCPriorDict` is now a `ConditionalPriorDict` (!868)
- Fixed hyper PE example (!910)
- Pinned numpy and pandas version number (!916)
- Fixed an issue with GPS times in `cpnest`
- `deepdish` is now longer a requirement since it lost its support (!925)
- Removed annoying warning message due to use of `newcommand` in latex (!924)
- Interpolation should be slightly faster now because we now access interpolation libraries more directly (!917, !923)
- Documentation now builds properly (!915)
- Fixed a bug caused by `loaded_modules_dict` (!920)
- `_ref_dist` is an attribute now which speeds up distance marginalised runs slightly (!913)
- Cache normalisation for `PriorDict` objects without `Constraint` priors (!914)
- Removed some deprecated `__future__` imports (!911)
- Fixed the behaviour of `plot_waveform_posterior` to use representative samples (!894)
- Uses `tqdm.auto` in some samplers now for better progress bars (!895)
- Fixed the correction of the epoch in time domain waveforms when using a segment duration that is not a power of two (!909)
- Fixed `ultranest` from failing
- Fixed issues with plotting failing in tests (!904)
- Changed the CI to run on auto-built images (!899)
- Resolved a `matplotlib` error occuring at `dynesty` checkpoint plots (!902)
- Fixed the multidimensional Gaussian example (!901)
- Now allow any lal dictionary option and added a numerical relativity file (!896)
- Fixed the likelihood count in `dynesty` (!853)
- Changed the ordering of keyword arguments for the `Sine` and `Cosine` constructors (!892)
## [1.0.4] 2020-11-23
Version 1.0.4 release of bilby Version 1.0.4 release of bilby
### Added ### Added
......
...@@ -16,7 +16,6 @@ https://lscsoft.docs.ligo.org/bilby/installation.html. ...@@ -16,7 +16,6 @@ https://lscsoft.docs.ligo.org/bilby/installation.html.
""" """
from __future__ import absolute_import
import sys import sys
from . import core, gw, hyper from . import core, gw, hyper
......
from __future__ import absolute_import
from . import grid, likelihood, prior, result, sampler, series, utils from . import grid, likelihood, prior, result, sampler, series, utils
from __future__ import division
import numpy as np import numpy as np
import os import os
import json import json
...@@ -16,7 +14,7 @@ def grid_file_name(outdir, label, gzip=False): ...@@ -16,7 +14,7 @@ def grid_file_name(outdir, label, gzip=False):
""" Returns the standard filename used for a grid file """ Returns the standard filename used for a grid file
Parameters Parameters
---------- ==========
outdir: str outdir: str
Name of the output directory Name of the output directory
label: str label: str
...@@ -25,7 +23,7 @@ def grid_file_name(outdir, label, gzip=False): ...@@ -25,7 +23,7 @@ def grid_file_name(outdir, label, gzip=False):
Set to True to append `.gz` to the extension for saving in gzipped format Set to True to append `.gz` to the extension for saving in gzipped format
Returns Returns
------- =======
str: File name of the output file str: File name of the output file
""" """
if gzip: if gzip:
...@@ -41,7 +39,7 @@ class Grid(object): ...@@ -41,7 +39,7 @@ class Grid(object):
""" """
Parameters Parameters
---------- ==========
likelihood: bilby.likelihood.Likelihood likelihood: bilby.likelihood.Likelihood
priors: bilby.prior.PriorDict priors: bilby.prior.PriorDict
grid_size: int, list, dict grid_size: int, list, dict
...@@ -114,7 +112,7 @@ class Grid(object): ...@@ -114,7 +112,7 @@ class Grid(object):
Marginalize over a list of parameters. Marginalize over a list of parameters.
Parameters Parameters
---------- ==========
log_array: array_like log_array: array_like
A :class:`numpy.ndarray` of log likelihood/posterior values. A :class:`numpy.ndarray` of log likelihood/posterior values.
parameters: list, str parameters: list, str
...@@ -125,7 +123,7 @@ class Grid(object): ...@@ -125,7 +123,7 @@ class Grid(object):
the set of parameter to *not* marginalize over. the set of parameter to *not* marginalize over.
Returns Returns
------- =======
out_array: array_like out_array: array_like
An array containing the marginalized log likelihood/posterior. An array containing the marginalized log likelihood/posterior.
""" """
...@@ -164,7 +162,7 @@ class Grid(object): ...@@ -164,7 +162,7 @@ class Grid(object):
Marginalize the log likelihood/posterior over a single given parameter. Marginalize the log likelihood/posterior over a single given parameter.
Parameters Parameters
---------- ==========
log_array: array_like log_array: array_like
A :class:`numpy.ndarray` of log likelihood/posterior values. A :class:`numpy.ndarray` of log likelihood/posterior values.
name: str name: str
...@@ -173,7 +171,7 @@ class Grid(object): ...@@ -173,7 +171,7 @@ class Grid(object):
A list of parameter names that have not been marginalized over. A list of parameter names that have not been marginalized over.
Returns Returns
------- =======
out: array_like out: array_like
An array containing the marginalized log likelihood/posterior. An array containing the marginalized log likelihood/posterior.
""" """
...@@ -220,14 +218,14 @@ class Grid(object): ...@@ -220,14 +218,14 @@ class Grid(object):
ln likelihood will be fully marginalized over. ln likelihood will be fully marginalized over.
Parameters Parameters
---------- ==========
parameters: str, list, optional parameters: str, list, optional
Name of, or list of names of, the parameter(s) to marginalize over. Name of, or list of names of, the parameter(s) to marginalize over.
not_parameters: str, optional not_parameters: str, optional
Name of, or list of names of, the parameter(s) to not marginalize over. Name of, or list of names of, the parameter(s) to not marginalize over.
Returns Returns
------- =======
array-like: array-like:
The marginalized ln likelihood. The marginalized ln likelihood.
""" """
...@@ -241,14 +239,14 @@ class Grid(object): ...@@ -241,14 +239,14 @@ class Grid(object):
ln posterior will be fully marginalized over. ln posterior will be fully marginalized over.
Parameters Parameters
---------- ==========
parameters: str, list, optional parameters: str, list, optional
Name of, or list of names of, the parameter(s) to marginalize over. Name of, or list of names of, the parameter(s) to marginalize over.
not_parameters: str, optional not_parameters: str, optional
Name of, or list of names of, the parameter(s) to not marginalize over. Name of, or list of names of, the parameter(s) to not marginalize over.
Returns Returns
------- =======
array-like: array-like:
The marginalized ln posterior. The marginalized ln posterior.
""" """
...@@ -262,14 +260,14 @@ class Grid(object): ...@@ -262,14 +260,14 @@ class Grid(object):
likelihood will be fully marginalized over. likelihood will be fully marginalized over.
Parameters Parameters
---------- ==========
parameters: str, list, optional parameters: str, list, optional
Name of, or list of names of, the parameter(s) to marginalize over. Name of, or list of names of, the parameter(s) to marginalize over.
not_parameters: str, optional not_parameters: str, optional
Name of, or list of names of, the parameter(s) to not marginalize over. Name of, or list of names of, the parameter(s) to not marginalize over.
Returns Returns
------- =======
array-like: array-like:
The marginalized likelihood. The marginalized likelihood.
""" """
...@@ -285,14 +283,14 @@ class Grid(object): ...@@ -285,14 +283,14 @@ class Grid(object):
posterior will be fully marginalized over. posterior will be fully marginalized over.
Parameters Parameters
---------- ==========
parameters: str, list, optional parameters: str, list, optional
Name of, or list of names of, the parameter(s) to marginalize over. Name of, or list of names of, the parameter(s) to marginalize over.
not_parameters: str, optional not_parameters: str, optional
Name of, or list of names of, the parameter(s) to not marginalize over. Name of, or list of names of, the parameter(s) to not marginalize over.
Returns Returns
------- =======
array-like: array-like:
The marginalized posterior. The marginalized posterior.
""" """
...@@ -377,7 +375,7 @@ class Grid(object): ...@@ -377,7 +375,7 @@ class Grid(object):
Writes the Grid to a file. Writes the Grid to a file.
Parameters Parameters
---------- ==========
filename: str, optional filename: str, optional
Filename to write to (overwrites the default) Filename to write to (overwrites the default)
overwrite: bool, optional overwrite: bool, optional
...@@ -420,7 +418,7 @@ class Grid(object): ...@@ -420,7 +418,7 @@ class Grid(object):
""" Read in a saved .json grid file """ Read in a saved .json grid file
Parameters Parameters
---------- ==========
filename: str filename: str
If given, try to load from this filename If given, try to load from this filename
outdir, label: str outdir, label: str
...@@ -431,11 +429,11 @@ class Grid(object): ...@@ -431,11 +429,11 @@ class Grid(object):
extension) extension)
Returns Returns
------- =======
grid: bilby.core.grid.Grid grid: bilby.core.grid.Grid
Raises Raises
------- =======
ValueError: If no filename is given and either outdir or label is None ValueError: If no filename is given and either outdir or label is None
If no bilby.core.grid.Grid is found in the path If no bilby.core.grid.Grid is found in the path
......
from __future__ import division, print_function
import copy import copy
import numpy as np import numpy as np
...@@ -14,7 +13,7 @@ class Likelihood(object): ...@@ -14,7 +13,7 @@ class Likelihood(object):
"""Empty likelihood class to be subclassed by other likelihoods """Empty likelihood class to be subclassed by other likelihoods
Parameters Parameters
---------- ==========
parameters: dict parameters: dict
A dictionary of the parameter names and associated values A dictionary of the parameter names and associated values
""" """
...@@ -29,7 +28,7 @@ class Likelihood(object): ...@@ -29,7 +28,7 @@ class Likelihood(object):
""" """
Returns Returns
------- =======
float float
""" """
return np.nan return np.nan
...@@ -38,7 +37,7 @@ class Likelihood(object): ...@@ -38,7 +37,7 @@ class Likelihood(object):
""" """
Returns Returns
------- =======
float float
""" """
return np.nan return np.nan
...@@ -47,7 +46,7 @@ class Likelihood(object): ...@@ -47,7 +46,7 @@ class Likelihood(object):
"""Difference between log likelihood and noise log likelihood """Difference between log likelihood and noise log likelihood
Returns Returns
------- =======
float float
""" """
return self.log_likelihood() - self.noise_log_likelihood() return self.log_likelihood() - self.noise_log_likelihood()
...@@ -72,7 +71,7 @@ class ZeroLikelihood(Likelihood): ...@@ -72,7 +71,7 @@ class ZeroLikelihood(Likelihood):
""" A special test-only class which already returns zero likelihood """ A special test-only class which already returns zero likelihood
Parameters Parameters
---------- ==========
likelihood: bilby.core.likelihood.Likelihood likelihood: bilby.core.likelihood.Likelihood
A likelihood object to mimic A likelihood object to mimic
...@@ -99,7 +98,7 @@ class Analytical1DLikelihood(Likelihood): ...@@ -99,7 +98,7 @@ class Analytical1DLikelihood(Likelihood):
parameters are inferred from the arguments of function parameters are inferred from the arguments of function
Parameters Parameters
---------- ==========
x, y: array_like x, y: array_like
The data to analyse The data to analyse
func: func:
...@@ -175,7 +174,7 @@ class GaussianLikelihood(Analytical1DLikelihood): ...@@ -175,7 +174,7 @@ class GaussianLikelihood(Analytical1DLikelihood):
parameters are inferred from the arguments of function parameters are inferred from the arguments of function
Parameters Parameters
---------- ==========
x, y: array_like x, y: array_like
The data to analyse The data to analyse
func: func:
...@@ -236,7 +235,7 @@ class PoissonLikelihood(Analytical1DLikelihood): ...@@ -236,7 +235,7 @@ class PoissonLikelihood(Analytical1DLikelihood):
inferred from the arguments of function, which provides a rate. inferred from the arguments of function, which provides a rate.
Parameters Parameters
---------- ==========
x: array_like x: array_like
A dependent variable at which the Poisson rates will be calculated A dependent variable at which the Poisson rates will be calculated
...@@ -292,7 +291,7 @@ class ExponentialLikelihood(Analytical1DLikelihood): ...@@ -292,7 +291,7 @@ class ExponentialLikelihood(Analytical1DLikelihood):
An exponential likelihood function. An exponential likelihood function.
Parameters Parameters
---------- ==========
x, y: array_like x, y: array_like
The data to analyse The data to analyse
...@@ -339,7 +338,7 @@ class StudentTLikelihood(Analytical1DLikelihood): ...@@ -339,7 +338,7 @@ class StudentTLikelihood(Analytical1DLikelihood):
https://en.wikipedia.org/wiki/Student%27s_t-distribution#Generalized_Student's_t-distribution https://en.wikipedia.org/wiki/Student%27s_t-distribution#Generalized_Student's_t-distribution
Parameters Parameters
---------- ==========
x, y: array_like x, y: array_like
The data to analyse The data to analyse
func: func:
...@@ -411,7 +410,7 @@ class Multinomial(Likelihood): ...@@ -411,7 +410,7 @@ class Multinomial(Likelihood):
""" """
Parameters Parameters
---------- ==========
data: array-like data: array-like
The number of objects in each class The number of objects in each class
n_dimensions: int n_dimensions: int
...@@ -455,7 +454,7 @@ class AnalyticalMultidimensionalCovariantGaussian(Likelihood): ...@@ -455,7 +454,7 @@ class AnalyticalMultidimensionalCovariantGaussian(Likelihood):
with known analytic solution. with known analytic solution.
Parameters Parameters
---------- ==========
mean: array_like mean: array_like
Array with the mean values of distribution Array with the mean values of distribution
cov: array_like cov: array_like
...@@ -485,7 +484,7 @@ class AnalyticalMultidimensionalBimodalCovariantGaussian(Likelihood): ...@@ -485,7 +484,7 @@ class AnalyticalMultidimensionalBimodalCovariantGaussian(Likelihood):
with known analytic solution. with known analytic solution.
Parameters Parameters
---------- ==========
mean_1: array_like mean_1: array_like
Array with the mean value of the first mode Array with the mean value of the first mode
mean_2: array_like mean_2: array_like
...@@ -524,7 +523,7 @@ class JointLikelihood(Likelihood): ...@@ -524,7 +523,7 @@ class JointLikelihood(Likelihood):
set consistently set consistently
Parameters Parameters
---------- ==========
*likelihoods: bilby.core.likelihood.Likelihood *likelihoods: bilby.core.likelihood.Likelihood
likelihoods to be combined parsed as arguments likelihoods to be combined parsed as arguments
""" """
......
...@@ -13,7 +13,7 @@ class DeltaFunction(Prior): ...@@ -13,7 +13,7 @@ class DeltaFunction(Prior):
"""Dirac delta function prior, this always returns peak. """Dirac delta function prior, this always returns peak.
Parameters Parameters
---------- ==========
peak: float peak: float
Peak value of the delta function Peak value of the delta function
name: str name: str
...@@ -33,11 +33,11 @@ class DeltaFunction(Prior): ...@@ -33,11 +33,11 @@ class DeltaFunction(Prior):
"""Rescale everything to the peak with the correct shape. """Rescale everything to the peak with the correct shape.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
float: Rescaled probability, equivalent to peak float: Rescaled probability, equivalent to peak
""" """
self.test_valid_for_rescaling(val) self.test_valid_for_rescaling(val)
...@@ -47,11 +47,11 @@ class DeltaFunction(Prior): ...@@ -47,11 +47,11 @@ class DeltaFunction(Prior):
"""Return the prior probability of val """Return the prior probability of val
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: np.inf if val = peak, 0 otherwise Union[float, array_like]: np.inf if val = peak, 0 otherwise
""" """
...@@ -69,7 +69,7 @@ class PowerLaw(Prior): ...@@ -69,7 +69,7 @@ class PowerLaw(Prior):
"""Power law with bounds and alpha, spectral index """Power law with bounds and alpha, spectral index
Parameters Parameters
---------- ==========
alpha: float alpha: float
Power law exponent parameter Power law exponent parameter
minimum: float minimum: float
...@@ -97,12 +97,12 @@ class PowerLaw(Prior): ...@@ -97,12 +97,12 @@ class PowerLaw(Prior):
This maps to the inverse CDF. This has been analytically solved for this case. This maps to the inverse CDF. This has been analytically solved for this case.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Uniform probability Uniform probability
Returns Returns
------- =======
Union[float, array_like]: Rescaled probability Union[float, array_like]: Rescaled probability
""" """
self.test_valid_for_rescaling(val) self.test_valid_for_rescaling(val)
...@@ -116,11 +116,11 @@ class PowerLaw(Prior): ...@@ -116,11 +116,11 @@ class PowerLaw(Prior):
"""Return the prior probability of val """Return the prior probability of val
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
float: Prior probability of val float: Prior probability of val
""" """
if self.alpha == -1: if self.alpha == -1:
...@@ -134,11 +134,11 @@ class PowerLaw(Prior): ...@@ -134,11 +134,11 @@ class PowerLaw(Prior):
"""Return the logarithmic prior probability of val """Return the logarithmic prior probability of val
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
float: float:
""" """
...@@ -170,7 +170,7 @@ class Uniform(Prior): ...@@ -170,7 +170,7 @@ class Uniform(Prior):
"""Uniform prior with bounds """Uniform prior with bounds
Parameters Parameters
---------- ==========
minimum: float minimum: float
See superclass See superclass
maximum: float maximum: float
...@@ -195,12 +195,12 @@ class Uniform(Prior): ...@@ -195,12 +195,12 @@ class Uniform(Prior):
This maps to the inverse CDF. This has been analytically solved for this case. This maps to the inverse CDF. This has been analytically solved for this case.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Uniform probability Uniform probability
Returns Returns
------- =======
Union[float, array_like]: Rescaled probability Union[float, array_like]: Rescaled probability
""" """
self.test_valid_for_rescaling(val) self.test_valid_for_rescaling(val)
...@@ -210,11 +210,11 @@ class Uniform(Prior): ...@@ -210,11 +210,11 @@ class Uniform(Prior):
"""Return the prior probability of val """Return the prior probability of val
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
float: Prior probability of val float: Prior probability of val
""" """
return ((val >= self.minimum) & (val <= self.maximum)) / (self.maximum - self.minimum) return ((val >= self.minimum) & (val <= self.maximum)) / (self.maximum - self.minimum)
...@@ -223,11 +223,11 @@ class Uniform(Prior): ...@@ -223,11 +223,11 @@ class Uniform(Prior):
"""Return the log prior probability of val """Return the log prior probability of val
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
float: log probability of val float: log probability of val
""" """
return xlogy(1, (val >= self.minimum) & (val <= self.maximum)) - xlogy(1, self.maximum - self.minimum) return xlogy(1, (val >= self.minimum) & (val <= self.maximum)) - xlogy(1, self.maximum - self.minimum)
...@@ -246,7 +246,7 @@ class LogUniform(PowerLaw): ...@@ -246,7 +246,7 @@ class LogUniform(PowerLaw):
"""Log-Uniform prior with bounds """Log-Uniform prior with bounds
Parameters Parameters
---------- ==========
minimum: float minimum: float
See superclass See superclass
maximum: float maximum: float
...@@ -278,7 +278,7 @@ class SymmetricLogUniform(Prior): ...@@ -278,7 +278,7 @@ class SymmetricLogUniform(Prior):
maximum]. maximum].
Parameters Parameters
---------- ==========
minimum: float minimum: float
See superclass See superclass
maximum: float maximum: float
...@@ -303,12 +303,12 @@ class SymmetricLogUniform(Prior): ...@@ -303,12 +303,12 @@ class SymmetricLogUniform(Prior):
This maps to the inverse CDF. This has been analytically solved for this case. This maps to the inverse CDF. This has been analytically solved for this case.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Uniform probability Uniform probability
Returns Returns
------- =======
Union[float, array_like]: Rescaled probability Union[float, array_like]: Rescaled probability
""" """
self.test_valid_for_rescaling(val) self.test_valid_for_rescaling(val)
...@@ -330,11 +330,11 @@ class SymmetricLogUniform(Prior): ...@@ -330,11 +330,11 @@ class SymmetricLogUniform(Prior):
"""Return the prior probability of val """Return the prior probability of val
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
float: Prior probability of val float: Prior probability of val
""" """
val = np.abs(val) val = np.abs(val)
...@@ -345,11 +345,11 @@ class SymmetricLogUniform(Prior): ...@@ -345,11 +345,11 @@ class SymmetricLogUniform(Prior):
"""Return the logarithmic prior probability of val """Return the logarithmic prior probability of val
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
float: float:
""" """
...@@ -370,12 +370,12 @@ class SymmetricLogUniform(Prior): ...@@ -370,12 +370,12 @@ class SymmetricLogUniform(Prior):
class Cosine(Prior): class Cosine(Prior):
def __init__(self, name=None, latex_label=None, unit=None, def __init__(self, minimum=-np.pi / 2, maximum=np.pi / 2, name=None,
minimum=-np.pi / 2, maximum=np.pi / 2, boundary=None): latex_label=None, unit=None, boundary=None):
"""Cosine prior with bounds """Cosine prior with bounds
Parameters Parameters
---------- ==========
minimum: float minimum: float
See superclass See superclass
maximum: float maximum: float
...@@ -389,8 +389,8 @@ class Cosine(Prior): ...@@ -389,8 +389,8 @@ class Cosine(Prior):
boundary: str boundary: str
See superclass See superclass
""" """
super(Cosine, self).__init__(name=name, latex_label=latex_label, unit=unit, super(Cosine, self).__init__(minimum=minimum, maximum=maximum, name=name,
minimum=minimum, maximum=maximum, boundary=boundary) latex_label=latex_label, unit=unit, boundary=boundary)
def rescale(self, val): def rescale(self, val):
""" """
...@@ -406,11 +406,11 @@ class Cosine(Prior): ...@@ -406,11 +406,11 @@ class Cosine(Prior):
"""Return the prior probability of val. Defined over [-pi/2, pi/2]. """Return the prior probability of val. Defined over [-pi/2, pi/2].
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
float: Prior probability of val float: Prior probability of val
""" """
return np.cos(val) / 2 * self.is_in_prior_range(val) return np.cos(val) / 2 * self.is_in_prior_range(val)
...@@ -425,12 +425,12 @@ class Cosine(Prior): ...@@ -425,12 +425,12 @@ class Cosine(Prior):
class Sine(Prior): class Sine(Prior):
def __init__(self, name=None, latex_label=None, unit=None, minimum=0, def __init__(self, minimum=0, maximum=np.pi, name=None,
maximum=np.pi, boundary=None): latex_label=None, unit=None, boundary=None):
"""Sine prior with bounds """Sine prior with bounds
Parameters Parameters
---------- ==========
minimum: float minimum: float
See superclass See superclass
maximum: float maximum: float
...@@ -444,8 +444,8 @@ class Sine(Prior): ...@@ -444,8 +444,8 @@ class Sine(Prior):
boundary: str boundary: str
See superclass See superclass
""" """
super(Sine, self).__init__(name=name, latex_label=latex_label, unit=unit, super(Sine, self).__init__(minimum=minimum, maximum=maximum, name=name,
minimum=minimum, maximum=maximum, boundary=boundary) latex_label=latex_label, unit=unit, boundary=boundary)
def rescale(self, val): def rescale(self, val):
""" """
...@@ -461,11 +461,11 @@ class Sine(Prior): ...@@ -461,11 +461,11 @@ class Sine(Prior):
"""Return the prior probability of val. Defined over [0, pi]. """Return the prior probability of val. Defined over [0, pi].
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
return np.sin(val) / 2 * self.is_in_prior_range(val) return np.sin(val) / 2 * self.is_in_prior_range(val)
...@@ -484,7 +484,7 @@ class Gaussian(Prior): ...@@ -484,7 +484,7 @@ class Gaussian(Prior):
"""Gaussian prior with mean mu and width sigma """Gaussian prior with mean mu and width sigma
Parameters Parameters
---------- ==========
mu: float mu: float
Mean of the Gaussian prior Mean of the Gaussian prior
sigma: sigma:
...@@ -507,7 +507,7 @@ class Gaussian(Prior): ...@@ -507,7 +507,7 @@ class Gaussian(Prior):
'Rescale' a sample from the unit line element to the appropriate Gaussian prior. 'Rescale' a sample from the unit line element to the appropriate Gaussian prior.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
This maps to the inverse CDF. This has been analytically solved for this case. This maps to the inverse CDF. This has been analytically solved for this case.
...@@ -519,11 +519,11 @@ class Gaussian(Prior): ...@@ -519,11 +519,11 @@ class Gaussian(Prior):
"""Return the prior probability of val. """Return the prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
return np.exp(-(self.mu - val) ** 2 / (2 * self.sigma ** 2)) / (2 * np.pi) ** 0.5 / self.sigma return np.exp(-(self.mu - val) ** 2 / (2 * self.sigma ** 2)) / (2 * np.pi) ** 0.5 / self.sigma
...@@ -532,11 +532,11 @@ class Gaussian(Prior): ...@@ -532,11 +532,11 @@ class Gaussian(Prior):
"""Return the Log prior probability of val. """Return the Log prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
...@@ -559,7 +559,7 @@ class TruncatedGaussian(Prior): ...@@ -559,7 +559,7 @@ class TruncatedGaussian(Prior):
https://en.wikipedia.org/wiki/Truncated_normal_distribution https://en.wikipedia.org/wiki/Truncated_normal_distribution
Parameters Parameters
---------- ==========
mu: float mu: float
Mean of the Gaussian prior Mean of the Gaussian prior
sigma: sigma:
...@@ -587,7 +587,7 @@ class TruncatedGaussian(Prior): ...@@ -587,7 +587,7 @@ class TruncatedGaussian(Prior):
""" Calculates the proper normalisation of the truncated Gaussian """ Calculates the proper normalisation of the truncated Gaussian
Returns Returns
------- =======
float: Proper normalisation of the truncated Gaussian float: Proper normalisation of the truncated Gaussian
""" """
return (erf((self.maximum - self.mu) / 2 ** 0.5 / self.sigma) - erf( return (erf((self.maximum - self.mu) / 2 ** 0.5 / self.sigma) - erf(
...@@ -607,11 +607,11 @@ class TruncatedGaussian(Prior): ...@@ -607,11 +607,11 @@ class TruncatedGaussian(Prior):
"""Return the prior probability of val. """Return the prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
float: Prior probability of val float: Prior probability of val
""" """
return np.exp(-(self.mu - val) ** 2 / (2 * self.sigma ** 2)) / (2 * np.pi) ** 0.5 \ return np.exp(-(self.mu - val) ** 2 / (2 * self.sigma ** 2)) / (2 * np.pi) ** 0.5 \
...@@ -635,7 +635,7 @@ class HalfGaussian(TruncatedGaussian): ...@@ -635,7 +635,7 @@ class HalfGaussian(TruncatedGaussian):
"""A Gaussian with its mode at zero, and truncated to only be positive. """A Gaussian with its mode at zero, and truncated to only be positive.
Parameters Parameters
---------- ==========
sigma: float sigma: float
See superclass See superclass
name: str name: str
...@@ -663,7 +663,7 @@ class LogNormal(Prior): ...@@ -663,7 +663,7 @@ class LogNormal(Prior):
https://en.wikipedia.org/wiki/Log-normal_distribution https://en.wikipedia.org/wiki/Log-normal_distribution
Parameters Parameters
---------- ==========
mu: float mu: float
Mean of the Gaussian prior Mean of the Gaussian prior
sigma: sigma:
...@@ -699,11 +699,11 @@ class LogNormal(Prior): ...@@ -699,11 +699,11 @@ class LogNormal(Prior):
"""Returns the prior probability of val. """Returns the prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
if isinstance(val, (float, int)): if isinstance(val, (float, int)):
...@@ -723,11 +723,11 @@ class LogNormal(Prior): ...@@ -723,11 +723,11 @@ class LogNormal(Prior):
"""Returns the log prior probability of val. """Returns the log prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
if isinstance(val, (float, int)): if isinstance(val, (float, int)):
...@@ -765,7 +765,7 @@ class Exponential(Prior): ...@@ -765,7 +765,7 @@ class Exponential(Prior):
"""Exponential prior with mean mu """Exponential prior with mean mu
Parameters Parameters
---------- ==========
mu: float mu: float
Mean of the Exponential prior Mean of the Exponential prior
name: str name: str
...@@ -794,11 +794,11 @@ class Exponential(Prior): ...@@ -794,11 +794,11 @@ class Exponential(Prior):
"""Return the prior probability of val. """Return the prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
if isinstance(val, (float, int)): if isinstance(val, (float, int)):
...@@ -815,11 +815,11 @@ class Exponential(Prior): ...@@ -815,11 +815,11 @@ class Exponential(Prior):
"""Returns the log prior probability of val. """Returns the log prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
if isinstance(val, (float, int)): if isinstance(val, (float, int)):
...@@ -853,7 +853,7 @@ class StudentT(Prior): ...@@ -853,7 +853,7 @@ class StudentT(Prior):
https://en.wikipedia.org/wiki/Student%27s_t-distribution#Generalized_Student's_t-distribution https://en.wikipedia.org/wiki/Student%27s_t-distribution#Generalized_Student's_t-distribution
Parameters Parameters
---------- ==========
df: float df: float
Number of degrees of freedom for distribution Number of degrees of freedom for distribution
mu: float mu: float
...@@ -902,11 +902,11 @@ class StudentT(Prior): ...@@ -902,11 +902,11 @@ class StudentT(Prior):
"""Return the prior probability of val. """Return the prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
return np.exp(self.ln_prob(val)) return np.exp(self.ln_prob(val))
...@@ -915,11 +915,11 @@ class StudentT(Prior): ...@@ -915,11 +915,11 @@ class StudentT(Prior):
"""Returns the log prior probability of val. """Returns the log prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
return gammaln(0.5 * (self.df + 1)) - gammaln(0.5 * self.df)\ return gammaln(0.5 * (self.df + 1)) - gammaln(0.5 * self.df)\
...@@ -941,7 +941,7 @@ class Beta(Prior): ...@@ -941,7 +941,7 @@ class Beta(Prior):
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html
Parameters Parameters
---------- ==========
alpha: float alpha: float
first shape parameter first shape parameter
beta: float beta: float
...@@ -981,11 +981,11 @@ class Beta(Prior): ...@@ -981,11 +981,11 @@ class Beta(Prior):
"""Return the prior probability of val. """Return the prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
return np.exp(self.ln_prob(val)) return np.exp(self.ln_prob(val))
...@@ -994,11 +994,11 @@ class Beta(Prior): ...@@ -994,11 +994,11 @@ class Beta(Prior):
"""Returns the log prior probability of val. """Returns the log prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
_ln_prob = xlogy(self.alpha - 1, val - self.minimum) + xlogy(self.beta - 1, self.maximum - val)\ _ln_prob = xlogy(self.alpha - 1, val - self.minimum) + xlogy(self.beta - 1, self.maximum - val)\
...@@ -1039,7 +1039,7 @@ class Logistic(Prior): ...@@ -1039,7 +1039,7 @@ class Logistic(Prior):
https://en.wikipedia.org/wiki/Logistic_distribution https://en.wikipedia.org/wiki/Logistic_distribution
Parameters Parameters
---------- ==========
mu: float mu: float
Mean of the distribution Mean of the distribution
scale: float scale: float
...@@ -1086,11 +1086,11 @@ class Logistic(Prior): ...@@ -1086,11 +1086,11 @@ class Logistic(Prior):
"""Return the prior probability of val. """Return the prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
return np.exp(self.ln_prob(val)) return np.exp(self.ln_prob(val))
...@@ -1099,11 +1099,11 @@ class Logistic(Prior): ...@@ -1099,11 +1099,11 @@ class Logistic(Prior):
"""Returns the log prior probability of val. """Returns the log prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
return -(val - self.mu) / self.scale -\ return -(val - self.mu) / self.scale -\
...@@ -1120,7 +1120,7 @@ class Cauchy(Prior): ...@@ -1120,7 +1120,7 @@ class Cauchy(Prior):
https://en.wikipedia.org/wiki/Cauchy_distribution https://en.wikipedia.org/wiki/Cauchy_distribution
Parameters Parameters
---------- ==========
alpha: float alpha: float
Location parameter Location parameter
beta: float beta: float
...@@ -1164,11 +1164,11 @@ class Cauchy(Prior): ...@@ -1164,11 +1164,11 @@ class Cauchy(Prior):
"""Return the prior probability of val. """Return the prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
return 1. / self.beta / np.pi / (1. + ((val - self.alpha) / self.beta) ** 2) return 1. / self.beta / np.pi / (1. + ((val - self.alpha) / self.beta) ** 2)
...@@ -1177,11 +1177,11 @@ class Cauchy(Prior): ...@@ -1177,11 +1177,11 @@ class Cauchy(Prior):
"""Return the log prior probability of val. """Return the log prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Log prior probability of val Union[float, array_like]: Log prior probability of val
""" """
return - np.log(self.beta * np.pi) - np.log(1. + ((val - self.alpha) / self.beta) ** 2) return - np.log(self.beta * np.pi) - np.log(1. + ((val - self.alpha) / self.beta) ** 2)
...@@ -1201,7 +1201,7 @@ class Gamma(Prior): ...@@ -1201,7 +1201,7 @@ class Gamma(Prior):
https://en.wikipedia.org/wiki/Gamma_distribution https://en.wikipedia.org/wiki/Gamma_distribution
Parameters Parameters
---------- ==========
k: float k: float
The shape parameter The shape parameter
theta: float theta: float
...@@ -1237,11 +1237,11 @@ class Gamma(Prior): ...@@ -1237,11 +1237,11 @@ class Gamma(Prior):
"""Return the prior probability of val. """Return the prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
return np.exp(self.ln_prob(val)) return np.exp(self.ln_prob(val))
...@@ -1250,11 +1250,11 @@ class Gamma(Prior): ...@@ -1250,11 +1250,11 @@ class Gamma(Prior):
"""Returns the log prior probability of val. """Returns the log prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
if isinstance(val, (float, int)): if isinstance(val, (float, int)):
...@@ -1288,7 +1288,7 @@ class ChiSquared(Gamma): ...@@ -1288,7 +1288,7 @@ class ChiSquared(Gamma):
https://en.wikipedia.org/wiki/Chi-squared_distribution https://en.wikipedia.org/wiki/Chi-squared_distribution
Parameters Parameters
---------- ==========
nu: int nu: int
Number of degrees of freedom Number of degrees of freedom
name: str name: str
...@@ -1324,7 +1324,7 @@ class FermiDirac(Prior): ...@@ -1324,7 +1324,7 @@ class FermiDirac(Prior):
is defined by Equation 22 of [1]_. is defined by Equation 22 of [1]_.
Parameters Parameters
---------- ==========
sigma: float (required) sigma: float (required)
The range over which the attenuation of the distribution happens The range over which the attenuation of the distribution happens
mu: float mu: float
...@@ -1341,7 +1341,7 @@ class FermiDirac(Prior): ...@@ -1341,7 +1341,7 @@ class FermiDirac(Prior):
See superclass See superclass
References References
---------- ==========
.. [1] M. Pitkin, M. Isi, J. Veitch & G. Woan, `arXiv:1705.08978v1 .. [1] M. Pitkin, M. Isi, J. Veitch & G. Woan, `arXiv:1705.08978v1
<https:arxiv.org/abs/1705.08978v1>`_, 2017. <https:arxiv.org/abs/1705.08978v1>`_, 2017.
...@@ -1370,14 +1370,14 @@ class FermiDirac(Prior): ...@@ -1370,14 +1370,14 @@ class FermiDirac(Prior):
'Rescale' a sample from the unit line element to the appropriate Fermi-Dirac prior. 'Rescale' a sample from the unit line element to the appropriate Fermi-Dirac prior.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
This maps to the inverse CDF. This has been analytically solved for this case, This maps to the inverse CDF. This has been analytically solved for this case,
see Equation 24 of [1]_. see Equation 24 of [1]_.
References References
---------- ==========
.. [1] M. Pitkin, M. Isi, J. Veitch & G. Woan, `arXiv:1705.08978v1 .. [1] M. Pitkin, M. Isi, J. Veitch & G. Woan, `arXiv:1705.08978v1
<https:arxiv.org/abs/1705.08978v1>`_, 2017. <https:arxiv.org/abs/1705.08978v1>`_, 2017.
...@@ -1404,11 +1404,11 @@ class FermiDirac(Prior): ...@@ -1404,11 +1404,11 @@ class FermiDirac(Prior):
"""Return the prior probability of val. """Return the prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
float: Prior probability of val float: Prior probability of val
""" """
return np.exp(self.ln_prob(val)) return np.exp(self.ln_prob(val))
...@@ -1417,11 +1417,11 @@ class FermiDirac(Prior): ...@@ -1417,11 +1417,11 @@ class FermiDirac(Prior):
"""Return the log prior probability of val. """Return the log prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Log prior probability of val Union[float, array_like]: Log prior probability of val
""" """
......
...@@ -20,7 +20,7 @@ class Prior(object): ...@@ -20,7 +20,7 @@ class Prior(object):
""" Implements a Prior object """ Implements a Prior object
Parameters Parameters
---------- ==========
name: str, optional name: str, optional
Name associated with prior. Name associated with prior.
latex_label: str, optional latex_label: str, optional
...@@ -57,27 +57,58 @@ class Prior(object): ...@@ -57,27 +57,58 @@ class Prior(object):
"""Overrides the __call__ special method. Calls the sample method. """Overrides the __call__ special method. Calls the sample method.
Returns Returns
------- =======
float: The return value of the sample method. float: The return value of the sample method.
""" """
return self.sample() return self.sample()
def __eq__(self, other): def __eq__(self, other):
"""
Test equality of two prior objects.
Returns true iff:
- The class of the two priors are the same
- Both priors have the same keys in the __dict__ attribute
- The instantiation arguments match
We don't check that all entries the the __dict__ attribute
are equal as some attributes are variable for conditional
priors.
Parameters
==========
other: Prior
The prior to compare with
Returns
=======
bool
Whether the priors are equivalent
Notes
=====
A special case is made for :code `scipy.stats.beta`: instances.
It may be possible to remove this as we now only check instantiation
arguments.
"""
if self.__class__ != other.__class__: if self.__class__ != other.__class__:
return False return False
if sorted(self.__dict__.keys()) != sorted(other.__dict__.keys()): if sorted(self.__dict__.keys()) != sorted(other.__dict__.keys()):
return False return False
for key in self.__dict__: this_dict = self.get_instantiation_dict()
other_dict = other.get_instantiation_dict()
for key in this_dict:
if key == "least_recently_sampled": if key == "least_recently_sampled":
# ignore sample drawn from prior in comparison
continue continue
if type(self.__dict__[key]) is np.ndarray: if isinstance(this_dict[key], np.ndarray):
if not np.array_equal(self.__dict__[key], other.__dict__[key]): if not np.array_equal(this_dict[key], other_dict[key]):
return False return False
elif isinstance(self.__dict__[key], type(scipy.stats.beta(1., 1.))): elif isinstance(this_dict[key], type(scipy.stats.beta(1., 1.))):
continue continue
else: else:
if not self.__dict__[key] == other.__dict__[key]: if not this_dict[key] == other_dict[key]:
return False return False
return True return True
...@@ -85,12 +116,12 @@ class Prior(object): ...@@ -85,12 +116,12 @@ class Prior(object):
"""Draw a sample from the prior """Draw a sample from the prior
Parameters Parameters
---------- ==========
size: int or tuple of ints, optional size: int or tuple of ints, optional
See numpy.random.uniform docs See numpy.random.uniform docs
Returns Returns
------- =======
float: A random number between 0 and 1, rescaled to match the distribution of this Prior float: A random number between 0 and 1, rescaled to match the distribution of this Prior
""" """
...@@ -104,12 +135,12 @@ class Prior(object): ...@@ -104,12 +135,12 @@ class Prior(object):
This should be overwritten by each subclass. This should be overwritten by each subclass.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
A random number between 0 and 1 A random number between 0 and 1
Returns Returns
------- =======
None None
""" """
...@@ -119,11 +150,11 @@ class Prior(object): ...@@ -119,11 +150,11 @@ class Prior(object):
"""Return the prior probability of val, this should be overwritten """Return the prior probability of val, this should be overwritten
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
np.nan np.nan
""" """
...@@ -146,11 +177,11 @@ class Prior(object): ...@@ -146,11 +177,11 @@ class Prior(object):
"""Return the prior ln probability of val, this should be overwritten """Return the prior ln probability of val, this should be overwritten
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
np.nan np.nan
""" """
...@@ -160,11 +191,11 @@ class Prior(object): ...@@ -160,11 +191,11 @@ class Prior(object):
"""Returns True if val is in the prior boundaries, zero otherwise """Returns True if val is in the prior boundaries, zero otherwise
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
np.nan np.nan
""" """
...@@ -175,11 +206,11 @@ class Prior(object): ...@@ -175,11 +206,11 @@ class Prior(object):
"""Test if 0 < val < 1 """Test if 0 < val < 1
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Raises Raises
------- =======
ValueError: If val is not between 0 and 1 ValueError: If val is not between 0 and 1
""" """
valarray = np.atleast_1d(val) valarray = np.atleast_1d(val)
...@@ -194,7 +225,7 @@ class Prior(object): ...@@ -194,7 +225,7 @@ class Prior(object):
Works correctly for all child classes Works correctly for all child classes
Returns Returns
------- =======
str: A string representation of this instance str: A string representation of this instance
""" """
...@@ -224,7 +255,7 @@ class Prior(object): ...@@ -224,7 +255,7 @@ class Prior(object):
Returns Returns
------- =======
bool: Whether it's fixed or not! bool: Whether it's fixed or not!
""" """
...@@ -237,7 +268,7 @@ class Prior(object): ...@@ -237,7 +268,7 @@ class Prior(object):
Draws from a set of default labels if no label is given Draws from a set of default labels if no label is given
Returns Returns
------- =======
str: A latex representation for this prior str: A latex representation for this prior
""" """
...@@ -392,17 +423,17 @@ class Prior(object): ...@@ -392,17 +423,17 @@ class Prior(object):
Parameters Parameters
---------- ==========
val: str val: str
The string version of the agument The string version of the agument
Returns Returns
------- =======
val: object val: object
The parsed version of the argument. The parsed version of the argument.
Raises Raises
------ ======
TypeError: TypeError:
If val cannot be parsed as described above. If val cannot be parsed as described above.
""" """
......
...@@ -15,7 +15,7 @@ def conditional_prior_factory(prior_class): ...@@ -15,7 +15,7 @@ def conditional_prior_factory(prior_class):
""" """
Parameters Parameters
---------- ==========
condition_func: func condition_func: func
Functional form of the condition for this prior. The first function argument Functional form of the condition for this prior. The first function argument
has to be a dictionary for the `reference_params` (see below). The following has to be a dictionary for the `reference_params` (see below). The following
...@@ -27,10 +27,14 @@ def conditional_prior_factory(prior_class): ...@@ -27,10 +27,14 @@ def conditional_prior_factory(prior_class):
`p(x|y)` with the boundaries linearly depending on y, then this `p(x|y)` with the boundaries linearly depending on y, then this
could have the following form: could have the following form:
``` .. code-block:: python
def condition_func(reference_params, y):
return dict(minimum=reference_params['minimum'] + y, maximum=reference_params['maximum'] + y) def condition_func(reference_params, y):
``` return dict(
minimum=reference_params['minimum'] + y,
maximum=reference_params['maximum'] + y
)
name: str, optional name: str, optional
See superclass See superclass
latex_label: str, optional latex_label: str, optional
...@@ -61,14 +65,14 @@ def conditional_prior_factory(prior_class): ...@@ -61,14 +65,14 @@ def conditional_prior_factory(prior_class):
"""Draw a sample from the prior """Draw a sample from the prior
Parameters Parameters
---------- ==========
size: int or tuple of ints, optional size: int or tuple of ints, optional
See superclass See superclass
required_variables: required_variables:
Any required variables that this prior depends on Any required variables that this prior depends on
Returns Returns
------- =======
float: See superclass float: See superclass
""" """
...@@ -80,7 +84,7 @@ def conditional_prior_factory(prior_class): ...@@ -80,7 +84,7 @@ def conditional_prior_factory(prior_class):
'Rescale' a sample from the unit line element to the prior. 'Rescale' a sample from the unit line element to the prior.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
See superclass See superclass
required_variables: required_variables:
...@@ -95,7 +99,7 @@ def conditional_prior_factory(prior_class): ...@@ -95,7 +99,7 @@ def conditional_prior_factory(prior_class):
"""Return the prior probability of val. """Return the prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
See superclass See superclass
required_variables: required_variables:
...@@ -103,7 +107,7 @@ def conditional_prior_factory(prior_class): ...@@ -103,7 +107,7 @@ def conditional_prior_factory(prior_class):
Returns Returns
------- =======
float: Prior probability of val float: Prior probability of val
""" """
self.update_conditions(**required_variables) self.update_conditions(**required_variables)
...@@ -113,7 +117,7 @@ def conditional_prior_factory(prior_class): ...@@ -113,7 +117,7 @@ def conditional_prior_factory(prior_class):
"""Return the natural log prior probability of val. """Return the natural log prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
See superclass See superclass
required_variables: required_variables:
...@@ -121,7 +125,7 @@ def conditional_prior_factory(prior_class): ...@@ -121,7 +125,7 @@ def conditional_prior_factory(prior_class):
Returns Returns
------- =======
float: Natural log prior probability of val float: Natural log prior probability of val
""" """
self.update_conditions(**required_variables) self.update_conditions(**required_variables)
...@@ -131,7 +135,7 @@ def conditional_prior_factory(prior_class): ...@@ -131,7 +135,7 @@ def conditional_prior_factory(prior_class):
"""Return the cdf of val. """Return the cdf of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
See superclass See superclass
required_variables: required_variables:
...@@ -139,7 +143,7 @@ def conditional_prior_factory(prior_class): ...@@ -139,7 +143,7 @@ def conditional_prior_factory(prior_class):
Returns Returns
------- =======
float: CDF of val float: CDF of val
""" """
self.update_conditions(**required_variables) self.update_conditions(**required_variables)
...@@ -154,7 +158,7 @@ def conditional_prior_factory(prior_class): ...@@ -154,7 +158,7 @@ def conditional_prior_factory(prior_class):
If no variables are given, the most recently used conditional parameters are kept If no variables are given, the most recently used conditional parameters are kept
Parameters Parameters
---------- ==========
required_variables: required_variables:
Any required variables that this prior depends on. If none are given, Any required variables that this prior depends on. If none are given,
self.reference_params will be used. self.reference_params will be used.
...@@ -217,7 +221,7 @@ def conditional_prior_factory(prior_class): ...@@ -217,7 +221,7 @@ def conditional_prior_factory(prior_class):
Works correctly for all child classes Works correctly for all child classes
Returns Returns
------- =======
str: A string representation of this instance str: A string representation of this instance
""" """
...@@ -234,49 +238,116 @@ def conditional_prior_factory(prior_class): ...@@ -234,49 +238,116 @@ def conditional_prior_factory(prior_class):
return ConditionalPrior return ConditionalPrior
ConditionalBasePrior = conditional_prior_factory(Prior) # Only for testing purposes class ConditionalBasePrior(conditional_prior_factory(Prior)):
ConditionalUniform = conditional_prior_factory(Uniform) pass
ConditionalDeltaFunction = conditional_prior_factory(DeltaFunction)
ConditionalPowerLaw = conditional_prior_factory(PowerLaw)
ConditionalGaussian = conditional_prior_factory(Gaussian) class ConditionalUniform(conditional_prior_factory(Uniform)):
ConditionalLogUniform = conditional_prior_factory(LogUniform) pass
ConditionalSymmetricLogUniform = conditional_prior_factory(SymmetricLogUniform)
ConditionalCosine = conditional_prior_factory(Cosine)
ConditionalSine = conditional_prior_factory(Sine) class ConditionalDeltaFunction(conditional_prior_factory(DeltaFunction)):
ConditionalTruncatedGaussian = conditional_prior_factory(TruncatedGaussian) pass
ConditionalHalfGaussian = conditional_prior_factory(HalfGaussian)
ConditionalLogNormal = conditional_prior_factory(LogNormal)
ConditionalExponential = conditional_prior_factory(Exponential) class ConditionalPowerLaw(conditional_prior_factory(PowerLaw)):
ConditionalStudentT = conditional_prior_factory(StudentT) pass
ConditionalBeta = conditional_prior_factory(Beta)
ConditionalLogistic = conditional_prior_factory(Logistic)
ConditionalCauchy = conditional_prior_factory(Cauchy) class ConditionalGaussian(conditional_prior_factory(Gaussian)):
ConditionalGamma = conditional_prior_factory(Gamma) pass
ConditionalChiSquared = conditional_prior_factory(ChiSquared)
ConditionalFermiDirac = conditional_prior_factory(FermiDirac)
ConditionalInterped = conditional_prior_factory(Interped) class ConditionalLogUniform(conditional_prior_factory(LogUniform)):
pass
class ConditionalSymmetricLogUniform(conditional_prior_factory(SymmetricLogUniform)):
pass
class ConditionalCosine(conditional_prior_factory(Cosine)):
pass
class ConditionalSine(conditional_prior_factory(Sine)):
pass
class ConditionalTruncatedGaussian(conditional_prior_factory(TruncatedGaussian)):
pass
class ConditionalHalfGaussian(conditional_prior_factory(HalfGaussian)):
pass
class ConditionalLogNormal(conditional_prior_factory(LogNormal)):
pass
class ConditionalExponential(conditional_prior_factory(Exponential)):
pass
class ConditionalStudentT(conditional_prior_factory(StudentT)):
pass
class ConditionalBeta(conditional_prior_factory(Beta)):
pass
class ConditionalLogistic(conditional_prior_factory(Logistic)):
pass
class ConditionalCauchy(conditional_prior_factory(Cauchy)):
pass
class ConditionalGamma(conditional_prior_factory(Gamma)):
pass
class ConditionalChiSquared(conditional_prior_factory(ChiSquared)):
pass
class ConditionalFermiDirac(conditional_prior_factory(FermiDirac)):
pass
class ConditionalInterped(conditional_prior_factory(Interped)):
pass
class DirichletElement(ConditionalBeta): class DirichletElement(ConditionalBeta):
""" r"""
Single element in a dirichlet distribution Single element in a dirichlet distribution
The probability scales as The probability scales as
$p(x_order) \propto (x_max - x_order)^(n_dimensions - order - 2)$ .. math::
p(x_n) \propto (x_\max - x_n)^{(N - n - 2)}
for x_order < x_max, where x_max is the sum of x_i for i < order for :math:`x_n < x_\max`, where :math:`x_\max` is the sum of :math:`x_i`
for :math:`i < n`
Examples Examples
-------- ========
n_dimensions = 1: n_dimensions = 1:
p(x_0) \propto 1 ; 0 < x_0 < 1
.. math::
p(x_0) \propto 1 ; 0 < x_0 < 1
n_dimensions = 2: n_dimensions = 2:
p(x_0) \propto (1 - x_0) ; 0 < x_0 < 1 .. math::
p(x_1) \propto 1 ; 0 < x_1 < 1 p(x_0) &\propto (1 - x_0) ; 0 < x_0 < 1
p(x_1) &\propto 1 ; 0 < x_1 < 1
Parameters Parameters
---------- ==========
order: int order: int
Order of this element of the dirichlet distribution. Order of this element of the dirichlet distribution.
n_dimensions: int n_dimensions: int
...@@ -284,9 +355,11 @@ class DirichletElement(ConditionalBeta): ...@@ -284,9 +355,11 @@ class DirichletElement(ConditionalBeta):
label: str label: str
Label for the dirichlet distribution. Label for the dirichlet distribution.
This should be the same for all elements. This should be the same for all elements.
""" """
def __init__(self, order, n_dimensions, label): def __init__(self, order, n_dimensions, label):
""" """
super(DirichletElement, self).__init__( super(DirichletElement, self).__init__(
minimum=0, maximum=1, alpha=1, beta=n_dimensions - order - 1, minimum=0, maximum=1, alpha=1, beta=n_dimensions - order - 1,
name=label + str(order), name=label + str(order),
......
...@@ -3,7 +3,6 @@ from io import open as ioopen ...@@ -3,7 +3,6 @@ from io import open as ioopen
import json import json
import os import os
from future.utils import iteritems
from matplotlib.cbook import flatten from matplotlib.cbook import flatten
import numpy as np import numpy as np
...@@ -19,7 +18,7 @@ class PriorDict(dict): ...@@ -19,7 +18,7 @@ class PriorDict(dict):
""" A dictionary of priors """ A dictionary of priors
Parameters Parameters
---------- ==========
dictionary: Union[dict, str, None] dictionary: Union[dict, str, None]
If given, a dictionary to generate the prior set. If given, a dictionary to generate the prior set.
filename: Union[str, None] filename: Union[str, None]
...@@ -61,12 +60,12 @@ class PriorDict(dict): ...@@ -61,12 +60,12 @@ class PriorDict(dict):
Placeholder parameter conversion function. Placeholder parameter conversion function.
Parameters Parameters
---------- ==========
sample: dict sample: dict
Dictionary to convert Dictionary to convert
Returns Returns
------- =======
sample: dict sample: dict
Same as input Same as input
""" """
...@@ -76,7 +75,7 @@ class PriorDict(dict): ...@@ -76,7 +75,7 @@ class PriorDict(dict):
""" Write the prior distribution to file. """ Write the prior distribution to file.
Parameters Parameters
---------- ==========
outdir: str outdir: str
output directory name output directory name
label: str label: str
...@@ -124,18 +123,20 @@ class PriorDict(dict): ...@@ -124,18 +123,20 @@ class PriorDict(dict):
""" Reads in a prior from a file specification """ Reads in a prior from a file specification
Parameters Parameters
---------- ==========
filename: str filename: str
Name of the file to be read in Name of the file to be read in
Notes Notes
----- =====
Lines beginning with '#' or empty lines will be ignored. Lines beginning with '#' or empty lines will be ignored.
Priors can be loaded from: Priors can be loaded from:
bilby.core.prior as, e.g., foo = Uniform(minimum=0, maximum=1)
floats, e.g., foo = 1 - bilby.core.prior as, e.g., :code:`foo = Uniform(minimum=0, maximum=1)`
bilby.gw.prior as, e.g., foo = bilby.gw.prior.AlignedSpin() - floats, e.g., :code:`foo = 1`
other external modules, e.g., foo = my.module.CustomPrior(...) - bilby.gw.prior as, e.g., :code:`foo = bilby.gw.prior.AlignedSpin()`
- other external modules, e.g., :code:`foo = my.module.CustomPrior(...)`
""" """
comments = ['#', '\n'] comments = ['#', '\n']
...@@ -154,7 +155,7 @@ class PriorDict(dict): ...@@ -154,7 +155,7 @@ class PriorDict(dict):
@classmethod @classmethod
def _get_from_json_dict(cls, prior_dict): def _get_from_json_dict(cls, prior_dict):
try: try:
cls == getattr( cls = getattr(
import_module(prior_dict["__module__"]), import_module(prior_dict["__module__"]),
prior_dict["__name__"]) prior_dict["__name__"])
except ImportError: except ImportError:
...@@ -175,7 +176,7 @@ class PriorDict(dict): ...@@ -175,7 +176,7 @@ class PriorDict(dict):
""" Reads in a prior from a json file """ Reads in a prior from a json file
Parameters Parameters
---------- ==========
filename: str filename: str
Name of the file to be read in Name of the file to be read in
""" """
...@@ -185,7 +186,7 @@ class PriorDict(dict): ...@@ -185,7 +186,7 @@ class PriorDict(dict):
def from_dictionary(self, dictionary): def from_dictionary(self, dictionary):
eval_dict = dict(inf=np.inf) eval_dict = dict(inf=np.inf)
for key, val in iteritems(dictionary): for key, val in dictionary.items():
if isinstance(val, Prior): if isinstance(val, Prior):
continue continue
elif isinstance(val, (int, float)): elif isinstance(val, (int, float)):
...@@ -230,9 +231,19 @@ class PriorDict(dict): ...@@ -230,9 +231,19 @@ class PriorDict(dict):
"= {}. Error message {}".format(key, val, e) "= {}. Error message {}".format(key, val, e)
) )
elif isinstance(val, dict): elif isinstance(val, dict):
logger.warning( try:
'Cannot convert {} into a prior object. ' _class = getattr(
'Leaving as dictionary.'.format(key)) import_module(val.get("__module__", "none")),
val.get("__name__", "none"))
dictionary[key] = _class(**val.get("kwargs", dict()))
except ImportError:
logger.debug("Cannot import prior module {}.{}".format(
val.get("__module__", "none"), val.get("__name__", "none")
))
logger.warning(
'Cannot convert {} into a prior object. '
'Leaving as dictionary.'.format(key))
continue
else: else:
raise TypeError( raise TypeError(
"Unable to parse prior, bad entry: {} " "Unable to parse prior, bad entry: {} "
...@@ -265,7 +276,7 @@ class PriorDict(dict): ...@@ -265,7 +276,7 @@ class PriorDict(dict):
this will set-up default priors for those as well. this will set-up default priors for those as well.
Parameters Parameters
---------- ==========
likelihood: bilby.likelihood.GravitationalWaveTransient instance likelihood: bilby.likelihood.GravitationalWaveTransient instance
Used to infer the set of parameters to fill the prior with Used to infer the set of parameters to fill the prior with
default_priors_file: str, optional default_priors_file: str, optional
...@@ -273,7 +284,7 @@ class PriorDict(dict): ...@@ -273,7 +284,7 @@ class PriorDict(dict):
Returns Returns
------- =======
prior: dict prior: dict
The filled prior dictionary The filled prior dictionary
...@@ -302,12 +313,12 @@ class PriorDict(dict): ...@@ -302,12 +313,12 @@ class PriorDict(dict):
"""Draw samples from the prior set """Draw samples from the prior set
Parameters Parameters
---------- ==========
size: int or tuple of ints, optional size: int or tuple of ints, optional
See numpy.random.uniform docs See numpy.random.uniform docs
Returns Returns
------- =======
dict: Dictionary of the samples dict: Dictionary of the samples
""" """
return self.sample_subset_constrained(keys=list(self.keys()), size=size) return self.sample_subset_constrained(keys=list(self.keys()), size=size)
...@@ -316,14 +327,14 @@ class PriorDict(dict): ...@@ -316,14 +327,14 @@ class PriorDict(dict):
""" Return an array of samples """ Return an array of samples
Parameters Parameters
---------- ==========
keys: list keys: list
A list of keys to sample in A list of keys to sample in
size: int size: int
The number of samples to draw The number of samples to draw
Returns Returns
------- =======
array: array_like array: array_like
An array of shape (len(key), size) of the samples (ordered by keys) An array of shape (len(key), size) of the samples (ordered by keys)
""" """
...@@ -336,14 +347,14 @@ class PriorDict(dict): ...@@ -336,14 +347,14 @@ class PriorDict(dict):
"""Draw samples from the prior set for parameters which are not a DeltaFunction """Draw samples from the prior set for parameters which are not a DeltaFunction
Parameters Parameters
---------- ==========
keys: list keys: list
List of prior keys to draw samples from List of prior keys to draw samples from
size: int or tuple of ints, optional size: int or tuple of ints, optional
See numpy.random.uniform docs See numpy.random.uniform docs
Returns Returns
------- =======
dict: Dictionary of the drawn samples dict: Dictionary of the drawn samples
""" """
self.convert_floats_to_delta_functions() self.convert_floats_to_delta_functions()
...@@ -391,6 +402,7 @@ class PriorDict(dict): ...@@ -391,6 +402,7 @@ class PriorDict(dict):
samples = self.sample_subset(keys=keys, size=sampling_chunk) samples = self.sample_subset(keys=keys, size=sampling_chunk)
keep = np.atleast_1d(self.evaluate_constraints(samples)) keep = np.atleast_1d(self.evaluate_constraints(samples))
if len(keep) == 1: if len(keep) == 1:
self._cached_normalizations[keys] = 1
return 1 return 1
all_samples = {key: np.array([]) for key in keys} all_samples = {key: np.array([]) for key in keys}
while np.count_nonzero(keep) < min_accept: while np.count_nonzero(keep) < min_accept:
...@@ -407,14 +419,14 @@ class PriorDict(dict): ...@@ -407,14 +419,14 @@ class PriorDict(dict):
""" """
Parameters Parameters
---------- ==========
sample: dict sample: dict
Dictionary of the samples of which we want to have the probability of Dictionary of the samples of which we want to have the probability of
kwargs: kwargs:
The keyword arguments are passed directly to `np.product` The keyword arguments are passed directly to `np.product`
Returns Returns
------- =======
float: Joint probability of all individual sample probabilities float: Joint probability of all individual sample probabilities
""" """
...@@ -440,14 +452,14 @@ class PriorDict(dict): ...@@ -440,14 +452,14 @@ class PriorDict(dict):
""" """
Parameters Parameters
---------- ==========
sample: dict sample: dict
Dictionary of the samples of which to calculate the log probability Dictionary of the samples of which to calculate the log probability
axis: None or int axis: None or int
Axis along which the summation is performed Axis along which the summation is performed
Returns Returns
------- =======
float or ndarray: float or ndarray:
Joint log probability of all the individual sample probabilities Joint log probability of all the individual sample probabilities
...@@ -474,14 +486,14 @@ class PriorDict(dict): ...@@ -474,14 +486,14 @@ class PriorDict(dict):
"""Rescale samples from unit cube to prior """Rescale samples from unit cube to prior
Parameters Parameters
---------- ==========
keys: list keys: list
List of prior keys to be rescaled List of prior keys to be rescaled
theta: list theta: list
List of randomly drawn values on a unit cube associated with the prior keys List of randomly drawn values on a unit cube associated with the prior keys
Returns Returns
------- =======
list: List of floats containing the rescaled sample list: List of floats containing the rescaled sample
""" """
return list(flatten([self[key].rescale(sample) for key, sample in zip(keys, theta)])) return list(flatten([self[key].rescale(sample) for key, sample in zip(keys, theta)]))
...@@ -494,8 +506,8 @@ class PriorDict(dict): ...@@ -494,8 +506,8 @@ class PriorDict(dict):
""" """
Test whether there are redundant keys in self. Test whether there are redundant keys in self.
Return Returns
------ =======
bool: Whether there are redundancies or not bool: Whether there are redundancies or not
""" """
redundant = False redundant = False
...@@ -536,7 +548,7 @@ class ConditionalPriorDict(PriorDict): ...@@ -536,7 +548,7 @@ class ConditionalPriorDict(PriorDict):
""" """
Parameters Parameters
---------- ==========
dictionary: dict dictionary: dict
See parent class See parent class
filename: str filename: str
...@@ -615,12 +627,12 @@ class ConditionalPriorDict(PriorDict): ...@@ -615,12 +627,12 @@ class ConditionalPriorDict(PriorDict):
""" Returns the required variables to sample a given conditional key. """ Returns the required variables to sample a given conditional key.
Parameters Parameters
---------- ==========
key : str key : str
Name of the key that we want to know the required variables for Name of the key that we want to know the required variables for
Returns Returns
---------- ==========
dict: key/value pairs of the required variables dict: key/value pairs of the required variables
""" """
return {k: self[k].least_recently_sampled for k in getattr(self[key], 'required_variables', [])} return {k: self[k].least_recently_sampled for k in getattr(self[key], 'required_variables', [])}
...@@ -629,14 +641,14 @@ class ConditionalPriorDict(PriorDict): ...@@ -629,14 +641,14 @@ class ConditionalPriorDict(PriorDict):
""" """
Parameters Parameters
---------- ==========
sample: dict sample: dict
Dictionary of the samples of which we want to have the probability of Dictionary of the samples of which we want to have the probability of
kwargs: kwargs:
The keyword arguments are passed directly to `np.product` The keyword arguments are passed directly to `np.product`
Returns Returns
------- =======
float: Joint probability of all individual sample probabilities float: Joint probability of all individual sample probabilities
""" """
...@@ -650,14 +662,14 @@ class ConditionalPriorDict(PriorDict): ...@@ -650,14 +662,14 @@ class ConditionalPriorDict(PriorDict):
""" """
Parameters Parameters
---------- ==========
sample: dict sample: dict
Dictionary of the samples of which we want to have the log probability of Dictionary of the samples of which we want to have the log probability of
axis: Union[None, int] axis: Union[None, int]
Axis along which the summation is performed Axis along which the summation is performed
Returns Returns
------- =======
float: Joint log probability of all the individual sample probabilities float: Joint log probability of all the individual sample probabilities
""" """
...@@ -671,14 +683,14 @@ class ConditionalPriorDict(PriorDict): ...@@ -671,14 +683,14 @@ class ConditionalPriorDict(PriorDict):
"""Rescale samples from unit cube to prior """Rescale samples from unit cube to prior
Parameters Parameters
---------- ==========
keys: list keys: list
List of prior keys to be rescaled List of prior keys to be rescaled
theta: list theta: list
List of randomly drawn values on a unit cube associated with the prior keys List of randomly drawn values on a unit cube associated with the prior keys
Returns Returns
------- =======
list: List of floats containing the rescaled sample list: List of floats containing the rescaled sample
""" """
self._check_resolved() self._check_resolved()
...@@ -774,14 +786,14 @@ def create_default_prior(name, default_priors_file=None): ...@@ -774,14 +786,14 @@ def create_default_prior(name, default_priors_file=None):
"""Make a default prior for a parameter with a known name. """Make a default prior for a parameter with a known name.
Parameters Parameters
---------- ==========
name: str name: str
Parameter name Parameter name
default_priors_file: str, optional default_priors_file: str, optional
If given, a file containing the default priors. If given, a file containing the default priors.
Return Returns
------ ======
prior: Prior prior: Prior
Default prior distribution for that parameter, if unknown None is Default prior distribution for that parameter, if unknown None is
returned. returned.
......
...@@ -13,7 +13,7 @@ class Interped(Prior): ...@@ -13,7 +13,7 @@ class Interped(Prior):
"""Creates an interpolated prior function from arrays of xx and yy=p(xx) """Creates an interpolated prior function from arrays of xx and yy=p(xx)
Parameters Parameters
---------- ==========
xx: array_like xx: array_like
x values for the to be interpolated prior function x values for the to be interpolated prior function
yy: array_like yy: array_like
...@@ -32,7 +32,7 @@ class Interped(Prior): ...@@ -32,7 +32,7 @@ class Interped(Prior):
See superclass See superclass
Attributes Attributes
---------- ==========
probability_density: scipy.interpolate.interp1d probability_density: scipy.interpolate.interp1d
Interpolated prior probability distribution Interpolated prior probability distribution
cumulative_distribution: scipy.interpolate.interp1d cumulative_distribution: scipy.interpolate.interp1d
...@@ -69,11 +69,11 @@ class Interped(Prior): ...@@ -69,11 +69,11 @@ class Interped(Prior):
"""Return the prior probability of val. """Return the prior probability of val.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
Union[float, array_like]: Prior probability of val Union[float, array_like]: Prior probability of val
""" """
return self.probability_density(val) return self.probability_density(val)
...@@ -102,7 +102,7 @@ class Interped(Prior): ...@@ -102,7 +102,7 @@ class Interped(Prior):
Yields an error if value is set below instantiated x-array minimum. Yields an error if value is set below instantiated x-array minimum.
Returns Returns
------- =======
float: Minimum of the prior distribution float: Minimum of the prior distribution
""" """
...@@ -125,7 +125,7 @@ class Interped(Prior): ...@@ -125,7 +125,7 @@ class Interped(Prior):
Yields an error if value is set above instantiated x-array maximum. Yields an error if value is set above instantiated x-array maximum.
Returns Returns
------- =======
float: Maximum of the prior distribution float: Maximum of the prior distribution
""" """
...@@ -146,7 +146,7 @@ class Interped(Prior): ...@@ -146,7 +146,7 @@ class Interped(Prior):
Updates the prior distribution if it is changed Updates the prior distribution if it is changed
Returns Returns
------- =======
array_like: p(xx) values array_like: p(xx) values
""" """
...@@ -182,7 +182,7 @@ class FromFile(Interped): ...@@ -182,7 +182,7 @@ class FromFile(Interped):
"""Creates an interpolated prior function from arrays of xx and yy=p(xx) extracted from a file """Creates an interpolated prior function from arrays of xx and yy=p(xx) extracted from a file
Parameters Parameters
---------- ==========
file_name: str file_name: str
Name of the file containing the xx and yy arrays Name of the file containing the xx and yy arrays
minimum: float minimum: float
......
...@@ -15,7 +15,7 @@ class BaseJointPriorDist(object): ...@@ -15,7 +15,7 @@ class BaseJointPriorDist(object):
Parameters Parameters
---------- ==========
names: list (required) names: list (required)
A list of the parameter names in the JointPriorDist. The A list of the parameter names in the JointPriorDist. The
listed parameters must have the same order that they appear in listed parameters must have the same order that they appear in
...@@ -125,7 +125,7 @@ class BaseJointPriorDist(object): ...@@ -125,7 +125,7 @@ class BaseJointPriorDist(object):
Works correctly for all child classes Works correctly for all child classes
Returns Returns
------- =======
str: A string representation of this instance str: A string representation of this instance
""" """
...@@ -149,14 +149,14 @@ class BaseJointPriorDist(object): ...@@ -149,14 +149,14 @@ class BaseJointPriorDist(object):
probability will not be properly normalised. probability will not be properly normalised.
Parameters Parameters
---------- ==========
value: array_like value: array_like
A 1d vector of the sample, or 2d array of sample values with shape A 1d vector of the sample, or 2d array of sample values with shape
NxM, where N is the number of samples and M is the number of NxM, where N is the number of samples and M is the number of
parameters. parameters.
Returns Returns
------- =======
samp: array_like samp: array_like
returns the input value as a sample array returns the input value as a sample array
outbounds: array_like outbounds: array_like
...@@ -185,7 +185,7 @@ class BaseJointPriorDist(object): ...@@ -185,7 +185,7 @@ class BaseJointPriorDist(object):
probability will not be properly normalised. probability will not be properly normalised.
Parameters Parameters
---------- ==========
value: array_like value: array_like
A 1d vector of the sample, or 2d array of sample values with shape A 1d vector of the sample, or 2d array of sample values with shape
NxM, where N is the number of samples and M is the number of NxM, where N is the number of samples and M is the number of
...@@ -206,7 +206,7 @@ class BaseJointPriorDist(object): ...@@ -206,7 +206,7 @@ class BaseJointPriorDist(object):
probability will not be properly normalised. **this method needs overwritten by child class** probability will not be properly normalised. **this method needs overwritten by child class**
Parameters Parameters
---------- ==========
samp: vector samp: vector
sample to evaluate the ln_prob at sample to evaluate the ln_prob at
lnprob: vector lnprob: vector
...@@ -215,7 +215,7 @@ class BaseJointPriorDist(object): ...@@ -215,7 +215,7 @@ class BaseJointPriorDist(object):
boolean array showing which samples in lnprob vector are out of the given bounds boolean array showing which samples in lnprob vector are out of the given bounds
Returns Returns
------- =======
lnprob: vector lnprob: vector
array of lnprob values for each sample given array of lnprob values for each sample given
""" """
...@@ -229,7 +229,7 @@ class BaseJointPriorDist(object): ...@@ -229,7 +229,7 @@ class BaseJointPriorDist(object):
Draw, and set, a sample from the Dist, accompanying method _sample needs to overwritten Draw, and set, a sample from the Dist, accompanying method _sample needs to overwritten
Parameters Parameters
---------- ==========
size: int size: int
number of samples to generate, defualts to 1 number of samples to generate, defualts to 1
""" """
...@@ -248,7 +248,7 @@ class BaseJointPriorDist(object): ...@@ -248,7 +248,7 @@ class BaseJointPriorDist(object):
Draw, and set, a sample from the joint dist (**needs to be ovewritten by child class**) Draw, and set, a sample from the joint dist (**needs to be ovewritten by child class**)
Parameters Parameters
---------- ==========
size: int size: int
number of samples to generate, defualts to 1 number of samples to generate, defualts to 1
""" """
...@@ -265,7 +265,7 @@ class BaseJointPriorDist(object): ...@@ -265,7 +265,7 @@ class BaseJointPriorDist(object):
overwrite accompanying method _rescale(). overwrite accompanying method _rescale().
Parameters Parameters
---------- ==========
value: array value: array
A 1d vector sample (one for each parameter) drawn from a uniform A 1d vector sample (one for each parameter) drawn from a uniform
distribution between 0 and 1, or a 2d NxM array of samples where distribution between 0 and 1, or a 2d NxM array of samples where
...@@ -275,7 +275,7 @@ class BaseJointPriorDist(object): ...@@ -275,7 +275,7 @@ class BaseJointPriorDist(object):
args are called in the JointPrior rescale methods for each parameter args are called in the JointPrior rescale methods for each parameter
Returns Returns
------- =======
array: array:
An vector sample drawn from the multivariate Gaussian An vector sample drawn from the multivariate Gaussian
distribution. distribution.
...@@ -297,7 +297,7 @@ class BaseJointPriorDist(object): ...@@ -297,7 +297,7 @@ class BaseJointPriorDist(object):
rescale a sample from a unit hypercybe to the joint dist (**needs to be ovewritten by child class**) rescale a sample from a unit hypercybe to the joint dist (**needs to be ovewritten by child class**)
Parameters Parameters
---------- ==========
samp: numpy array samp: numpy array
this is a vector sample drawn from a uniform distribtuion to be rescaled to the distribution this is a vector sample drawn from a uniform distribtuion to be rescaled to the distribution
""" """
...@@ -322,7 +322,7 @@ class MultivariateGaussianDist(BaseJointPriorDist): ...@@ -322,7 +322,7 @@ class MultivariateGaussianDist(BaseJointPriorDist):
MultiNest. MultiNest.
Parameters Parameters
---------- ==========
names: list names: list
A list of the parameter names in the multivariate Gaussian. The A list of the parameter names in the multivariate Gaussian. The
listed parameters must have the same order that they appear in listed parameters must have the same order that they appear in
...@@ -656,7 +656,7 @@ class JointPrior(Prior): ...@@ -656,7 +656,7 @@ class JointPrior(Prior):
"""This defines the single parameter Prior object for parameters that belong to a JointPriorDist """This defines the single parameter Prior object for parameters that belong to a JointPriorDist
Parameters Parameters
---------- ==========
dist: ChildClass of BaseJointPriorDist dist: ChildClass of BaseJointPriorDist
The shared JointPriorDistribution that this parameter belongs to The shared JointPriorDistribution that this parameter belongs to
name: str name: str
...@@ -699,13 +699,13 @@ class JointPrior(Prior): ...@@ -699,13 +699,13 @@ class JointPrior(Prior):
Scale a unit hypercube sample to the prior. Scale a unit hypercube sample to the prior.
Parameters Parameters
---------- ==========
val: array_like val: array_like
value drawn from unit hypercube to be rescaled onto the prior value drawn from unit hypercube to be rescaled onto the prior
kwargs: dict kwargs: dict
all kwargs passed to the dist.rescale method all kwargs passed to the dist.rescale method
Returns Returns
------- =======
float: float:
A sample from the prior paramter. A sample from the prior paramter.
""" """
...@@ -726,13 +726,13 @@ class JointPrior(Prior): ...@@ -726,13 +726,13 @@ class JointPrior(Prior):
Draw a sample from the prior. Draw a sample from the prior.
Parameters Parameters
---------- ==========
size: int, float (defaults to 1) size: int, float (defaults to 1)
number of samples to draw number of samples to draw
kwargs: dict kwargs: dict
kwargs passed to the dist.sample method kwargs passed to the dist.sample method
Returns Returns
------- =======
float: float:
A sample from the prior paramter. A sample from the prior paramter.
""" """
...@@ -764,11 +764,11 @@ class JointPrior(Prior): ...@@ -764,11 +764,11 @@ class JointPrior(Prior):
distribution. distribution.
Parameters Parameters
---------- ==========
val: array_like val: array_like
value to evaluate the prior log-prob at value to evaluate the prior log-prob at
Returns Returns
------- =======
float: float:
the logp value for the prior at given sample the logp value for the prior at given sample
""" """
...@@ -816,12 +816,12 @@ class JointPrior(Prior): ...@@ -816,12 +816,12 @@ class JointPrior(Prior):
"""Return the prior probability of val """Return the prior probability of val
Parameters Parameters
---------- ==========
val: array_like val: array_like
value to evaluate the prior prob at value to evaluate the prior prob at
Returns Returns
------- =======
float: float:
the p value for the prior at given sample the p value for the prior at given sample
""" """
......
...@@ -16,7 +16,7 @@ class SlabSpikePrior(Prior): ...@@ -16,7 +16,7 @@ class SlabSpikePrior(Prior):
`SymmetricLogUniform` and `FermiDirac` are currently not supported. `SymmetricLogUniform` and `FermiDirac` are currently not supported.
Parameters Parameters
---------- ==========
slab: Prior slab: Prior
Any instance of a bilby prior class. All general prior attributes Any instance of a bilby prior class. All general prior attributes
from the slab are copied into the SlabSpikePrior. from the slab are copied into the SlabSpikePrior.
...@@ -76,12 +76,12 @@ class SlabSpikePrior(Prior): ...@@ -76,12 +76,12 @@ class SlabSpikePrior(Prior):
'Rescale' a sample from the unit line element to the prior. 'Rescale' a sample from the unit line element to the prior.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
A random number between 0 and 1 A random number between 0 and 1
Returns Returns
------- =======
array_like: Associated prior value with input value. array_like: Associated prior value with input value.
""" """
val = np.atleast_1d(val) val = np.atleast_1d(val)
...@@ -104,12 +104,12 @@ class SlabSpikePrior(Prior): ...@@ -104,12 +104,12 @@ class SlabSpikePrior(Prior):
on the pure slab part of the prior. on the pure slab part of the prior.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
A random number between 0 and self.slab_fraction A random number between 0 and self.slab_fraction
Returns Returns
------- =======
array_like: Associated prior value with input value. array_like: Associated prior value with input value.
""" """
return self.slab.rescale(val / self.slab_fraction) return self.slab.rescale(val / self.slab_fraction)
...@@ -119,11 +119,11 @@ class SlabSpikePrior(Prior): ...@@ -119,11 +119,11 @@ class SlabSpikePrior(Prior):
Returns np.inf for the spike location Returns np.inf for the spike location
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
array_like: Prior probability of val array_like: Prior probability of val
""" """
res = self.slab.prob(val) * self.slab_fraction res = self.slab.prob(val) * self.slab_fraction
...@@ -136,11 +136,11 @@ class SlabSpikePrior(Prior): ...@@ -136,11 +136,11 @@ class SlabSpikePrior(Prior):
Returns np.inf for the spike location Returns np.inf for the spike location
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
array_like: Prior probability of val array_like: Prior probability of val
""" """
res = self.slab.ln_prob(val) + np.log(self.slab_fraction) res = self.slab.ln_prob(val) + np.log(self.slab_fraction)
...@@ -154,11 +154,11 @@ class SlabSpikePrior(Prior): ...@@ -154,11 +154,11 @@ class SlabSpikePrior(Prior):
at the spike location. at the spike location.
Parameters Parameters
---------- ==========
val: Union[float, int, array_like] val: Union[float, int, array_like]
Returns Returns
------- =======
array_like: CDF value of val array_like: CDF value of val
""" """
......
This diff is collapsed.
...@@ -13,6 +13,7 @@ from .dynamic_dynesty import DynamicDynesty ...@@ -13,6 +13,7 @@ from .dynamic_dynesty import DynamicDynesty
from .dynesty import Dynesty from .dynesty import Dynesty
from .emcee import Emcee from .emcee import Emcee
from .kombine import Kombine from .kombine import Kombine
from .nessai import Nessai
from .nestle import Nestle from .nestle import Nestle
from .polychord import PyPolyChord from .polychord import PyPolyChord
from .ptemcee import Ptemcee from .ptemcee import Ptemcee
...@@ -26,10 +27,10 @@ from . import proposal ...@@ -26,10 +27,10 @@ from . import proposal
IMPLEMENTED_SAMPLERS = { IMPLEMENTED_SAMPLERS = {
'cpnest': Cpnest, 'dnest4': DNest4, 'dynamic_dynesty': DynamicDynesty, 'cpnest': Cpnest, 'dnest4': DNest4, 'dynamic_dynesty': DynamicDynesty,
'dynesty': Dynesty, 'emcee': Emcee, 'kombine': Kombine, 'nestle': Nestle, 'dynesty': Dynesty, 'emcee': Emcee,'kombine': Kombine, 'nessai': Nessai,
'ptemcee': Ptemcee, 'ptmcmcsampler': PTMCMCSampler, 'pymc3': Pymc3, 'nestle': Nestle, 'ptemcee': Ptemcee, 'ptmcmcsampler': PTMCMCSampler,
'pymultinest': Pymultinest, 'pypolychord': PyPolyChord, 'ultranest': Ultranest, 'pymc3': Pymc3, 'pymultinest': Pymultinest, 'pypolychord': PyPolyChord,
'fake_sampler': FakeSampler} 'ultranest': Ultranest, 'fake_sampler': FakeSampler}
if command_line_args.sampler_help: if command_line_args.sampler_help:
sampler = command_line_args.sampler_help sampler = command_line_args.sampler_help
...@@ -57,7 +58,7 @@ def run_sampler(likelihood, priors=None, label='label', outdir='outdir', ...@@ -57,7 +58,7 @@ def run_sampler(likelihood, priors=None, label='label', outdir='outdir',
The primary interface to easy parameter estimation The primary interface to easy parameter estimation
Parameters Parameters
---------- ==========
likelihood: `bilby.Likelihood` likelihood: `bilby.Likelihood`
A `Likelihood` instance A `Likelihood` instance
priors: `bilby.PriorDict` priors: `bilby.PriorDict`
...@@ -108,7 +109,7 @@ def run_sampler(likelihood, priors=None, label='label', outdir='outdir', ...@@ -108,7 +109,7 @@ def run_sampler(likelihood, priors=None, label='label', outdir='outdir',
All kwargs are passed directly to the samplers `run` function All kwargs are passed directly to the samplers `run` function
Returns Returns
------- =======
result: bilby.core.result.Result result: bilby.core.result.Result
An object containing the results An object containing the results
""" """
......
from __future__ import absolute_import
import datetime import datetime
import distutils.dir_util import distutils.dir_util
import numpy as np import numpy as np
...@@ -16,7 +15,7 @@ class Sampler(object): ...@@ -16,7 +15,7 @@ class Sampler(object):
""" A sampler object to aid in setting up an inference run """ A sampler object to aid in setting up an inference run
Parameters Parameters
---------- ==========
likelihood: likelihood.Likelihood likelihood: likelihood.Likelihood
A object with a log_l method A object with a log_l method
priors: bilby.core.prior.PriorDict, dict priors: bilby.core.prior.PriorDict, dict
...@@ -51,7 +50,7 @@ class Sampler(object): ...@@ -51,7 +50,7 @@ class Sampler(object):
Additional keyword arguments Additional keyword arguments
Attributes Attributes
---------- ==========
likelihood: likelihood.Likelihood likelihood: likelihood.Likelihood
A object with a log_l method A object with a log_l method
priors: bilby.core.prior.PriorDict priors: bilby.core.prior.PriorDict
...@@ -79,7 +78,7 @@ class Sampler(object): ...@@ -79,7 +78,7 @@ class Sampler(object):
Dictionary of keyword arguments that can be used in the external sampler Dictionary of keyword arguments that can be used in the external sampler
Raises Raises
------ ======
TypeError: TypeError:
If external_sampler is neither a string nor an instance of this class If external_sampler is neither a string nor an instance of this class
If not all likelihood.parameters have been defined If not all likelihood.parameters have been defined
...@@ -227,7 +226,7 @@ class Sampler(object): ...@@ -227,7 +226,7 @@ class Sampler(object):
def _initialise_result(self, result_class): def _initialise_result(self, result_class):
""" """
Returns Returns
------- =======
bilby.core.result.Result: An initial template for the result bilby.core.result.Result: An initial template for the result
""" """
...@@ -251,29 +250,13 @@ class Sampler(object): ...@@ -251,29 +250,13 @@ class Sampler(object):
return result return result
def _check_if_priors_can_be_sampled(self):
"""Check if all priors can be sampled properly.
Raises
------
AttributeError
prior can't be sampled.
"""
for key in self.priors:
if isinstance(self.priors[key], Constraint):
continue
try:
self.priors[key].sample()
except AttributeError as e:
logger.warning('Cannot sample from {}, {}'.format(key, e))
def _verify_parameters(self): def _verify_parameters(self):
""" Evaluate a set of parameters drawn from the prior """ Evaluate a set of parameters drawn from the prior
Tests if the likelihood evaluation passes Tests if the likelihood evaluation passes
Raises Raises
------ ======
TypeError TypeError
Likelihood can't be evaluated. Likelihood can't be evaluated.
...@@ -297,7 +280,7 @@ class Sampler(object): ...@@ -297,7 +280,7 @@ class Sampler(object):
""" Times the likelihood evaluation and print an info message """ Times the likelihood evaluation and print an info message
Parameters Parameters
---------- ==========
n_evaluations: int n_evaluations: int
The number of evaluations to estimate the evaluation time from The number of evaluations to estimate the evaluation time from
...@@ -323,7 +306,13 @@ class Sampler(object): ...@@ -323,7 +306,13 @@ class Sampler(object):
Checks if use_ratio is set. Prints a warning if use_ratio is set but Checks if use_ratio is set. Prints a warning if use_ratio is set but
not properly implemented. not properly implemented.
""" """
self._check_if_priors_can_be_sampled() try:
self.priors.sample_subset(self.search_parameter_keys)
except (KeyError, AttributeError):
logger.error("Cannot sample from priors with keys: {}.".format(
self.search_parameter_keys
))
raise
if self.use_ratio is False: if self.use_ratio is False:
logger.debug("use_ratio set to False") logger.debug("use_ratio set to False")
return return
...@@ -343,12 +332,12 @@ class Sampler(object): ...@@ -343,12 +332,12 @@ class Sampler(object):
""" Prior transform method that is passed into the external sampler. """ Prior transform method that is passed into the external sampler.
Parameters Parameters
---------- ==========
theta: list theta: list
List of sampled values on a unit interval List of sampled values on a unit interval
Returns Returns
------- =======
list: Properly rescaled sampled values list: Properly rescaled sampled values
""" """
return self.priors.rescale(self._search_parameter_keys, theta) return self.priors.rescale(self._search_parameter_keys, theta)
...@@ -357,12 +346,12 @@ class Sampler(object): ...@@ -357,12 +346,12 @@ class Sampler(object):
""" """
Parameters Parameters
---------- ==========
theta: list theta: list
List of sampled values on a unit interval List of sampled values on a unit interval
Returns Returns
------- =======
float: Joint ln prior probability of theta float: Joint ln prior probability of theta
""" """
...@@ -374,12 +363,12 @@ class Sampler(object): ...@@ -374,12 +363,12 @@ class Sampler(object):
""" """
Parameters Parameters
---------- ==========
theta: list theta: list
List of values for the likelihood parameters List of values for the likelihood parameters
Returns Returns
------- =======
float: Log-likelihood or log-likelihood-ratio given the current float: Log-likelihood or log-likelihood-ratio given the current
likelihood.parameter values likelihood.parameter values
...@@ -401,7 +390,7 @@ class Sampler(object): ...@@ -401,7 +390,7 @@ class Sampler(object):
""" Get a random draw from the prior distribution """ Get a random draw from the prior distribution
Returns Returns
------- =======
draw: array_like draw: array_like
An ndim-length array of values drawn from the prior. Parameters An ndim-length array of values drawn from the prior. Parameters
with delta-function (or fixed) priors are not returned with delta-function (or fixed) priors are not returned
...@@ -420,12 +409,12 @@ class Sampler(object): ...@@ -420,12 +409,12 @@ class Sampler(object):
finite prior and likelihood (relevant for constrained priors). finite prior and likelihood (relevant for constrained priors).
Parameters Parameters
---------- ==========
npoints: int npoints: int
The number of values to return The number of values to return
Returns Returns
------- =======
unit_cube, parameters, likelihood: tuple of array_like unit_cube, parameters, likelihood: tuple of array_like
unit_cube (nlive, ndim) is an array of the prior samples from the unit_cube (nlive, ndim) is an array of the prior samples from the
unit cube, parameters (nlive, ndim) is the unit_cube array unit cube, parameters (nlive, ndim) is the unit_cube array
...@@ -454,12 +443,12 @@ class Sampler(object): ...@@ -454,12 +443,12 @@ class Sampler(object):
Also catches the output of `numpy.nan_to_num`. Also catches the output of `numpy.nan_to_num`.
Parameters Parameters
---------- ==========
theta: array_like theta: array_like
Parameter values at which to evaluate likelihood Parameter values at which to evaluate likelihood
Returns Returns
------- =======
bool, cube (nlive, bool, cube (nlive,
True if the likelihood and prior are finite, false otherwise True if the likelihood and prior are finite, false otherwise
...@@ -483,7 +472,7 @@ class Sampler(object): ...@@ -483,7 +472,7 @@ class Sampler(object):
""" """
TODO: Implement this method TODO: Implement this method
Raises Raises
------- =======
ValueError: in any case ValueError: in any case
""" """
raise ValueError("Method not yet implemented") raise ValueError("Method not yet implemented")
...@@ -557,7 +546,7 @@ class NestedSampler(Sampler): ...@@ -557,7 +546,7 @@ class NestedSampler(Sampler):
loglikelihoods loglikelihoods
Parameters Parameters
---------- ==========
sorted_samples, unsorted_samples: array-like sorted_samples, unsorted_samples: array-like
Sorted and unsorted values of the samples. These should be of the Sorted and unsorted values of the samples. These should be of the
same shape and contain the same sample values, but in different same shape and contain the same sample values, but in different
...@@ -566,7 +555,7 @@ class NestedSampler(Sampler): ...@@ -566,7 +555,7 @@ class NestedSampler(Sampler):
The loglikelihoods corresponding to the unsorted_samples The loglikelihoods corresponding to the unsorted_samples
Returns Returns
------- =======
sorted_loglikelihoods: array-like sorted_loglikelihoods: array-like
The loglikelihoods reordered to match that of the sorted_samples The loglikelihoods reordered to match that of the sorted_samples
...@@ -590,12 +579,12 @@ class NestedSampler(Sampler): ...@@ -590,12 +579,12 @@ class NestedSampler(Sampler):
the prior constraint here. the prior constraint here.
Parameters Parameters
---------- ==========
theta: array_like theta: array_like
Parameter values at which to evaluate likelihood Parameter values at which to evaluate likelihood
Returns Returns
------- =======
float: log_likelihood float: log_likelihood
""" """
if self.priors.evaluate_constraints({ if self.priors.evaluate_constraints({
...@@ -646,7 +635,7 @@ class MCMCSampler(Sampler): ...@@ -646,7 +635,7 @@ class MCMCSampler(Sampler):
""" Uses the `emcee.autocorr` module to estimate the autocorrelation """ Uses the `emcee.autocorr` module to estimate the autocorrelation
Parameters Parameters
---------- ==========
samples: array_like samples: array_like
A chain of samples. A chain of samples.
c: float c: float
......
from __future__ import absolute_import
import array import array
import copy import copy
...@@ -19,8 +18,8 @@ class Cpnest(NestedSampler): ...@@ -19,8 +18,8 @@ class Cpnest(NestedSampler):
for that class for further help. Under Other Parameters, we list commonly for that class for further help. Under Other Parameters, we list commonly
used kwargs and the bilby defaults. used kwargs and the bilby defaults.
Other Parameters Parameters
---------------- ==========
nlive: int nlive: int
The number of live points, note this can also equivalently be given as The number of live points, note this can also equivalently be given as
one of [npoints, nlives, n_live_points] one of [npoints, nlives, n_live_points]
...@@ -89,8 +88,8 @@ class Cpnest(NestedSampler): ...@@ -89,8 +88,8 @@ class Cpnest(NestedSampler):
prior_samples = self.priors.sample() prior_samples = self.priors.sample()
self._update_bounds() self._update_bounds()
point = LivePoint( point = LivePoint(
self.names, array.array( self.names, array.array('d', [prior_samples[name] for name in self.names])
'f', [prior_samples[name] for name in self.names])) )
return point return point
self._resolve_proposal_functions() self._resolve_proposal_functions()
...@@ -132,6 +131,7 @@ class Cpnest(NestedSampler): ...@@ -132,6 +131,7 @@ class Cpnest(NestedSampler):
self.result.nested_samples['weights'] = np.exp(log_weights) self.result.nested_samples['weights'] = np.exp(log_weights)
self.result.log_evidence = out.NS.state.logZ self.result.log_evidence = out.NS.state.logZ
self.result.log_evidence_err = np.sqrt(out.NS.state.info / out.NS.state.nlive) self.result.log_evidence_err = np.sqrt(out.NS.state.info / out.NS.state.nlive)
self.result.information_gain = out.NS.state.info
return self.result return self.result
def _verify_kwargs_against_default_kwargs(self): def _verify_kwargs_against_default_kwargs(self):
......
...@@ -69,11 +69,11 @@ class DNest4(NestedSampler): ...@@ -69,11 +69,11 @@ class DNest4(NestedSampler):
Bilby wrapper of DNest4 Bilby wrapper of DNest4
Parameters Parameters
---------- ==========
TBD TBD
Other Parameters Other Parameters
---------------- ------==========
num_particles: int num_particles: int
The number of points to use in the Nested Sampling active population. The number of points to use in the Nested Sampling active population.
max_num_levels: int max_num_levels: int
......
from __future__ import absolute_import
import os import os
import dill as pickle import dill as pickle
...@@ -22,7 +21,7 @@ class DynamicDynesty(Dynesty): ...@@ -22,7 +21,7 @@ class DynamicDynesty(Dynesty):
we list commonly all kwargs and the bilby defaults. we list commonly all kwargs and the bilby defaults.
Parameters Parameters
---------- ==========
likelihood: likelihood.Likelihood likelihood: likelihood.Likelihood
A object with a log_l method A object with a log_l method
priors: bilby.core.prior.PriorDict, dict priors: bilby.core.prior.PriorDict, dict
...@@ -42,7 +41,7 @@ class DynamicDynesty(Dynesty): ...@@ -42,7 +41,7 @@ class DynamicDynesty(Dynesty):
only advisable for testing environments only advisable for testing environments
Other Parameters Other Parameters
---------------- ------==========
bound: {'none', 'single', 'multi', 'balls', 'cubes'}, ('multi') bound: {'none', 'single', 'multi', 'balls', 'cubes'}, ('multi')
Method used to select new points Method used to select new points
sample: {'unif', 'rwalk', 'slice', 'rslice', 'hslice'}, ('rwalk') sample: {'unif', 'rwalk', 'slice', 'rslice', 'hslice'}, ('rwalk')
......
...@@ -6,7 +6,7 @@ import pickle ...@@ -6,7 +6,7 @@ import pickle
import signal import signal
import time import time
import tqdm from tqdm.auto import tqdm
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import numpy as np import numpy as np
from pandas import DataFrame from pandas import DataFrame
...@@ -79,7 +79,7 @@ class Dynesty(NestedSampler): ...@@ -79,7 +79,7 @@ class Dynesty(NestedSampler):
we list commonly all kwargs and the bilby defaults. we list commonly all kwargs and the bilby defaults.
Parameters Parameters
---------- ==========
likelihood: likelihood.Likelihood likelihood: likelihood.Likelihood
A object with a log_l method A object with a log_l method
priors: bilby.core.prior.PriorDict, dict priors: bilby.core.prior.PriorDict, dict
...@@ -99,7 +99,7 @@ class Dynesty(NestedSampler): ...@@ -99,7 +99,7 @@ class Dynesty(NestedSampler):
only advisable for testing environments only advisable for testing environments
Other Parameters Other Parameters
---------------- ------==========
npoints: int, (1000) npoints: int, (1000)
The number of live points, note this can also equivalently be given as The number of live points, note this can also equivalently be given as
one of [nlive, nlives, n_live_points] one of [nlive, nlives, n_live_points]
...@@ -224,7 +224,7 @@ class Dynesty(NestedSampler): ...@@ -224,7 +224,7 @@ class Dynesty(NestedSampler):
self.kwargs['update_interval'] = int(0.6 * self.kwargs['nlive']) self.kwargs['update_interval'] = int(0.6 * self.kwargs['nlive'])
if self.kwargs['print_func'] is None: if self.kwargs['print_func'] is None:
self.kwargs['print_func'] = self._print_func self.kwargs['print_func'] = self._print_func
self.pbar = tqdm.tqdm(file=sys.stdout) self.pbar = tqdm(file=sys.stdout)
Sampler._verify_kwargs_against_default_kwargs(self) Sampler._verify_kwargs_against_default_kwargs(self)
def _print_func(self, results, niter, ncall=None, dlogz=None, *args, **kwargs): def _print_func(self, results, niter, ncall=None, dlogz=None, *args, **kwargs):
...@@ -401,6 +401,7 @@ class Dynesty(NestedSampler): ...@@ -401,6 +401,7 @@ class Dynesty(NestedSampler):
sorted_samples=self.result.samples) sorted_samples=self.result.samples)
self.result.log_evidence = out.logz[-1] self.result.log_evidence = out.logz[-1]
self.result.log_evidence_err = out.logzerr[-1] self.result.log_evidence_err = out.logzerr[-1]
self.result.information_gain = out.information[-1]
def _run_nested_wrapper(self, kwargs): def _run_nested_wrapper(self, kwargs):
""" Wrapper function to run_nested """ Wrapper function to run_nested
...@@ -409,7 +410,7 @@ class Dynesty(NestedSampler): ...@@ -409,7 +410,7 @@ class Dynesty(NestedSampler):
dynesty accepting different arguments. dynesty accepting different arguments.
Parameters Parameters
---------- ==========
kwargs: dict kwargs: dict
The dictionary of kwargs to pass to run_nested The dictionary of kwargs to pass to run_nested
...@@ -474,7 +475,7 @@ class Dynesty(NestedSampler): ...@@ -474,7 +475,7 @@ class Dynesty(NestedSampler):
The previous run time is set to self. The previous run time is set to self.
Parameters Parameters
---------- ==========
continuing: bool continuing: bool
Whether the run is continuing or terminating, if True, the loaded Whether the run is continuing or terminating, if True, the loaded
state is mostly written back to disk. state is mostly written back to disk.
...@@ -612,7 +613,7 @@ class Dynesty(NestedSampler): ...@@ -612,7 +613,7 @@ class Dynesty(NestedSampler):
fig = dyplot.traceplot(self.sampler.results, labels=labels)[0] fig = dyplot.traceplot(self.sampler.results, labels=labels)[0]
fig.tight_layout() fig.tight_layout()
fig.savefig(filename) fig.savefig(filename)
except (RuntimeError, np.linalg.linalg.LinAlgError, ValueError) as e: except (RuntimeError, np.linalg.linalg.LinAlgError, ValueError, OverflowError, Exception) as e:
logger.warning(e) logger.warning(e)
logger.warning('Failed to create dynesty state plot at checkpoint') logger.warning('Failed to create dynesty state plot at checkpoint')
finally: finally:
...@@ -679,17 +680,27 @@ class Dynesty(NestedSampler): ...@@ -679,17 +680,27 @@ class Dynesty(NestedSampler):
cube we map this back to [0, 1]. cube we map this back to [0, 1].
Parameters Parameters
---------- ==========
theta: list theta: list
List of sampled values on a unit interval List of sampled values on a unit interval
Returns Returns
------- =======
list: Properly rescaled sampled values list: Properly rescaled sampled values
""" """
return self.priors.rescale(self._search_parameter_keys, theta) return self.priors.rescale(self._search_parameter_keys, theta)
def calc_likelihood_count(self):
if self.likelihood_benchmark:
if hasattr(self, 'sampler'):
self.result.num_likelihood_evaluations = \
getattr(self.sampler, 'ncall', 0)
else:
self.result.num_likelihood_evaluations = 0
else:
return None
def sample_rwalk_bilby(args): def sample_rwalk_bilby(args):
""" Modified bilby-implemented version of dynesty.sampling.sample_rwalk """ """ Modified bilby-implemented version of dynesty.sampling.sample_rwalk """
...@@ -809,13 +820,13 @@ def sample_rwalk_bilby(args): ...@@ -809,13 +820,13 @@ def sample_rwalk_bilby(args):
def estimate_nmcmc(accept_ratio, old_act, maxmcmc, safety=5, tau=None): def estimate_nmcmc(accept_ratio, old_act, maxmcmc, safety=5, tau=None):
""" Estimate autocorrelation length of chain using acceptance fraction """ Estimate autocorrelation length of chain using acceptance fraction
Using ACL = (2/acc) - 1 multiplied by a safety margin. Code adapated from Using ACL = (2/acc) - 1 multiplied by a safety margin. Code adapated from CPNest:
CPNest:
- https://github.com/johnveitch/cpnest/blob/master/cpnest/sampler.py - https://github.com/johnveitch/cpnest/blob/master/cpnest/sampler.py
- http://github.com/farr/Ensemble.jl - http://github.com/farr/Ensemble.jl
Parameters Parameters
---------- ==========
accept_ratio: float [0, 1] accept_ratio: float [0, 1]
Ratio of the number of accepted points to the total number of points Ratio of the number of accepted points to the total number of points
old_act: int old_act: int
......