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 (10)
Showing
with 225 additions and 139 deletions
......@@ -14,6 +14,7 @@
## [0.4.0] 2019-02-15
### Changed
- Changed the logic around redundancy tests in the `PriorDict` classes
- Fixed an accidental addition of astropy as a first-class dependency and added a check for missing dependencies to the C.I.
- Fixed a bug in the "create-your-own-time-domain-model" example
- Added citation guide to the readme
......@@ -33,7 +34,7 @@
- Improve the load_data_from_cache_file method
### Removed
-
- Removed deprecated `PriorSet` classes. Use `PriorDict` instead.
## [0.3.5] 2019-01-25
......
......@@ -245,10 +245,28 @@ class PriorDict(OrderedDict):
"""
return [self[key].rescale(sample) for key, sample in zip(keys, theta)]
def test_redundancy(self, key):
def test_redundancy(self, key, disable_logging=False):
"""Empty redundancy test, should be overwritten in subclasses"""
return False
def test_has_redundant_keys(self):
"""
Test whether there are redundant keys in self.
Return
------
bool: Whether there are redundancies or not
"""
redundant = False
for key in self:
temp = self.copy()
del temp[key]
if temp.test_redundancy(key, disable_logging=True):
logger.warning('{} is a redundant key in this {}.'
.format(key, self.__class__.__name__))
redundant = True
return redundant
def copy(self):
"""
We have to overwrite the copy method as it fails due to the presence of
......
......@@ -8,6 +8,7 @@ import numpy as np
import deepdish
import pandas as pd
import corner
import json
import scipy.stats
import matplotlib
import matplotlib.pyplot as plt
......@@ -19,7 +20,7 @@ from .utils import (logger, infer_parameters_from_function,
from .prior import Prior, PriorDict, DeltaFunction
def result_file_name(outdir, label):
def result_file_name(outdir, label, extension='json'):
""" Returns the standard filename used for a result file
Parameters
......@@ -28,17 +29,27 @@ def result_file_name(outdir, label):
Name of the output directory
label: str
Naming scheme of the output file
extension: str, optional
Whether to save as `hdf5` or `json`
Returns
-------
str: File name of the output file
"""
return '{}/{}_result.h5'.format(outdir, label)
if extension == 'hdf5':
return '{}/{}_result.h5'.format(outdir, label)
else:
return '{}/{}_result.json'.format(outdir, label)
def read_in_result(filename=None, outdir=None, label=None):
""" Wrapper to bilby.core.result.Result.from_hdf5 """
return Result.from_hdf5(filename=filename, outdir=outdir, label=label)
""" Wrapper to bilby.core.result.Result.from_hdf5
or bilby.core.result.Result.from_json """
try:
result = Result.from_json(filename=filename, outdir=outdir, label=label)
except (IOError, ValueError):
result = Result.from_hdf5(filename=filename, outdir=outdir, label=label)
return result
class Result(object):
......@@ -155,7 +166,7 @@ class Result(object):
if (outdir is None) and (label is None):
raise ValueError("No information given to load file")
else:
filename = result_file_name(outdir, label)
filename = result_file_name(outdir, label, extension='hdf5')
if os.path.isfile(filename):
dictionary = deepdish.io.load(filename)
# Some versions of deepdish/pytables return the dictionanary as
......@@ -169,6 +180,50 @@ class Result(object):
else:
raise IOError("No result '{}' found".format(filename))
@classmethod
def from_json(cls, filename=None, outdir=None, label=None):
""" Read in a saved .json data file
Parameters
----------
filename: str
If given, try to load from this filename
outdir, label: str
If given, use the default naming convention for saved results file
Returns
-------
result: bilby.core.result.Result
Raises
-------
ValueError: If no filename is given and either outdir or label is None
If no bilby.core.result.Result is found in the path
"""
if filename is None:
if (outdir is None) and (label is None):
raise ValueError("No information given to load file")
else:
filename = result_file_name(outdir, label)
if os.path.isfile(filename):
dictionary = json.load(open(filename, 'r'))
for key in dictionary.keys():
# Convert some dictionaries back to DataFrames
if key in ['posterior', 'nested_samples']:
dictionary[key] = pd.DataFrame.from_dict(dictionary[key])
# Convert the loaded priors to bilby prior type
if key == 'priors':
for param in dictionary[key].keys():
dictionary[key][param] = str(dictionary[key][param])
dictionary[key] = PriorDict(dictionary[key])
try:
return cls(**dictionary)
except TypeError as e:
raise IOError("Unable to load dictionary, error={}".format(e))
else:
raise IOError("No result '{}' found".format(filename))
def __str__(self):
"""Print a summary """
if getattr(self, 'posterior', None) is not None:
......@@ -303,9 +358,9 @@ class Result(object):
pass
return dictionary
def save_to_file(self, overwrite=False, outdir=None):
def save_to_file(self, overwrite=False, outdir=None, extension='json'):
"""
Writes the Result to a deepdish h5 file
Writes the Result to a json or deepdish h5 file
Parameters
----------
......@@ -314,9 +369,11 @@ class Result(object):
default=False
outdir: str, optional
Path to the outdir. Default is the one stored in the result object.
extension: str, optional
Whether to save as hdf5 instead of json
"""
outdir = self._safe_outdir_creation(outdir, self.save_to_file)
file_name = result_file_name(outdir, self.label)
file_name = result_file_name(outdir, self.label, extension)
if os.path.isfile(file_name):
if overwrite:
......@@ -341,8 +398,19 @@ class Result(object):
if hasattr(dictionary['sampler_kwargs'][key], '__call__'):
dictionary['sampler_kwargs'][key] = str(dictionary['sampler_kwargs'])
# Convert to json saveable format
if extension != 'hdf5':
for key in dictionary.keys():
if isinstance(dictionary[key], pd.core.frame.DataFrame):
dictionary[key] = dictionary[key].to_dict()
elif isinstance(dictionary[key], np.ndarray):
dictionary[key] = dictionary[key].tolist()
try:
deepdish.io.save(file_name, dictionary)
if extension == 'hdf5':
deepdish.io.save(file_name, dictionary)
else:
json.dump(dictionary, open(file_name, 'w'), indent=2)
except Exception as e:
logger.error("\n\n Saving the data has failed with the "
"following message:\n {} \n\n".format(e))
......
......@@ -85,6 +85,7 @@ def run_sampler(likelihood, priors=None, label='label', outdir='outdir',
overwritten.
save: bool
If true, save the priors and results to disk.
If hdf5, save as an hdf5 file instead of json.
result_class: bilby.core.result.Result, or child of
The result class to use. By default, `bilby.core.result.Result` is used,
but objects which inherit from this class can be given providing
......@@ -183,7 +184,10 @@ def run_sampler(likelihood, priors=None, label='label', outdir='outdir',
result.samples_to_posterior(likelihood=likelihood, priors=priors,
conversion_function=conversion_function)
if save:
if save == 'hdf5':
result.save_to_file(extension='hdf5')
logger.info("Results saved to {}/".format(outdir))
elif save:
result.save_to_file()
logger.info("Results saved to {}/".format(outdir))
if plot:
......
......@@ -241,6 +241,10 @@ class Sampler(object):
Likelihood can't be evaluated.
"""
if self.priors.test_has_redundant_keys():
raise IllegalSamplingSetError("Your sampling set contains redundant parameters.")
self._check_if_priors_can_be_sampled()
try:
t1 = datetime.datetime.now()
......@@ -502,3 +506,7 @@ class SamplerError(Error):
class SamplerNotInstalledError(SamplerError):
""" Base class for Error raised by not installed samplers """
class IllegalSamplingSetError(Error):
""" Class for illegal sets of sampling parameters """
......@@ -215,7 +215,7 @@ def convert_to_lal_binary_black_hole_parameters(parameters):
converted_parameters['phi_jl'] = 0.0
converted_parameters['phi_12'] = 0.0
for angle in ['tilt_1', 'tilt_2', 'iota']:
for angle in ['tilt_1', 'tilt_2', 'theta_jn']:
cos_angle = str('cos_' + angle)
if cos_angle in converted_parameters.keys():
converted_parameters[angle] =\
......@@ -827,7 +827,7 @@ def generate_component_spins(sample):
Parameters
----------
sample: A dictionary with the necessary spin conversion parameters:
'iota', 'phi_jl', 'tilt_1', 'tilt_2', 'phi_12', 'a_1', 'a_2', 'mass_1',
'theta_jn', 'phi_jl', 'tilt_1', 'tilt_2', 'phi_12', 'a_1', 'a_2', 'mass_1',
'mass_2', 'reference_frequency', 'phase'
Returns
......@@ -837,7 +837,7 @@ def generate_component_spins(sample):
"""
output_sample = sample.copy()
spin_conversion_parameters =\
['iota', 'phi_jl', 'tilt_1', 'tilt_2', 'phi_12', 'a_1', 'a_2', 'mass_1',
['theta_jn', 'phi_jl', 'tilt_1', 'tilt_2', 'phi_12', 'a_1', 'a_2', 'mass_1',
'mass_2', 'reference_frequency', 'phase']
if all(key in output_sample.keys() for key in spin_conversion_parameters):
output_sample['iota'], output_sample['spin_1x'],\
......@@ -845,7 +845,7 @@ def generate_component_spins(sample):
output_sample['spin_2x'], output_sample['spin_2y'],\
output_sample['spin_2z'] =\
transform_precessing_spins(
output_sample['iota'], output_sample['phi_jl'],
output_sample['theta_jn'], output_sample['phi_jl'],
output_sample['tilt_1'], output_sample['tilt_2'],
output_sample['phi_12'], output_sample['a_1'],
output_sample['a_2'],
......
......@@ -469,16 +469,20 @@ class InterferometerStrainData(object):
"""
data = self.time_domain_strain
if analysis_segment_start_time is not None:
logger.info("Removing analysis segment data from the PSD data")
analysis_segment_end_time = analysis_segment_start_time + fft_length
idxs = (
(self.time_array < analysis_segment_start_time) +
(self.time_array > analysis_segment_end_time))
data = self.time_domain_strain[idxs]
else:
data = self.time_domain_strain
inside = (analysis_segment_start_time > self.time_array[0] +
analysis_segment_end_time < self.time_array[-1])
if inside:
logger.info("Removing analysis segment data from the PSD data")
idxs = (
(self.time_array < analysis_segment_start_time) +
(self.time_array > analysis_segment_end_time))
data = data[idxs]
# WARNING this line can cause issues if the data is non-contiguous
strain = gwpy.timeseries.TimeSeries(data=data, sample_rate=self.sampling_frequency)
psd_alpha = 2 * self.roll_off / fft_length
logger.info(
......
......@@ -207,63 +207,48 @@ class BBHPriorDict(PriorDict):
filename = os.path.join(os.path.dirname(__file__), 'prior_files', filename)
PriorDict.__init__(self, dictionary=dictionary, filename=filename)
def test_redundancy(self, key):
def test_redundancy(self, key, disable_logging=False):
"""
Test whether adding the key would add be redundant.
Already existing keys return True.
Parameters
----------
key: str
The key to test.
disable_logging: bool, optional
Disable logging in this function call. Default is False.
Return
------
redundant: bool
Whether the key is redundant or not
"""
redundant = False
if key in self:
logger.debug('{} already in prior'.format(key))
return redundant
return True
mass_parameters = {'mass_1', 'mass_2', 'chirp_mass', 'total_mass', 'mass_ratio', 'symmetric_mass_ratio'}
spin_magnitude_parameters = {'a_1', 'a_2'}
spin_tilt_1_parameters = {'tilt_1', 'cos_tilt_1'}
spin_tilt_2_parameters = {'tilt_2', 'cos_tilt_2'}
spin_azimuth_parameters = {'phi_1', 'phi_2', 'phi_12', 'phi_jl'}
inclination_parameters = {'iota', 'cos_iota'}
inclination_parameters = {'theta_jn', 'cos_theta_jn'}
distance_parameters = {'luminosity_distance', 'comoving_distance', 'redshift'}
for parameter_set in [mass_parameters, spin_magnitude_parameters, spin_azimuth_parameters]:
if key in parameter_set:
if len(parameter_set.intersection(self)) > 2:
redundant = True
logger.warning('{} in prior. This may lead to unexpected behaviour.'.format(
parameter_set.intersection(self)))
break
elif len(parameter_set.intersection(self)) == 2:
redundant = True
break
for parameter_set in [inclination_parameters, distance_parameters, spin_tilt_1_parameters,
spin_tilt_2_parameters]:
for independent_parameters, parameter_set in \
zip([2, 2, 1, 1, 1, 1],
[mass_parameters, spin_azimuth_parameters,
spin_tilt_1_parameters, spin_tilt_2_parameters,
inclination_parameters, distance_parameters]):
if key in parameter_set:
if len(parameter_set.intersection(self)) > 1:
redundant = True
logger.warning('{} in prior. This may lead to unexpected behaviour.'.format(
parameter_set.intersection(self)))
break
elif len(parameter_set.intersection(self)) == 1:
redundant = True
break
return redundant
class BBHPriorSet(BBHPriorDict):
def __init__(self, dictionary=None, filename=None):
""" DEPRECATED: USE BBHPriorDict INSTEAD"""
logger.warning("The name 'BBHPriorSet' is deprecated use 'BBHPriorDict' instead")
super(BBHPriorSet, self).__init__(dictionary, filename)
if len(parameter_set.intersection(self)) >= independent_parameters:
logger.disabled = disable_logging
logger.warning('{} already in prior. '
'This may lead to unexpected behaviour.'
.format(parameter_set.intersection(self)))
logger.disabled = False
return True
return False
class BNSPriorDict(PriorDict):
......@@ -286,34 +271,32 @@ class BNSPriorDict(PriorDict):
filename = os.path.join(os.path.dirname(__file__), 'prior_files', filename)
PriorDict.__init__(self, dictionary=dictionary, filename=filename)
def test_redundancy(self, key):
logger.info("Performing redundancy check using BBHPriorDict().test_redundancy")
bbh_redundancy = BBHPriorDict().test_redundancy(key)
def test_redundancy(self, key, disable_logging=False):
logger.disabled = disable_logging
logger.info("Performing redundancy check using BBHPriorDict(self).test_redundancy")
logger.disabled = False
bbh_redundancy = BBHPriorDict(self).test_redundancy(key)
if bbh_redundancy:
return True
redundant = False
tidal_parameters =\
tidal_parameters = \
{'lambda_1', 'lambda_2', 'lambda_tilde', 'delta_lambda'}
if key in tidal_parameters:
if len(tidal_parameters.intersection(self)) > 2:
redundant = True
logger.warning('{} in prior. This may lead to unexpected behaviour.'.format(
tidal_parameters.intersection(self)))
logger.disabled = disable_logging
logger.warning('{} already in prior. '
'This may lead to unexpected behaviour.'
.format(tidal_parameters.intersection(self)))
logger.disabled = False
elif len(tidal_parameters.intersection(self)) == 2:
redundant = True
return redundant
class BNSPriorSet(BNSPriorDict):
def __init__(self, dictionary=None, filename=None):
""" DEPRECATED: USE BNSPriorDict INSTEAD"""
super(BNSPriorSet, self).__init__(dictionary, filename)
logger.warning("The name 'BNSPriorSet' is deprecated use 'BNSPriorDict' instead")
Prior._default_latex_labels = {
'mass_1': '$m_1$',
'mass_2': '$m_2$',
......@@ -334,6 +317,8 @@ Prior._default_latex_labels = {
'ra': '$\mathrm{RA}$',
'iota': '$\iota$',
'cos_iota': '$\cos\iota$',
'theta_jn': '$\\theta_{JN}$',
'cos_theta_jn': '$\cos\\theta_{JN}$',
'psi': '$\psi$',
'phase': '$\phi$',
'geocent_time': '$t_c$',
......@@ -418,13 +403,13 @@ class CalibrationPriorDict(PriorDict):
nodes = np.logspace(np.log10(minimum_frequency),
np.log10(maximum_frequency), n_nodes)
amplitude_mean_nodes =\
amplitude_mean_nodes = \
UnivariateSpline(frequency_array, amplitude_median)(nodes)
amplitude_sigma_nodes =\
amplitude_sigma_nodes = \
UnivariateSpline(frequency_array, amplitude_sigma)(nodes)
phase_mean_nodes =\
phase_mean_nodes = \
UnivariateSpline(frequency_array, phase_median)(nodes)
phase_sigma_nodes =\
phase_sigma_nodes = \
UnivariateSpline(frequency_array, phase_sigma)(nodes)
prior = CalibrationPriorDict()
......@@ -506,11 +491,3 @@ class CalibrationPriorDict(PriorDict):
latex_label=latex_label)
return prior
class CalibrationPriorSet(CalibrationPriorDict):
def __init__(self, dictionary=None, filename=None):
""" DEPRECATED: USE BNSPriorDict INSTEAD"""
super(CalibrationPriorSet, self).__init__(dictionary, filename)
logger.warning("The name 'CalibrationPriorSet' is deprecated use 'CalibrationPriorDict' instead")
......@@ -10,7 +10,7 @@ phi_jl = Uniform(name='phi_jl', minimum=0, maximum=2 * np.pi)
luminosity_distance = bilby.gw.prior.UniformComovingVolume(name='luminosity_distance', minimum=1e2, maximum=1e3, unit='Mpc')
dec = Cosine(name='dec')
ra = Uniform(name='ra', minimum=0, maximum=2 * np.pi)
iota = Sine(name='iota')
theta_jn = Sine(name='theta_jn')
psi = Uniform(name='psi', minimum=0, maximum=np.pi)
phase = Uniform(name='phase', minimum=0, maximum=2 * np.pi)
geocent_time = Uniform(1126259462.322, 1126259462.522, name='geocent_time', unit='$s$')
......
......@@ -19,7 +19,7 @@ phi_jl = Uniform(name='phi_jl', minimum=0, maximum=2 * np.pi)
luminosity_distance = bilby.gw.prior.UniformComovingVolume(name='luminosity_distance', minimum=1e2, maximum=5e3, unit='Mpc')
dec = Cosine(name='dec')
ra = Uniform(name='ra', minimum=0, maximum=2 * np.pi)
iota = Sine(name='iota')
# cos_iota = Uniform(name='cos_iota', minimum=-1, maximum=1)
theta_jn = Sine(name='theta_jn')
# cos_theta_jn = Uniform(name='cos_theta_jn', minimum=-1, maximum=1)
psi = Uniform(name='psi', minimum=0, maximum=np.pi)
phase = Uniform(name='phase', minimum=0, maximum=2 * np.pi)
......@@ -13,8 +13,8 @@ chi_2 = bilby.gw.prior.AlignedSpin(a_prior=Uniform(0, 0.05), z_prior=Uniform(-1
luminosity_distance = bilby.gw.prior.UniformComovingVolume(name='luminosity_distance', minimum=10, maximum=500, unit='Mpc')
dec = Cosine(name='dec')
ra = Uniform(name='ra', minimum=0, maximum=2 * np.pi)
iota = Sine(name='iota')
# cos_iota = Uniform(name='cos_iota', minimum=-1, maximum=1)
theta_jn = Sine(name='theta_jn')
# cos_theta_jn = Uniform(name='cos_theta_jn', minimum=-1, maximum=1)
psi = Uniform(name='psi', minimum=0, maximum=np.pi)
phase = Uniform(name='phase', minimum=0, maximum=2 * np.pi)
lambda_1 = Uniform(name='lambda_1', minimum=0, maximum=3000 )
......
......@@ -21,8 +21,8 @@ except ImportError:
def lal_binary_black_hole(
frequency_array, mass_1, mass_2, luminosity_distance, a_1, tilt_1, phi_12, a_2, tilt_2, phi_jl,
iota, phase, **kwargs):
frequency_array, mass_1, mass_2, luminosity_distance, a_1, tilt_1,
phi_12, a_2, tilt_2, phi_jl, theta_jn, phase, **kwargs):
""" A Binary Black Hole waveform model using lalsimulation
Parameters
......@@ -40,15 +40,16 @@ def lal_binary_black_hole(
tilt_1: float
Primary tilt angle
phi_12: float
Azimuthal angle between the two component spins
a_2: float
Dimensionless secondary spin magnitude
tilt_2: float
Secondary tilt angle
phi_jl: float
iota: float
Orbital inclination
Azimuthal angle between the total binary angular momentum and the
orbital angular momentum
theta_jn: float
Angle between the total binary angular momentum and the line of sight
phase: float
The phase at coalescence
kwargs: dict
......@@ -59,7 +60,8 @@ def lal_binary_black_hole(
dict: A dictionary with the plus and cross polarisation strain modes
"""
waveform_kwargs = dict(waveform_approximant='IMRPhenomPv2', reference_frequency=50.0,
waveform_kwargs = dict(waveform_approximant='IMRPhenomPv2',
reference_frequency=50.0,
minimum_frequency=20.0)
waveform_kwargs.update(kwargs)
waveform_approximant = waveform_kwargs['waveform_approximant']
......@@ -80,10 +82,11 @@ def lal_binary_black_hole(
spin_2x = 0
spin_2y = 0
spin_2z = a_2
iota = theta_jn
else:
iota, spin_1x, spin_1y, spin_1z, spin_2x, spin_2y, spin_2z = (
lalsim_SimInspiralTransformPrecessingNewInitialConditions(
iota, phi_jl, tilt_1, tilt_2, phi_12, a_1, a_2, mass_1,
theta_jn, phi_jl, tilt_1, tilt_2, phi_12, a_1, a_2, mass_1,
mass_2, reference_frequency, phase))
longitude_ascending_nodes = 0.0
......@@ -114,7 +117,8 @@ def lal_binary_black_hole(
def lal_eccentric_binary_black_hole_no_spins(
frequency_array, mass_1, mass_2, eccentricity, luminosity_distance, iota, phase, **kwargs):
frequency_array, mass_1, mass_2, eccentricity, luminosity_distance,
theta_jn, phase, **kwargs):
""" Eccentric binary black hole waveform model using lalsimulation (EccentricFD)
Parameters
......@@ -129,7 +133,7 @@ def lal_eccentric_binary_black_hole_no_spins(
The orbital eccentricity of the system
luminosity_distance: float
The luminosity distance in megaparsec
iota: float
theta_jn: float
Orbital inclination
phase: float
The phase at coalescence
......@@ -161,6 +165,7 @@ def lal_eccentric_binary_black_hole_no_spins(
spin_2x = 0.0
spin_2y = 0.0
spin_2z = 0.0
iota = theta_jn
longitude_ascending_nodes = 0.0
mean_per_ano = 0.0
......@@ -246,7 +251,7 @@ def supernova_pca_model(
def lal_binary_neutron_star(
frequency_array, mass_1, mass_2, luminosity_distance, chi_1, chi_2,
iota, phase, lambda_1, lambda_2, **kwargs):
theta_jn, phase, lambda_1, lambda_2, **kwargs):
""" A Binary Neutron Star waveform model using lalsimulation
Parameters
......@@ -263,7 +268,7 @@ def lal_binary_neutron_star(
Dimensionless aligned spin
chi_2: float
Dimensionless aligned spin
iota: float
theta_jn: float
Orbital inclination
phase: float
The phase at coalescence
......@@ -308,6 +313,7 @@ def lal_binary_neutron_star(
spin_2x = 0
spin_2y = 0
spin_2z = chi_2
iota = theta_jn
longitude_ascending_nodes = 0.0
eccentricity = 0.0
......@@ -339,7 +345,7 @@ def lal_binary_neutron_star(
def roq(frequency_array, mass_1, mass_2, luminosity_distance, a_1, tilt_1,
phi_12, a_2, tilt_2, phi_jl, iota, phase, **waveform_arguments):
phi_12, a_2, tilt_2, phi_jl, theta_jn, phase, **waveform_arguments):
"""
See https://git.ligo.org/lscsoft/lalsuite/blob/master/lalsimulation/src/LALSimInspiral.c#L1460
......@@ -365,7 +371,7 @@ def roq(frequency_array, mass_1, mass_2, luminosity_distance, a_1, tilt_1,
Secondary tilt angle
phi_jl: float
iota: float
theta_jn: float
Orbital inclination
phase: float
The phase at coalescence
......@@ -410,11 +416,12 @@ def roq(frequency_array, mass_1, mass_2, luminosity_distance, a_1, tilt_1,
spin_2x = 0
spin_2y = 0
spin_2z = a_2
iota = theta_jn
else:
iota, spin_1x, spin_1y, spin_1z, spin_2x, spin_2y, spin_2z = \
lalsim_SimInspiralTransformPrecessingNewInitialConditions(
iota, phi_jl, tilt_1, tilt_2, phi_12, a_1, a_2, mass_1, mass_2,
reference_frequency, phase)
theta_jn, phi_jl, tilt_1, tilt_2, phi_12, a_1, a_2, mass_1,
mass_2, reference_frequency, phase)
chi_1_l, chi_2_l, chi_p, theta_jn, alpha, phase_aligned, zeta =\
lalsim_SimIMRPhenomPCalculateModelParametersFromSourceFrame(
......
......@@ -130,6 +130,7 @@ def get_polarization_tensor(ra, dec, time, psi, mode):
elif mode.lower() == 'breathing':
return np.einsum('i,j->ij', m, m) + np.einsum('i,j->ij', n, n)
# Calculating omega here to avoid calculation when model in [plus, cross, breathing]
omega = np.cross(m, n)
if mode.lower() == 'longitudinal':
return np.sqrt(2) * np.einsum('i,j->ij', omega, omega)
......@@ -138,8 +139,7 @@ def get_polarization_tensor(ra, dec, time, psi, mode):
elif mode.lower() == 'y':
return np.einsum('i,j->ij', n, omega) + np.einsum('i,j->ij', omega, n)
else:
logger.warning("{} not a polarization mode!".format(mode))
return None
raise ValueError("{} not a polarization mode!".format(mode))
def get_vertex_position_geocentric(latitude, longitude, elevation):
......@@ -380,7 +380,7 @@ def get_open_strain_data(
return strain
def read_frame_file(file_name, start_time, end_time, channel=None, buffer_time=1, **kwargs):
def read_frame_file(file_name, start_time, end_time, channel=None, buffer_time=0, **kwargs):
""" A function which accesses the open strain data
This uses `gwpy` to download the open data and then saves a cached copy for
......@@ -416,23 +416,22 @@ def read_frame_file(file_name, start_time, end_time, channel=None, buffer_time=1
except RuntimeError:
logger.warning('Channel {} not found. Trying preset channel names'.format(channel))
while not loaded:
ligo_channel_types = ['GDS-CALIB_STRAIN', 'DCS-CALIB_STRAIN_C01', 'DCS-CALIB_STRAIN_C02',
'DCH-CLEAN_STRAIN_C02']
virgo_channel_types = ['Hrec_hoft_V1O2Repro2A_16384Hz', 'FAKE_h_16384Hz_4R']
channel_types = dict(H1=ligo_channel_types, L1=ligo_channel_types, V1=virgo_channel_types)
for detector in channel_types.keys():
for channel_type in channel_types[detector]:
if loaded:
break
channel = '{}:{}'.format(detector, channel_type)
try:
strain = TimeSeries.read(source=file_name, channel=channel, start=start_time, end=end_time,
**kwargs)
loaded = True
logger.info('Successfully read strain data for channel {}.'.format(channel))
except RuntimeError:
pass
ligo_channel_types = ['GDS-CALIB_STRAIN', 'DCS-CALIB_STRAIN_C01', 'DCS-CALIB_STRAIN_C02',
'DCH-CLEAN_STRAIN_C02']
virgo_channel_types = ['Hrec_hoft_V1O2Repro2A_16384Hz', 'FAKE_h_16384Hz_4R']
channel_types = dict(H1=ligo_channel_types, L1=ligo_channel_types, V1=virgo_channel_types)
for detector in channel_types.keys():
for channel_type in channel_types[detector]:
if loaded:
break
channel = '{}:{}'.format(detector, channel_type)
try:
strain = TimeSeries.read(source=file_name, channel=channel, start=start_time, end=end_time,
**kwargs)
loaded = True
logger.info('Successfully read strain data for channel {}.'.format(channel))
except RuntimeError:
pass
if loaded:
return strain
......
......@@ -59,7 +59,7 @@ interferometers.append(AusIFO)
# signal at 4 Gpc
injection_parameters = dict(
mass_1=36., mass_2=29., a_1=0.4, a_2=0.3, tilt_1=0.5, tilt_2=1.0,
phi_12=1.7, phi_jl=0.3, luminosity_distance=4000., iota=0.4, psi=2.659,
phi_12=1.7, phi_jl=0.3, luminosity_distance=4000., theta_jn=0.4, psi=2.659,
phase=1.3, geocent_time=1126259642.413, ra=1.375, dec=0.2108)
......
......@@ -28,7 +28,7 @@ np.random.seed(88170235)
# aligned spins of both black holes (chi_1, chi_2), etc.
injection_parameters = dict(
mass_1=1.5, mass_2=1.3, chi_1=0.02, chi_2=0.02, luminosity_distance=50.,
iota=0.4, psi=2.659, phase=1.3, geocent_time=1126259642.413,
theta_jn=0.4, psi=2.659, phase=1.3, geocent_time=1126259642.413,
ra=1.375, dec=-1.2108, lambda_1=400, lambda_2=450)
# Set the duration and sampling frequency of the data segment that we're going
......@@ -66,7 +66,7 @@ interferometers.inject_signal(parameters=injection_parameters,
# delta_lambda rather than mass_1, mass_2, lambda_1, and lambda_2.
priors = bilby.gw.prior.BNSPriorDict()
for key in ['psi', 'geocent_time', 'ra', 'dec', 'chi_1', 'chi_2',
'iota', 'luminosity_distance', 'phase']:
'theta_jn', 'luminosity_distance', 'phase']:
priors[key] = injection_parameters[key]
priors.pop('mass_1')
priors.pop('mass_2')
......
......@@ -28,7 +28,7 @@ np.random.seed(88170235)
# spins of both black holes (a, tilt, phi), etc.
injection_parameters = dict(
mass_1=36., mass_2=29., a_1=0.4, a_2=0.3, tilt_1=0.5, tilt_2=1.0,
phi_12=1.7, phi_jl=0.3, luminosity_distance=2000., iota=0.4, psi=2.659,
phi_12=1.7, phi_jl=0.3, luminosity_distance=2000., theta_jn=0.4, psi=2.659,
phase=1.3, geocent_time=1126259642.413, ra=1.375, dec=-1.2108)
# Fixed arguments passed into the source model
......
......@@ -22,7 +22,7 @@ np.random.seed(151226)
injection_parameters = dict(
total_mass=66., mass_ratio=0.9, a_1=0.4, a_2=0.3, tilt_1=0.5, tilt_2=1.0,
phi_12=1.7, phi_jl=0.3, luminosity_distance=2000, iota=0.4, psi=2.659,
phi_12=1.7, phi_jl=0.3, luminosity_distance=2000, theta_jn=0.4, psi=2.659,
phase=1.3, geocent_time=1126259642.413, ra=1.375, dec=-1.2108)
waveform_arguments = dict(waveform_approximant='IMRPhenomPv2',
......@@ -63,8 +63,8 @@ priors['redshift'] = bilby.prior.Uniform(
for key in ['a_1', 'a_2', 'tilt_1', 'tilt_2', 'phi_12', 'phi_jl', 'psi',
'ra', 'dec', 'geocent_time', 'phase']:
priors[key] = injection_parameters[key]
priors.pop('iota')
priors['cos_iota'] = np.cos(injection_parameters['iota'])
priors.pop('theta_jn')
priors['cos_theta_jn'] = np.cos(injection_parameters['theta_jn'])
print(priors)
# Initialise GravitationalWaveTransient
......
......@@ -27,7 +27,7 @@ np.random.seed(150914)
injection_parameters = dict(
mass_1=35., mass_2=30., eccentricity=0.1, luminosity_distance=440.,
iota=0.4, psi=0.1, phase=1.2, geocent_time=1180002601.0, ra=45, dec=5.73)
theta_jn=0.4, psi=0.1, phase=1.2, geocent_time=1180002601.0, ra=45, dec=5.73)
waveform_arguments = dict(waveform_approximant='EccentricFD',
reference_frequency=10., minimum_frequency=10.)
......@@ -70,7 +70,7 @@ priors["luminosity_distance"] = bilby.gw.prior.UniformComovingVolume(
priors["dec"] = bilby.core.prior.Cosine(name='dec')
priors["ra"] = bilby.core.prior.Uniform(
name='ra', minimum=0, maximum=2 * np.pi)
priors["iota"] = bilby.core.prior.Sine(name='iota')
priors["theta_jn"] = bilby.core.prior.Sine(name='theta_jn')
priors["psi"] = bilby.core.prior.Uniform(name='psi', minimum=0, maximum=np.pi)
priors["phase"] = bilby.core.prior.Uniform(
name='phase', minimum=0, maximum=2 * np.pi)
......
......@@ -31,7 +31,7 @@ np.random.seed(88170235)
# spins of both black holes (a, tilt, phi), etc.
injection_parameters = dict(
mass_1=36., mass_2=29., a_1=0.4, a_2=0.3, tilt_1=0.5, tilt_2=1.0,
phi_12=1.7, phi_jl=0.3, luminosity_distance=2000., iota=0.4, psi=2.659,
phi_12=1.7, phi_jl=0.3, luminosity_distance=2000., theta_jn=0.4, psi=2.659,
phase=1.3, geocent_time=1126259642.413, ra=1.375, dec=-1.2108)
# Fixed arguments passed into the source model
......@@ -61,7 +61,7 @@ ifos.inject_signal(waveform_generator=waveform_generator,
# prior is a delta function at the true, injected value. In reality, the
# sampler implementation is smart enough to not sample any parameter that has
# a delta-function prior.
# The above list does *not* include mass_1, mass_2, iota and luminosity
# The above list does *not* include mass_1, mass_2, theta_jn and luminosity
# distance, which means those are the parameters that will be included in the
# sampler. If we do nothing, then the default priors get used.
priors = bilby.gw.prior.BBHPriorDict()
......
......@@ -17,7 +17,7 @@ np.random.seed(151012)
injection_parameters = dict(
mass_1=36., mass_2=29., a_1=0.4, a_2=0.3, tilt_1=0.5, tilt_2=1.0,
phi_12=1.7, phi_jl=0.3, luminosity_distance=4000., iota=0.4, psi=2.659,
phi_12=1.7, phi_jl=0.3, luminosity_distance=4000., theta_jn=0.4, psi=2.659,
phase=1.3, geocent_time=1126259642.413, ra=1.375, dec=-1.2108)
waveform_arguments = dict(waveform_approximant='IMRPhenomPv2',
......@@ -41,7 +41,7 @@ ifos.inject_signal(waveform_generator=waveform_generator,
# This loads in a predefined set of priors for BBHs.
priors = bilby.gw.prior.BBHPriorDict()
# These parameters will not be sampled
for key in ['tilt_1', 'tilt_2', 'phi_12', 'phi_jl', 'phase', 'iota', 'ra',
for key in ['tilt_1', 'tilt_2', 'phi_12', 'phi_jl', 'phase', 'theta_jn', 'ra',
'dec', 'geocent_time', 'psi']:
priors[key] = injection_parameters[key]
# We can make uniform distributions.
......