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 (26)
Showing
with 494 additions and 182 deletions
......@@ -43,7 +43,7 @@ basic-3.7:
# test example on python 3.7
python-3.7:
stage: test
image: bilbydev/v2-dockerfile-test-suite-python37
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen
script:
- python -m pip install .
......@@ -69,7 +69,7 @@ python-3.7:
# test example on python 3.8
python-3.8:
stage: test
image: bilbydev/v2-dockerfile-test-suite-python38
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python38-frozen
script:
- python -m pip install .
......@@ -78,7 +78,7 @@ python-3.8:
# test example on python 3.6
python-3.6:
stage: test
image: bilbydev/v2-dockerfile-test-suite-python36
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python36-frozen
script:
- python -m pip install .
......@@ -87,7 +87,7 @@ python-3.6:
# test samplers on python 3.7
python-3.7-samplers:
stage: test
image: bilbydev/v2-dockerfile-test-suite-python37
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen
script:
- python -m pip install .
......@@ -97,7 +97,7 @@ python-3.7-samplers:
# test samplers on python 3.6
python-3.6-samplers:
stage: test
image: bilbydev/v2-dockerfile-test-suite-python36
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python36-frozen
script:
- python -m pip install .
......@@ -106,7 +106,7 @@ python-3.6-samplers:
# Test containers are up to date
containers:
stage: test
image: bilbydev/v2-dockerfile-test-suite-python37
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen
script:
- cd containers
- python write_dockerfiles.py
......@@ -117,7 +117,7 @@ containers:
# Tests run at a fixed schedule rather than on push
scheduled-python-3.7:
stage: test
image: bilbydev/v2-dockerfile-test-suite-python37
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen
only:
- schedules
script:
......@@ -129,7 +129,7 @@ scheduled-python-3.7:
plotting:
stage: test
image: bilbydev/bilby-test-suite-python37
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen
only:
- schedules
script:
......@@ -138,6 +138,12 @@ plotting:
- pytest test/gw/plot_test.py
authors:
stage: test
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen
script:
- python test/check_author_list.py
pages:
stage: deploy
dependencies:
......@@ -156,7 +162,7 @@ pages:
deploy_release:
stage: deploy
image: bilbydev/v2-dockerfile-test-suite-python37
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen
variables:
TWINE_USERNAME: $PYPI_USERNAME
TWINE_PASSWORD: $PYPI_PASSWORD
......@@ -171,7 +177,7 @@ deploy_release:
precommits-py3.7:
stage: test
image: bilbydev/v2-dockerfile-test-suite-python37
image: quay.io/gregory_ashton/bilby_v2-dockerfile-test-suite-python37-frozen
script:
- source activate python37
- mkdir -p .pip37
......
# Authors
This file lists all the authors in first-name alphabetical order who have
contributed (either by code contribution or indirectly). If your name is not
listed here, please contact anyone on this list and raise your concern.
Abhirup Ghosh
Aditya Vijaykumar
Andrew Kim
Andrew Miller
Antoni Ramos-Buades
Avi Vajpeyi
Bruce Edelman
Carl-Johan Haster
Cecilio Garcia-Quiros
Charlie Hoy
Christopher Berry
Christos Karathanasis
Colm Talbot
Daniel Williams
David Keitel
Duncan Macleod
Eric Thrane
Ethan Payne
Francisco Javier Hernandez
Gregory Ashton
Hector Estelles
Ignacio Magaña Hernandez
Isobel Marguarethe Romero-Shaw
Jade Powell
James A Clark
John Veitch
Katerina Chatziioannou
Kaylee de Soto
Khun Sang Phukon
Kshipraa Athar
Liting Xiao
Maite Mateu-Lucena
Marc Arene
Marcus Edward Lower
Margaret Millhouse
Marta Colleoni
Matthew Carney
Matthew David Pitkin
Michael Puerrer
Michael Williams
Monica Rizzo
Moritz Huebner
Nicola De Lillo
Nikhil Sarin
Nirban Bose
Paul Easter
Paul Lasky
Philip Relton
Rhys Green
Roberto Cotesta
Rory Smith
S. H. Oh
Sacha Husa
Scott Coughlin
Serguei Ossokine
Shanika Galaudage
Sharan Banagiri
Shichao Wu
Simon Stevenson
Soichiro Morisaki
Sumeet Kulkarni
Sylvia Biscoveanu
Tathagata Ghosh
Virginia d'Emilio
Vivien Raymond
# All notable changes will be documented in this file
## [1.0.3] 2020-11-23
Version 1.0.4 release of bilby
### Added
- Added a chirp-mass and mass-ratio prior which are uniform in component masses (!891)
### Changes
- Fixed issue in the CI
## [1.0.3] 2020-10-23
Version 1.0.3 release of bilby
### Added
- SlabSpikePrior and examples (!857)
- Authors file (!885)
- CDF function to conditional priors (!882)
- Waveform plot in visualising_the_results.ipynb (!817)
- Addition of dnest4 sampler (!849, !883)
- Loaded modules added to meta-data (!881)
### Changes
- Constraint to Uniform priors in ROQ tutorial (!884)
- Fix to CDF and PDF for SymmetricLogUniform prior (!876)
- Fix bug in evidence combination (!880)
- Typo fixes (!878, !887, !879)
- Minor bug fixes (!888)
## [1.0.2] 2020-09-14
Version 1.0.2 release of bilby
......@@ -8,7 +36,7 @@ Version 1.0.2 release of bilby
- Template for the docker files (!783)
- New delta_phase parameter (!850)
- Normalization factor to time-domain waveform plot (!867)
- JSON encoding for int and float types (!866)
- JSON encoding for int and float types (!866)
- Various minor formatting additions (!870)
### Changes
......
......@@ -4,3 +4,4 @@ from .conditional import *
from .dict import *
from .interpolated import *
from .joint import *
from .slabspike import *
......@@ -618,6 +618,7 @@ class TruncatedGaussian(Prior):
/ self.sigma / self.normalisation * self.is_in_prior_range(val)
def cdf(self, val):
val = np.atleast_1d(val)
_cdf = (erf((val - self.mu) / 2 ** 0.5 / self.sigma) - erf(
(self.minimum - self.mu) / 2 ** 0.5 / self.sigma)) / 2 / self.normalisation
_cdf[val > self.maximum] = 1
......
......@@ -110,9 +110,41 @@ def conditional_prior_factory(prior_class):
return super(ConditionalPrior, self).prob(val)
def ln_prob(self, val, **required_variables):
"""Return the natural log prior probability of val.
Parameters
----------
val: Union[float, int, array_like]
See superclass
required_variables:
Any required variables that this prior depends on
Returns
-------
float: Natural log prior probability of val
"""
self.update_conditions(**required_variables)
return super(ConditionalPrior, self).ln_prob(val)
def cdf(self, val, **required_variables):
"""Return the cdf of val.
Parameters
----------
val: Union[float, int, array_like]
See superclass
required_variables:
Any required variables that this prior depends on
Returns
-------
float: CDF of val
"""
self.update_conditions(**required_variables)
return super(ConditionalPrior, self).cdf(val)
def update_conditions(self, **required_variables):
"""
This method updates the conditional parameters (depending on the parent class
......
import numpy as np
from bilby.core.prior.base import Prior
from bilby.core.utils import logger
class SlabSpikePrior(Prior):
def __init__(self, slab, spike_location=None, spike_height=0):
"""'Slab-and-spike' prior, see e.g. https://arxiv.org/abs/1812.07259
This prior is composed of a `slab`, i.e. any common prior distribution,
and a Dirac spike at a fixed location. This can effectively be used
to emulate sampling in the number of dimensions (similar to reversible-
jump MCMC).
`SymmetricLogUniform` and `FermiDirac` are currently not supported.
Parameters
----------
slab: Prior
Any instance of a bilby prior class. All general prior attributes
from the slab are copied into the SlabSpikePrior.
Note that this hasn't been tested for conditional priors.
spike_location: float, optional
Location of the Dirac spike. Must be between minimum and maximum
of the slab. Defaults to the minimum of the slab
spike_height: float, optional
Relative weight of the spike compared to the slab. Must be
between 0 and 1. Defaults to 0, i.e. the prior is just the slab.
"""
self.slab = slab
super().__init__(name=self.slab.name, latex_label=self.slab.latex_label, unit=self.slab.unit,
minimum=self.slab.minimum, maximum=self.slab.maximum,
check_range_nonzero=self.slab.check_range_nonzero, boundary=self.slab.boundary)
self.spike_location = spike_location
self.spike_height = spike_height
try:
self.inverse_cdf_below_spike = self._find_inverse_cdf_fraction_before_spike()
except Exception as e:
logger.warning("Disregard the following warning when running tests:\n {}".format(e))
@property
def spike_location(self):
return self._spike_loc
@spike_location.setter
def spike_location(self, spike_loc):
if spike_loc is None:
spike_loc = self.minimum
if not self.minimum <= spike_loc <= self.maximum:
raise ValueError("Spike location {} not within prior domain ".format(spike_loc))
self._spike_loc = spike_loc
@property
def spike_height(self):
return self._spike_height
@spike_height.setter
def spike_height(self, spike_height):
if 0 <= spike_height <= 1:
self._spike_height = spike_height
else:
raise ValueError("Spike height must be between 0 and 1, but is {}".format(spike_height))
@property
def slab_fraction(self):
""" Relative prior weight of the slab. """
return 1 - self.spike_height
def _find_inverse_cdf_fraction_before_spike(self):
return float(self.slab.cdf(self.spike_location)) * self.slab_fraction
def rescale(self, val):
"""
'Rescale' a sample from the unit line element to the prior.
Parameters
----------
val: Union[float, int, array_like]
A random number between 0 and 1
Returns
-------
array_like: Associated prior value with input value.
"""
val = np.atleast_1d(val)
lower_indices = np.where(val < self.inverse_cdf_below_spike)[0]
intermediate_indices = np.where(np.logical_and(
self.inverse_cdf_below_spike <= val,
val <= self.inverse_cdf_below_spike + self.spike_height))[0]
higher_indices = np.where(val > self.inverse_cdf_below_spike + self.spike_height)[0]
res = np.zeros(len(val))
res[lower_indices] = self._contracted_rescale(val[lower_indices])
res[intermediate_indices] = self.spike_location
res[higher_indices] = self._contracted_rescale(val[higher_indices] - self.spike_height)
return res
def _contracted_rescale(self, val):
"""
Contracted version of the rescale function that implements the `rescale` function
on the pure slab part of the prior.
Parameters
----------
val: Union[float, int, array_like]
A random number between 0 and self.slab_fraction
Returns
-------
array_like: Associated prior value with input value.
"""
return self.slab.rescale(val / self.slab_fraction)
def prob(self, val):
"""Return the prior probability of val.
Returns np.inf for the spike location
Parameters
----------
val: Union[float, int, array_like]
Returns
-------
array_like: Prior probability of val
"""
res = self.slab.prob(val) * self.slab_fraction
res = np.atleast_1d(res)
res[np.where(val == self.spike_location)] = np.inf
return res
def ln_prob(self, val):
"""Return the Log prior probability of val.
Returns np.inf for the spike location
Parameters
----------
val: Union[float, int, array_like]
Returns
-------
array_like: Prior probability of val
"""
res = self.slab.ln_prob(val) + np.log(self.slab_fraction)
res = np.atleast_1d(res)
res[np.where(val == self.spike_location)] = np.inf
return res
def cdf(self, val):
""" Return the CDF of the prior.
This calls to the slab CDF and adds a discrete step
at the spike location.
Parameters
----------
val: Union[float, int, array_like]
Returns
-------
array_like: CDF value of val
"""
res = self.slab.cdf(val) * self.slab_fraction
res = np.atleast_1d(res)
indices_above_spike = np.where(val > self.spike_location)[0]
res[indices_above_spike] += self.spike_height
return res
......@@ -25,11 +25,11 @@ from .dnest4 import DNest4
from . import proposal
IMPLEMENTED_SAMPLERS = {
'cpnest': Cpnest, 'dynamic_dynesty': DynamicDynesty, 'dynesty': Dynesty,
'emcee': Emcee, 'kombine': Kombine, 'nestle': Nestle, 'ptemcee': Ptemcee,
'ptmcmcsampler': PTMCMCSampler, 'pymc3': Pymc3, 'pymultinest': Pymultinest,
'pypolychord': PyPolyChord, 'ultranest': Ultranest,
'fake_sampler': FakeSampler, 'dnest4': DNest4}
'cpnest': Cpnest, 'dnest4': DNest4, 'dynamic_dynesty': DynamicDynesty,
'dynesty': Dynesty, 'emcee': Emcee, 'kombine': Kombine, 'nestle': Nestle,
'ptemcee': Ptemcee, 'ptmcmcsampler': PTMCMCSampler, 'pymc3': Pymc3,
'pymultinest': Pymultinest, 'pypolychord': PyPolyChord, 'ultranest': Ultranest,
'fake_sampler': FakeSampler}
if command_line_args.sampler_help:
sampler = command_line_args.sampler_help
......
from __future__ import absolute_import
import datetime
import distutils.dir_util
import numpy as np
import os
import tempfile
from pandas import DataFrame
from ..utils import logger, command_line_args, Counter
from ..utils import logger, check_directory_exists_and_if_not_mkdir, command_line_args, Counter
from ..prior import Prior, PriorDict, DeltaFunction, Constraint
from ..result import Result, read_in_result
......@@ -541,7 +544,8 @@ class Sampler(object):
class NestedSampler(Sampler):
npoints_equiv_kwargs = ['nlive', 'nlives', 'n_live_points', 'npoints', 'npoint', 'Nlive', 'num_live_points']
npoints_equiv_kwargs = ['nlive', 'nlives', 'n_live_points', 'npoints',
'npoint', 'Nlive', 'num_live_points', 'num_particles']
walks_equiv_kwargs = ['walks', 'steps', 'nmcmc']
def reorder_loglikelihoods(self, unsorted_loglikelihoods, unsorted_samples,
......@@ -601,6 +605,27 @@ class NestedSampler(Sampler):
else:
return np.nan_to_num(-np.inf)
def _setup_run_directory(self):
"""
If using a temporary directory, the output directory is moved to the
temporary directory.
Used for Dnest4, Pymultinest, and Ultranest.
"""
if self.use_temporary_directory:
temporary_outputfiles_basename = tempfile.TemporaryDirectory().name
self.temporary_outputfiles_basename = temporary_outputfiles_basename
if os.path.exists(self.outputfiles_basename):
distutils.dir_util.copy_tree(self.outputfiles_basename, self.temporary_outputfiles_basename)
check_directory_exists_and_if_not_mkdir(temporary_outputfiles_basename)
self.kwargs["outputfiles_basename"] = self.temporary_outputfiles_basename
logger.info("Using temporary file {}".format(temporary_outputfiles_basename))
else:
check_directory_exists_and_if_not_mkdir(self.outputfiles_basename)
self.kwargs["outputfiles_basename"] = self.outputfiles_basename
logger.info("Using output file {}".format(self.outputfiles_basename))
class MCMCSampler(Sampler):
nwalkers_equiv_kwargs = ['nwalker', 'nwalkers', 'draws', 'Niter']
......
from __future__ import absolute_import
import array
import copy
import numpy as np
......@@ -88,8 +89,8 @@ class Cpnest(NestedSampler):
prior_samples = self.priors.sample()
self._update_bounds()
point = LivePoint(
self.names, [prior_samples[name]
for name in self.names])
self.names, array.array(
'f', [prior_samples[name] for name in self.names]))
return point
self._resolve_proposal_functions()
......
from __future__ import absolute_import
import os
import tempfile
import shutil
import distutils.dir_util
import signal
import time
import datetime
import sys
import numpy as np
import pandas as pd
......@@ -20,14 +18,14 @@ class _DNest4Model(object):
def __init__(self, log_likelihood_func, from_prior_func, widths, centers, highs, lows):
"""Initialize the DNest4 model.
Args:
log_likelihood_func (function): The loglikelihood function to use
during the Nested Sampling run.
from_prior_func (function): The function to use when randomly
selecting parameter vectors from the prior space.
widths (numpy.array): The approximate widths of the prior
distrbutions.
centers (numpy.array): The approximate center points of the prior
distributions.
log_likelihood_func: function
The loglikelihood function to use during the Nested Sampling run.
from_prior_func: function
The function to use when randomly selecting parameter vectors from the prior space.
widths: array_like
The approximate widths of the prior distrbutions.
centers: array_like
The approximate center points of the prior distributions.
"""
self._log_likelihood = log_likelihood_func
self._from_prior = from_prior_func
......@@ -58,9 +56,11 @@ class _DNest4Model(object):
return 0.0
def wrap(self, x, a, b):
assert b > a
return (x - a) % (b - a) + a
@staticmethod
def wrap(x, minimum, maximum):
if maximum <= minimum:
raise ValueError("maximum {} <= minimum {}, when trying to wrap coordinates".format(maximum, minimum))
return (x - minimum) % (maximum - minimum) + minimum
class DNest4(NestedSampler):
......@@ -83,8 +83,9 @@ class DNest4(NestedSampler):
The python DNest4 backend for storing the output.
Options are: 'memory' and 'csv'. If 'memory' the
DNest4 outputs are stored in memory during the run. If 'csv' the
DNest4 outputs are written out to filse with a CSV format during
DNest4 outputs are written out to files with a CSV format during
the run.
CSV backend may not be functional right now (October 2020)
num_steps: int
The number of MCMC iterations to run
new_level_interval: int
......@@ -97,53 +98,20 @@ class DNest4(NestedSampler):
Set the seed for the C++ random number generator
verbose: Bool
If True, prints information during run
TO DO: add equivalent args for num_particles (nlive, etc.)
Add sampling time functions
"""
default_kwargs = dict(
max_num_levels=20,
num_steps=500, # Number of iterations
new_level_interval=10000,
num_per_step=10000,
thread_steps=1,
num_particles=1000,
lam=10.0,
beta=100,
seed=None,
verbose=True,
outputfiles_basename=None,
# backend_callback=None, # for checkpointing in dnest5
backend='memory', # csv is currently bugged right now
# could change max_num_levels based on snr
)
def __init__(
self,
likelihood,
priors,
outdir="outdir",
label="label",
use_ratio=False,
plot=False,
exit_code=77,
skip_import_verification=False,
temporary_directory=True,
resume=True,
**kwargs
):
default_kwargs = dict(max_num_levels=20, num_steps=500,
new_level_interval=10000, num_per_step=10000,
thread_steps=1, num_particles=1000, lam=10.0,
beta=100, seed=None, verbose=True, outputfiles_basename=None,
backend='memory')
def __init__(self, likelihood, priors, outdir="outdir", label="label", use_ratio=False, plot=False,
exit_code=77, skip_import_verification=False, temporary_directory=True, **kwargs):
super(DNest4, self).__init__(
likelihood=likelihood,
priors=priors,
outdir=outdir,
label=label,
use_ratio=use_ratio,
plot=plot,
skip_import_verification=skip_import_verification,
exit_code=exit_code,
**kwargs
)
likelihood=likelihood, priors=priors, outdir=outdir, label=label,
use_ratio=use_ratio, plot=plot, skip_import_verification=skip_import_verification,
exit_code=exit_code, **kwargs)
self.num_particles = self.kwargs["num_particles"]
self.max_num_levels = self.kwargs["max_num_levels"]
......@@ -151,6 +119,13 @@ class DNest4(NestedSampler):
self._backend = self.kwargs["backend"]
self.use_temporary_directory = temporary_directory
self.start_time = np.nan
self.sampler = None
self._information = np.nan
self._last_live_sample_info = np.nan
self._outputfiles_basename = None
self._temporary_outputfiles_basename = None
signal.signal(signal.SIGTERM, self.write_current_state_and_exit)
signal.signal(signal.SIGINT, self.write_current_state_and_exit)
signal.signal(signal.SIGALRM, self.write_current_state_and_exit)
......@@ -180,26 +155,19 @@ class DNest4(NestedSampler):
self._highs = np.array(highs)
self._lows = np.array(lows)
self._from_prior = self.get_random_draw_from_prior
self._dnest4_model = _DNest4Model(self.log_likelihood, self._from_prior, self._widths,
self._dnest4_model = _DNest4Model(self.log_likelihood, self.get_random_draw_from_prior, self._widths,
self._centers, self._highs, self._lows)
def _set_backend(self):
import dnest4
if self._backend == 'csv':
# for CSVBackend, which is output data to disk
backend = dnest4.backends.CSVBackend("{}/dnest4{}/".format(self.outdir, self.label), sep=" ")
# change to original
return dnest4.backends.CSVBackend("{}/dnest4{}/".format(self.outdir, self.label), sep=" ")
else:
# for the MemoryBackend, which is output data to memory
backend = dnest4.backends.MemoryBackend()
return backend
return dnest4.backends.MemoryBackend()
def _set_dnest4_kwargs(self):
dnest4_keys = ["num_steps", "new_level_interval", "lam", "beta", "seed"]
self.dnest4_kwargs = {key: self.kwargs[key] for key in dnest4_keys}
return self.dnest4_kwargs
def run_sampler(self):
import dnest4
......@@ -233,17 +201,11 @@ class DNest4(NestedSampler):
if self._backend == 'memory':
self._last_live_sample_info = pd.DataFrame(self.sampler.backend.sample_info[-1])
self.result.log_likelihood_evaluations = self._last_live_sample_info['log_likelihood']
self.result.samples = np.array(self.sampler.backend.posterior_samples)
print("here")
print(self.sampler.backend.posterior_samples)
print(self.result.samples)
else:
sample_info_path = './' + self.kwargs["outputfiles_basename"] + '/sample_info.txt'
sample_info = np.genfromtxt(sample_info_path, comments='#', names=True)
self.result.log_likelihood_evaluations = sample_info['log_likelihood']
self.result.samples = np.array(self.sampler.backend.posterior_samples)
self.result.sampler_output = out
......@@ -262,36 +224,7 @@ class DNest4(NestedSampler):
def _verify_kwargs_against_default_kwargs(self):
self.outputfiles_basename = self.kwargs.pop("outputfiles_basename", None)
# if self.kwargs['backend_callback'] is None:
# self.kwargs['backend_callback'] = self._backend_callback
NestedSampler._verify_kwargs_against_default_kwargs(self)
# def _backend_callback(self, *args, **kwargs):
# if self.use_temporary_directory:
# self._copy_temporary_directory_contents_to_proper_path()
# self._calculate_and_save_sampling_time()
def _setup_run_directory(self):
"""
If using a temporary directory, the output directory is moved to the
temporary directory.
"""
if self.use_temporary_directory:
temporary_outputfiles_basename = tempfile.TemporaryDirectory().name
self.temporary_outputfiles_basename = temporary_outputfiles_basename
if os.path.exists(self.outputfiles_basename):
distutils.dir_util.copy_tree(self.outputfiles_basename, self.temporary_outputfiles_basename)
check_directory_exists_and_if_not_mkdir(temporary_outputfiles_basename)
self.kwargs["outputfiles_basename"] = self.temporary_outputfiles_basename
logger.info("Using temporary file {}".format(temporary_outputfiles_basename))
else:
check_directory_exists_and_if_not_mkdir(self.outputfiles_basename)
self.kwargs["outputfiles_basename"] = self.outpuxtfiles_basename
logger.info("Using output file {}".format(self.outputfiles_basename))
super(DNest4, self)._verify_kwargs_against_default_kwargs()
def _check_and_load_sampling_time_file(self):
self.time_file_path = self.kwargs["outputfiles_basename"] + '/sampling_time.dat'
......@@ -355,7 +288,7 @@ class DNest4(NestedSampler):
self._calculate_and_save_sampling_time()
if self.use_temporary_directory:
self._move_temporary_directory_to_proper_path()
os._exit(self.exit_code)
sys.exit(self.exit_code)
def _move_temporary_directory_to_proper_path(self):
"""
......
import importlib
import os
import tempfile
import shutil
import distutils.dir_util
import signal
import time
import datetime
import sys
import numpy as np
......@@ -175,7 +175,7 @@ class Pymultinest(NestedSampler):
self._calculate_and_save_sampling_time()
if self.use_temporary_directory:
self._move_temporary_directory_to_proper_path()
os._exit(self.exit_code)
sys.exit(self.exit_code)
def _copy_temporary_directory_contents_to_proper_path(self):
"""
......@@ -239,26 +239,6 @@ class Pymultinest(NestedSampler):
self.result.sampling_time = datetime.timedelta(seconds=self.total_sampling_time)
return self.result
def _setup_run_directory(self):
"""
If using a temporary directory, the output directory is moved to the
temporary directory.
"""
if self.use_temporary_directory:
temporary_outputfiles_basename = tempfile.TemporaryDirectory().name
self.temporary_outputfiles_basename = temporary_outputfiles_basename
if os.path.exists(self.outputfiles_basename):
distutils.dir_util.copy_tree(self.outputfiles_basename, self.temporary_outputfiles_basename)
check_directory_exists_and_if_not_mkdir(temporary_outputfiles_basename)
self.kwargs["outputfiles_basename"] = self.temporary_outputfiles_basename
logger.info("Using temporary file {}".format(temporary_outputfiles_basename))
else:
check_directory_exists_and_if_not_mkdir(self.outputfiles_basename)
self.kwargs["outputfiles_basename"] = self.outputfiles_basename
logger.info("Using output file {}".format(self.outputfiles_basename))
def _check_and_load_sampling_time_file(self):
self.time_file_path = self.kwargs["outputfiles_basename"] + '/sampling_time.dat'
if os.path.exists(self.time_file_path):
......
......@@ -6,7 +6,6 @@ import inspect
import os
import shutil
import signal
import tempfile
import time
import numpy as np
......@@ -287,6 +286,7 @@ class Ultranest(NestedSampler):
stepsampler = self.kwargs.pop("step_sampler", None)
self._setup_run_directory()
self.kwargs["log_dir"] = self.kwargs.pop("outputfiles_basename")
self._check_and_load_sampling_time_file()
# use reactive nested sampler when no live points are given
......@@ -326,30 +326,6 @@ class Ultranest(NestedSampler):
return self.result
def _setup_run_directory(self):
"""
If using a temporary directory, the output directory is moved to the
temporary directory and symlinked back.
"""
if self.use_temporary_directory:
temporary_outputfiles_basename = tempfile.TemporaryDirectory().name
self.temporary_outputfiles_basename = temporary_outputfiles_basename
if os.path.exists(self.outputfiles_basename):
distutils.dir_util.copy_tree(
self.outputfiles_basename, self.temporary_outputfiles_basename
)
check_directory_exists_and_if_not_mkdir(temporary_outputfiles_basename)
self.kwargs["log_dir"] = self.temporary_outputfiles_basename
logger.info(
"Using temporary file {}".format(temporary_outputfiles_basename)
)
else:
check_directory_exists_and_if_not_mkdir(self.outputfiles_basename)
self.kwargs["log_dir"] = self.outputfiles_basename
logger.info("Using output file {}".format(self.outputfiles_basename))
def _clean_up_run_directory(self):
if self.use_temporary_directory:
self._move_temporary_directory_to_proper_path()
......
......@@ -4,11 +4,13 @@ import copy
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline, interp1d
from scipy.integrate import cumtrapz
from scipy.special import hyp2f1
from scipy.stats import norm
from ..core.prior import (PriorDict, Uniform, Prior, DeltaFunction, Gaussian,
Interped, Constraint, conditional_prior_factory,
BaseJointPriorDist, JointPrior, JointPriorDistError)
BaseJointPriorDist, JointPrior, JointPriorDistError,
PowerLaw)
from ..core.utils import infer_args_from_method, logger
from .conversion import (
convert_to_lal_binary_black_hole_parameters,
......@@ -285,6 +287,93 @@ class UniformSourceFrame(Cosmological):
return zs, p_dz
class UniformInComponentsChirpMass(PowerLaw):
def __init__(self, minimum, maximum, name='chirp_mass',
latex_label='$\mathcal{M}$', unit=None, boundary=None):
"""
Prior distribution for chirp mass which is uniform in component masses.
This is useful when chirp mass and mass ratio are sampled while the
prior is uniform in component masses.
Parameters
----------
minimum : float
The minimum of chirp mass
maximum : float
The maximum of chirp mass
name: see superclass
latex_label: see superclass
unit: see superclass
boundary: see superclass
"""
super(UniformInComponentsChirpMass, self).__init__(
alpha=1., minimum=minimum, maximum=maximum,
name=name, latex_label=latex_label, unit=unit, boundary=boundary)
class WrappedInterp1d(interp1d):
""" A wrapper around scipy interp1d which sets equality-by-instantiation """
def __eq__(self, other):
for key in self.__dict__:
if type(self.__dict__[key]) is np.ndarray:
if not np.array_equal(self.__dict__[key], other.__dict__[key]):
return False
elif key == "_spline":
pass
elif getattr(self, key) != getattr(other, key):
return False
return True
class UniformInComponentsMassRatio(Prior):
def __init__(self, minimum, maximum, name='mass_ratio', latex_label='$q$',
unit=None, boundary=None):
"""
Prior distribution for mass ratio which is uniform in component masses.
This is useful when chirp mass and mass ratio are sampled while the
prior is uniform in component masses.
Parameters
----------
minimum : float
The minimum of mass ratio
maximum : float
The maximum of mass ratio
name: see superclass
latex_label: see superclass
unit: see superclass
boundary: see superclass
"""
super(UniformInComponentsMassRatio, self).__init__(
minimum=minimum, maximum=maximum, name=name,
latex_label=latex_label, unit=unit, boundary=boundary)
self.norm = self._integral(maximum) - self._integral(minimum)
qs = np.linspace(minimum, maximum, 1000)
self.icdf = WrappedInterp1d(
self.cdf(qs), qs, kind='cubic',
bounds_error=False, fill_value=(minimum, maximum))
@staticmethod
def _integral(q):
return -5. * q**(-1. / 5.) * hyp2f1(-2. / 5., -1. / 5., 4. / 5., -q)
def cdf(self, val):
return (self._integral(val) - self._integral(self.minimum)) / self.norm
def rescale(self, val):
self.test_valid_for_rescaling(val)
return self.icdf(val)
def prob(self, val):
in_prior = (val >= self.minimum) & (val <= self.maximum)
return (1. + val)**(2. / 5.) / (val**(6. / 5.)) / self.norm * in_prior
class AlignedSpin(Interped):
def __init__(self, a_prior=Uniform(0, 1), z_prior=Uniform(-1, 1),
......
FROM continuumio/miniconda3
FROM containers.ligo.org/docker/base:conda
LABEL name="bilby Base miniconda3" \
maintainer="Gregory Ashton <gregory.ashton@ligo.org>"
......
# This dockerfile is written automatically and should not be modified by hand.
FROM continuumio/miniconda3
FROM containers.ligo.org/docker/base:conda
LABEL name="bilby Base miniconda3" \
maintainer="Gregory Ashton <gregory.ashton@ligo.org>"
......
# This dockerfile is written automatically and should not be modified by hand.
FROM continuumio/miniconda3
FROM containers.ligo.org/docker/base:conda
LABEL name="bilby Base miniconda3" \
maintainer="Gregory Ashton <gregory.ashton@ligo.org>"
......
# This dockerfile is written automatically and should not be modified by hand.
FROM continuumio/miniconda3
FROM containers.ligo.org/docker/base:conda
LABEL name="bilby Base miniconda3" \
maintainer="Gregory Ashton <gregory.ashton@ligo.org>"
......
# This dockerfile is written automatically and should not be modified by hand.
FROM continuumio/miniconda3
FROM containers.ligo.org/docker/base:conda
LABEL name="bilby Base miniconda3" \
maintainer="Gregory Ashton <gregory.ashton@ligo.org>"
......
......@@ -45,7 +45,7 @@ which provides extra functionality. For example, to sample from the prior:
.. code:: python
>>> priors = bilby.core.priors.PriorDict()
>>> priors = bilby.core.prior.PriorDict()
>>> priors['a'] = bilby.prior.Uniform(minimum=0, maximum=10, name='a')
>>> priors['b'] = bilby.prior.Uniform(minimum=0, maximum=10, name='b')
>>> priors.sample()
......@@ -89,7 +89,7 @@ matrix and standard deviations, e.g.:
>>> names = ['a', 'b'] # set the parameter names
>>> mu = [0., 5.] # the means of the parameters
>>> cov = [[2., 0.7], [0.7, 3.]] # the covariance matrix
>>> mvg = bilby.core.priors.MultivariateGaussianDist(names, mus=mu, covs=cov)
>>> mvg = bilby.core.prior.MultivariateGaussianDist(names, mus=mu, covs=cov)
It is also possible to define a mixture model of multiple multivariate Gaussian modes of
different weights if required, e.g.:
......@@ -100,7 +100,7 @@ different weights if required, e.g.:
>>> mu = [[0., 5.], [2., 7.]] # the means of the parameters
>>> cov = [[[2., 0.7], [0.7, 3.]], [[1., -0.9], [-0.9, 5.]]] # the covariance matrix
>>> weights = [0.3, 0.7] # weights of each mode
>>> mvg = bilby.core.priors.MultivariateGaussianDist(names, mus=mu, covs=cov, nmodes=2, weights=weights)
>>> mvg = bilby.core.prior.MultivariateGaussianDist(names, mus=mu, covs=cov, nmodes=2, weights=weights)
The distribution can also have hard bounds on each parameter by supplying them.
......