ler.rates
Submodules
Package Contents
Classes
Sample lens galaxy parameters conditioned on strong lensing. |
|
Class to sample lensed and unlensed GW events and calculate their detection rates. |
|
Class for sampling compact binary coalescence source parameters. |
|
Class to sample GW events and calculate their detection rates. |
Functions
|
Load a json file. |
|
Append (values with corresponding keys) and update a json file with a dictionary. There are four options: |
|
Function to get the parameters from json file. |
|
Function to run the sampling in batches. |
|
Remove a file. |
|
Load a json file. |
|
Append (values with corresponding keys) and update a json file with a dictionary. There are four options: |
|
Function to get the parameters from json file. |
|
Function to run the sampling in batches. |
|
Remove a file. |
- class ler.rates.LensGalaxyParameterDistribution(npool=4, z_min=0.0, z_max=10.0, cosmology=None, event_type='BBH', lens_type='epl_shear_galaxy', lens_functions=None, lens_functions_params=None, lens_param_samplers=None, lens_param_samplers_params=None, directory='./interpolator_json', create_new_interpolator=False, buffer_size=1000, **kwargs)[source]
Bases:
ler.gw_source_population.CBCSourceParameterDistribution,ler.image_properties.ImageProperties,ler.lens_galaxy_population.optical_depth.OpticalDepthSample lens galaxy parameters conditioned on strong lensing.
This class handles the distribution of lens galaxy parameters such as velocity dispersion, axis ratio, axis rotation angle, shear, and density profile slope. It samples source parameters conditioned on the source being strongly lensed using cross-section based rejection or importance sampling.
Key Features:
Samples lens parameters using EPL+shear galaxy model
Supports rejection and importance sampling based on cross-section
Computes optical depth weighted source redshift distributions
Integrates with GW source population and image property calculations
- Parameters:
- npool
int Number of processors to use for parallel sampling.
default: 4
- z_min
float Minimum redshift for source and lens populations.
default: 0.0
- z_max
float Maximum redshift for source and lens populations.
default: 10.0
- cosmology
astropy.cosmologyorNone Cosmology object for distance calculations.
default: None (uses FlatLambdaCDM with H0=70, Om0=0.3)
- event_type
str Type of compact binary coalescence event.
Options:
‘BBH’: Binary black hole
‘BNS’: Binary neutron star
‘NSBH’: Neutron star-black hole
default: ‘BBH’
- lens_type
str Type of lens galaxy model to use.
default: ‘epl_shear_galaxy’
- lens_functions
dictorNone Dictionary specifying lens-related functions.
default: None (uses defaults from OpticalDepth)
- lens_functions_params
dictorNone Parameters for lens functions.
default: None
- lens_param_samplers
dictorNone Dictionary specifying lens parameter sampling functions.
default: None (uses defaults from OpticalDepth)
- lens_param_samplers_params
dictorNone Parameters for lens parameter samplers.
default: None
- directory
str Directory for storing interpolator files.
default: ‘./interpolator_json’
- create_new_interpolator
bool If True, recreates interpolators even if files exist.
default: False
- buffer_size
int Buffer size for batch sampling of lens parameters.
default: 1000
- **kwargs
dict Additional keyword arguments passed to parent classes:
- npool
Examples
Basic usage:
>>> from ler.lens_galaxy_population import LensGalaxyParameterDistribution >>> lens = LensGalaxyParameterDistribution() >>> lensed_params = lens.sample_lens_parameters(size=1000) >>> print(lensed_params.keys())
Instance Methods
LensGalaxyParameterDistribution has the following methods:
Instance Attributes
LensGalaxyParameterDistribution has the following attributes:
Attribute
Type
Unit
Description
npoolintNumber of processors for parallel computation
z_minfloatMinimum redshift
z_maxfloatMaximum redshift
cosmoastropy.cosmologyCosmology object for calculations
strType of CBC event (BBH, BNS, NSBH)
directorystrPath to interpolator storage directory
dictDictionary of lens parameter sampler names
dictParameters for lens parameter samplers
dictDictionary of lens function names
floatNormalization constant for lensed source z pdf
- property source_redshift_sl
Function to sample source redshifts conditioned on strong lensing.
- Returns:
- source_redshift_sl
ler.functions.FunctionConditioning Function for sampling source redshifts conditioned on strong lensing.
- source_redshift_sl
- property normalization_pdf_z_lensed
Normalization constant for the lensed source redshift pdf.
This constant is used to normalize the probability distribution
of source redshifts conditioned on strong lensing. It is computed
by integrating the merger rate density times optical depth.
- Returns:
- normalization_pdf_z_lensed
float Normalization constant for lensed redshift distribution.
- normalization_pdf_z_lensed
- property lens_param_samplers
Dictionary of lens parameter sampler function names.
- Returns:
- lens_param_samplers
dict Dictionary mapping parameter names to sampler function names.
Keys include: ‘source_redshift_sl’, ‘lens_redshift’,
‘velocity_dispersion’, ‘axis_ratio’, ‘axis_rotation_angle’,
‘external_shear’, ‘density_profile_slope’.
- lens_param_samplers
- property lens_param_samplers_params
Dictionary of parameters for lens parameter samplers.
- Returns:
- lens_param_samplers_params
dict Dictionary with sampler parameters.
Each key corresponds to a sampler in lens_param_samplers.
- lens_param_samplers_params
- property lens_functions
Dictionary of lens-related function names.
- Returns:
- lens_functions
dict Dictionary mapping function types to function names.
Keys include: ‘param_sampler_type’, ‘cross_section_based_sampler’,
‘optical_depth’, ‘cross_section’.
- lens_functions
- event_type = "'BBH'"
strType of event to generate.
e.g. ‘BBH’, ‘BNS’, ‘NSBH’
- sample_lens_parameters_routine
- cross_section_based_sampler
- sample_lens_parameters(size=1000)[source]
Sample lens galaxy and source parameters conditioned on strong lensing.
This method samples both lens galaxy parameters (velocity dispersion, axis ratio, shear, etc.) and gravitational wave source parameters, with the source redshift distribution weighted by strong lensing optical depth.
- Parameters:
- size
int Number of lens-source parameter sets to sample.
default: 1000
- size
- Returns:
- lens_parameters
dict Dictionary containing sampled lens and source parameters.
The included parameters and their units are as follows (for default settings):
- lens_parameters
Examples
>>> from ler.lens_galaxy_population import LensGalaxyParameterDistribution >>> lens = LensGalaxyParameterDistribution() >>> params = lens.sample_lens_parameters(size=1000) >>> print(params.keys())
- sample_all_routine_epl_shear_sl(size=1000)[source]
Sample EPL+shear galaxy lens parameters with strong lensing condition.
- Parameters:
- size
int Number of lens parameters to sample.
default: 1000
- size
- Returns:
- lens_parameters
dict Dictionary of sampled lens parameters.
The included parameters and their units are as follows (for default settings):
Parameter
Units
Description
zl
redshift of the lens
zs
redshift of the source
sigma
km s^-1
velocity dispersion
q
axis ratio
theta_E
radian
Einstein radius
phi
rad
axis rotation angle. counter-clockwise from the positive x-axis (RA-like axis) to the major axis of the projected mass distribution.
gamma
density profile slope of EPL galaxy
gamma1
external shear component in the x-direction (RA-like axis)
gamma2
external shear component in the y-direction (Dec-like axis)
- lens_parameters
- strongly_lensed_source_redshift(size, get_attribute=False, **kwargs)[source]
Sample source redshifts conditioned on strong lensing.
- Parameters:
- size
int Number of samples to generate.
default: 1000
- get_attribute
bool If True, returns the sampler object instead of samples.
default: False
- **kwargs
dict Additional parameters
- size
- Returns:
- redshifts
numpy.ndarray Array of source redshifts conditioned on strong lensing.
- redshifts
Examples
>>> from ler.lens_galaxy_population import LensGalaxyParameterDistribution >>> lens = LensGalaxyParameterDistribution() >>> zs = lens.strongly_lensed_source_redshift(size=1000) >>> print(f"strongly lensed source redshift: {zs.mean():.2f}")
- sample_all_routine_epl_shear_intrinsic(size=1000)[source]
Sample EPL+shear galaxy lens parameters from intrinsic distributions.
Samples lens parameters from their intrinsic distributions without applying strong lensing cross-section weighting.
- Parameters:
- size
int Number of lens parameters to sample.
default: 1000
- size
- Returns:
- lens_parameters
dict Dictionary of sampled lens parameters.
The included parameters and their units are as follows (for default settings):
Parameter
Units
Description
zl
redshift of the lens
zs
redshift of the source
sigma
km s^-1
velocity dispersion
q
axis ratio
theta_E
radian
Einstein radius
phi
rad
axis rotation angle. counter-clockwise from the positive x-axis (RA-like axis) to the major axis of the projected mass distribution.
gamma
density profile slope of EPL galaxy
gamma1
external shear component in the x-direction (RA-like axis)
gamma2
external shear component in the y-direction (Dec-like axis)
- lens_parameters
- ler.rates.load_json(file_name)[source]
Load a json file.
- Parameters:
- file_namestr
json file name for storing the parameters.
- Returns:
- paramdict
- ler.rates.append_json(file_name, new_dictionary, old_dictionary=None, replace=False)[source]
Append (values with corresponding keys) and update a json file with a dictionary. There are four options:
If old_dictionary is provided, the values of the new dictionary will be appended to the old dictionary and save in the ‘file_name’ json file.
If replace is True, replace the json file (with the ‘file_name’) content with the new_dictionary.
If the file does not exist, create a new one with the new_dictionary.
If none of the above, append the new dictionary to the content of the json file.
- Parameters:
- file_namestr
json file name for storing the parameters.
- new_dictionarydict
dictionary to be appended to the json file.
- old_dictionarydict, optional
If provided the values of the new dictionary will be appended to the old dictionary and save in the ‘file_name’ json file. Default is None.
- replacebool, optional
If True, replace the json file with the dictionary. Default is False.
- ler.rates.get_param_from_json(json_file)[source]
Function to get the parameters from json file.
- Parameters:
- json_filestr
json file name for storing the parameters.
- Returns:
- paramdict
- ler.rates.batch_handler(size, batch_size, sampling_routine, output_jsonfile, save_batch=True, resume=False, param_name='parameters')[source]
Function to run the sampling in batches.
- Parameters:
- sizeint
number of samples.
- batch_sizeint
batch size.
- sampling_routinefunction
sampling function. It should have ‘size’ as input and return a dictionary.
- output_jsonfilestr
json file name for storing the parameters.
- save_batchbool, optional
if True, save sampled parameters in each iteration. Default is True.
- resumebool, optional
if True, resume sampling from the last batch. Default is False.
- param_namestr, optional
name of the parameter. Default is ‘parameters’.
- Returns:
- dict_bufferdict
dictionary of parameters.
- class ler.rates.LeR(npool=int(4), z_min=0.0, z_max=10.0, event_type='BBH', lens_type='epl_shear_galaxy', cosmology=None, pdet_finder=None, json_file_names=None, interpolator_directory='./interpolator_json', create_new_interpolator=False, ler_directory='./ler_data', verbose=True, **kwargs)[source]
Bases:
ler.lens_galaxy_population.LensGalaxyParameterDistributionClass to sample lensed and unlensed GW events and calculate their detection rates.
This class provides functionality for sampling gravitational wave source parameters, detection probabilities, and computing detection rates for both lensed and unlensed compact binary coalescence events. Parameters of simulated events are stored in JSON files (not as class attributes) to conserve RAM memory.
Key Features:
Sampling of unlensed and lensed CBC event parameters
Detection probability calculation using
gwsnrpackage or custom functionsRate calculation for detectable events
Batch processing for memory efficiency
JSON-based parameter storage for reproducibility
- Parameters:
- npool
int Number of cores to use for parallel processing.
default: 4
- z_min
float Minimum redshift of the source population.
default: 0.0
- z_max
float Maximum redshift of the source population.
default: 10.0
- event_type
str Type of event to generate. source_priors and source_priors_params will be set accordingly.
Options:
‘BBH’: Binary Black Hole
‘BNS’: Binary Neutron Star
‘NSBH’: Neutron Star-Black Hole
default: ‘BBH’
- lens_type
str Type of lens model to use. lens_functions, lens_functions_params, lens_param_samplers and lens_param_samplers_params will be set accordingly.
Options:
‘epl_shear_galaxy’: Exponential Power Law Shear Galaxy
‘sie_galaxy’: Singular Isothermal Ellipsoid Galaxy
‘sis_galaxy’: Singular Isothermal Sphere Galaxy
default: ‘epl_shear_galaxy’
- cosmology
astropy.cosmology Cosmology to use for the calculation.
default: LambdaCDM(H0=70, Om0=0.3, Ode0=0.7, Tcmb0=0.0, Neff=3.04, m_nu=None, Ob0=0.0)
- pdet_finder
functionorNone Custom detection probability finder function.
If None, uses gwsnr’s pdet calculator.
The function should follow the signature:
def pdet_finder(gw_param_dict): return pdet_net_dictwhere pdet_net_dict.keys = [‘pdet_net’].
default: None
- json_file_names
dict Names of the JSON files to store the necessary parameters.
- default: dict(
ler_params=”ler_params.json”, unlensed_param=”unlensed_param.json”, unlensed_param_detectable=”unlensed_param_detectable.json”, lensed_param=”lensed_param.json”, lensed_param_detectable=”lensed_param_detectable.json”
)
- interpolator_directory
str Directory to store the interpolators.
default: ‘./interpolator_json’
- create_new_interpolator
boolordict Whether to create new interpolators. Look at
create_new_interpolator()for details.Options:
True: Create all interpolators anew
False: Load existing interpolators if available
dict: Specify which interpolators to create new
default: False
- ler_directory
str Directory to store the output parameters.
default: ‘./ler_data’
- verbose
bool If True, print all chosen parameters during initialization.
default: True
- **kwargs
dict Additional keyword arguments passed to parent classes:
LensGalaxyParameterDistribution,CBCSourceParameterDistribution,ImageProperties, andGWSNR(if snr_finder=’gwsnr’).
- npool
Notes
LeRclass inherits fromLensGalaxyParameterDistribution.Refer to that class for additional inherited attributes and methods.
Parameters are stored in JSON files for memory efficiency and reproducibility.
For stable rate estimates, use size >= 1e6 samples.
Examples
Basic usage:
>>> from ler import LeR >>> ler = LeR() >>> unlensed_params = ler.unlensed_cbc_statistics() >>> ler.unlensed_rate() >>> lensed_params = ler.lensed_cbc_statistics() >>> ler.lensed_rate() >>> ler.rate_ratio()
Instance Methods
LeR class has the following methods:
Method
Description
Generate unlensed GW source parameters
Generate unlensed parameters with batching
Calculate the unlensed detection rate
Generate lensed GW source parameters
Generate lensed parameters with batching
Calculate the lensed detection rate
General helper for rate calculation
Calculate lensed/unlensed rate ratio
Calculate and compare lensed/unlensed rates
Select n unlensed detectable events
Select n lensed detectable events
Instance Attributes
LeR class has the following attributes:
Attribute
Type
Unit
Description
intNumber of parallel processing cores
floatMinimum source redshift
floatMaximum source redshift
strType of CBC event (BBH, BNS, NSBH)
strType of lens galaxy model
CosmologyAstropy cosmology object
dictJSON file names for parameter storage
strDirectory for interpolator files
strDirectory for output parameter files
callableDetection probability finder function
dictAll LeR initialization arguments
dictInterpolator creation settings
- property npool
Number of parallel processing cores.
- Returns:
- npool
int Number of logical cores to use for multiprocessing.
default: 4
- npool
- property z_min
Minimum redshift of the source population.
- Returns:
- z_min
float Minimum source redshift for sampling.
default: 0.0
- z_min
- property z_max
Maximum redshift of the source population.
- Returns:
- z_max
float Maximum source redshift for sampling.
default: 10.0
- z_max
- property event_type
Type of compact binary coalescence event.
- Returns:
- event_type
str Type of CBC event.
Options:
‘BBH’: Binary Black Hole
‘BNS’: Binary Neutron Star
‘NSBH’: Neutron Star-Black Hole
default: ‘BBH’
- event_type
- property lens_type
Type of lens galaxy model.
- Returns:
- lens_type
str Type of lens model.
Options:
‘epl_shear_galaxy’: Elliptical Power Law with external shear
‘sie_galaxy’: Singular Isothermal Ellipsoid
‘sis_galaxy’: Singular Isothermal Sphere
default: ‘epl_shear_galaxy’
- lens_type
- property cosmo
Astropy cosmology object for distance calculations.
- Returns:
- cosmo
astropy.cosmology Cosmology used for luminosity distance and comoving volume calculations.
default: LambdaCDM(H0=70, Om0=0.3, Ode0=0.7, Tcmb0=0.0, Neff=3.04, m_nu=None, Ob0=0.0)
- cosmo
- property json_file_names
Dictionary of JSON file names for parameter storage.
- Returns:
- json_file_names
dict Dictionary with keys:
‘ler_params’: LeR initialization parameters
‘unlensed_param’: Unlensed event parameters
‘unlensed_param_detectable’: Detectable unlensed events
‘lensed_param’: Lensed event parameters
‘lensed_param_detectable’: Detectable lensed events
- json_file_names
- property interpolator_directory
Directory path for interpolator JSON files.
- Returns:
- interpolator_directory
str Path to directory containing interpolator data files.
default: ‘./interpolator_json’
- interpolator_directory
- property ler_directory
Directory path for LeR output files.
- Returns:
- ler_directory
str Path to directory for storing output parameter files.
default: ‘./ler_data’
- ler_directory
- property create_new_interpolator
Configuration dictionary for interpolator creation settings.
- Returns:
- create_new_interpolator
dict Dictionary specifying which interpolators to create.
Each key is an interpolator name, and values are dicts with:
‘create_new’: bool - Whether to create new interpolator
‘resolution’: int or list - Grid resolution for interpolation
Special key ‘gwsnr’ is a bool for GWSNR interpolator creation. Default: dict(
merger_rate_density = {‘create_new’: False, ‘resolution’: 500}, redshift_distribution = {‘create_new’: False, ‘resolution’: 500}, luminosity_distance = {‘create_new’: False, ‘resolution’: 500}, differential_comoving_volume = {‘create_new’: False, ‘resolution’: 500}, source_frame_masses = {‘create_new’: False, ‘resolution’: 500}, geocent_time = {‘create_new’: False, ‘resolution’: 500}, ra = {‘create_new’: False, ‘resolution’: 500}, dec = {‘create_new’: False, ‘resolution’: 500}, phase = {‘create_new’: False, ‘resolution’: 500}, psi = {‘create_new’: False, ‘resolution’: 500}, theta_jn = {‘create_new’: False, ‘resolution’: 500}, a_1 = {‘create_new’: False, ‘resolution’: 500}, a_2 = {‘create_new’: False, ‘resolution’: 500}, tilt_1 = {‘create_new’: False, ‘resolution’: 500}, tilt_2 = {‘create_new’: False, ‘resolution’: 500}, phi_12 = {‘create_new’: False, ‘resolution’: 500}, phi_jl = {‘create_new’: False, ‘resolution’: 500}, velocity_dispersion = {‘create_new’: False, ‘resolution’: 500, ‘zl_resolution’: 48}, axis_ratio = {‘create_new’: False, ‘resolution’: 500, ‘sigma_resolution’: 48}, lens_redshift = {‘create_new’: False, ‘resolution’: 48, ‘zl_resolution’: 48}, lens_redshift_intrinsic = {‘create_new’: False, ‘resolution’: 500}, optical_depth = {‘create_new’: False, ‘resolution’: 48}, comoving_distance = {‘create_new’: False, ‘resolution’: 500}, angular_diameter_distance = {‘create_new’: False, ‘resolution’: 500}, angular_diameter_distance_z1z2 = {‘create_new’: False, ‘resolution’: 500}, density_profile_slope = {‘create_new’: False, ‘resolution’: 100}, lens_parameters_kde_sl = {‘create_new’: False, ‘resolution’: 5000}, cross_section = {‘create_new’: False, ‘resolution’: [25, 25, 45, 15, 15]}, gwsnr = False,
)
- create_new_interpolator
- property pdet_finder
Detection probability finder function.
- Returns:
- pdet_finder
callable Function that calculates detection probability for GW events.
The function signature should be:
pdet_finder(gw_param_dict) -> dictwith key ‘pdet_net’.
- pdet_finder
- property ler_args
Dictionary of all LeR initialization arguments.
- Returns:
- ler_args
dict Dictionary containing all parameters used to initialize LeR and
its parent classes, useful for reproducibility.
- ler_args
- unlensed_cbc_statistics(size=100000, batch_size=50000, resume=True, save_batch=False, output_jsonfile=None)[source]
Generate unlensed GW source parameters.
This function calls the unlensed_sampling_routine function to generate the parameters in batches. The generated parameters are stored in a JSON file; and if save_batch=True, it keeps updating the file in batches.
- Parameters:
- size
int Number of samples to generate.
default: 100000
- batch_size
int Batch size for sampling.
default: 50000
- resume
bool If True, the function will resume from the last batch.
default: True
- save_batch
bool If True, saves parameters in batches during sampling.
If False, saves all parameters at the end (faster).
default: False
- output_jsonfile
str JSON file name for storing the parameters.
default: None (uses self.json_file_names[“unlensed_param”])
- size
- Returns:
- unlensed_param
dict Dictionary of unlensed GW source parameters. The included parameters and their units are as follows (for default settings):
Parameter
Units
Description
zs
redshift of the source
geocent_time
s
GPS time of coalescence
ra
rad
right ascension
dec
rad
declination
phase
rad
phase of GW at reference frequency
psi
rad
polarization angle
theta_jn
rad
inclination angle
a_1
spin_1 of the compact binary
a_2
spin_2 of the compact binary
luminosity_distance
Mpc
luminosity distance
mass_1_source
Msun
mass_1 of the compact binary (source frame)
mass_2_source
Msun
mass_2 of the compact binary (source frame)
mass_1
Msun
mass_1 of the compact binary (detector frame)
mass_2
Msun
mass_2 of the compact binary (detector frame)
pdet_L1
pdet of L1
pdet_H1
pdet of H1
pdet_V1
pdet of V1
pdet_net
pdet of the network
- unlensed_param
Examples
>>> from ler import LeR >>> ler = LeR() >>> unlensed_param = ler.unlensed_cbc_statistics()
- unlensed_sampling_routine(size, output_jsonfile, resume=True, save_batch=True)[source]
Generate unlensed GW source parameters for a single batch.
This is the core sampling routine called by unlensed_cbc_statistics. It samples GW source parameters and calculates detection probabilities.
- Parameters:
- size
int Number of samples to generate.
- output_jsonfile
str JSON file name for storing the parameters.
- resume
bool If True, appends new samples to existing JSON file.
default: True
- save_batch
bool If True, saves parameters in batches during sampling.
default: True
- size
- Returns:
- unlensed_param
dict Dictionary of unlensed GW source parameters.
- unlensed_param
- unlensed_rate(unlensed_param=None, pdet_threshold=0.5, pdet_type='boolean', output_jsonfile=None)[source]
Function to calculate the unlensed rate.
This function calculates the detection rate for unlensed events and stores the parameters of the detectable events in a JSON file.
- Parameters:
- unlensed_param
dictorstr Dictionary of GW source parameters or JSON file name.
default: None (uses self.json_file_names[“unlensed_param”])
- pdet_threshold
float Threshold for detection probability.
default: 0.5
- pdet_type
str Detectability condition type.
Options:
‘boolean’: Binary detection based on pdet_threshold
‘probability_distribution’: Uses pdet values directly
default: ‘boolean’
- output_jsonfile
str JSON file name for storing the parameters of the detectable events.
default: None (uses self.json_file_names[“unlensed_param_detectable”])
- unlensed_param
- Returns:
- total_rate
float Total unlensed rate (yr^-1).
- unlensed_param
dict Dictionary of unlensed GW source parameters of the detectable events.
- total_rate
Examples
>>> from ler import LeR >>> ler = LeR() >>> ler.unlensed_cbc_statistics() >>> total_rate, unlensed_param_detectable = ler.unlensed_rate()
- rate_function(detectable_size, total_size, param_type='unlensed', verbose=True)[source]
Calculate the detection rate for unlensed or lensed events.
This is a general helper function that computes the rate based on Monte Carlo integration using the ratio of detectable to total events.
- Parameters:
- detectable_size
intorfloat Number of detectable events (or sum of pdet values).
- total_size
int Total number of simulated events.
- param_type
str Type of parameters.
Options:
‘unlensed’: Use unlensed normalization
‘lensed’: Use lensed normalization
default: ‘unlensed’
- verbose
bool If True, print rate information.
default: True
- detectable_size
- Returns:
- rate
float Event rate (yr^-1).
- rate
Examples
>>> from ler import LeR >>> ler = LeR() >>> rate = ler.rate_function(detectable_size=100, total_size=1000)
- lensed_cbc_statistics(size=100000, batch_size=50000, save_batch=False, resume=True, output_jsonfile=None)[source]
Generate lensed GW source parameters.
This function calls the lensed_sampling_routine function to generate the parameters in batches. The generated parameters are stored in a JSON file; and if save_batch=True, it keeps updating the file in batches.
- Parameters:
- size
int Number of samples to generate.
default: 100000
- batch_size
int Batch size for sampling.
default: 50000
- save_batch
bool If True, saves parameters in batches during sampling.
If False, saves all parameters at the end (faster).
default: True
- resume
bool If True, the function will resume from the last batch.
default: True
- output_jsonfile
str JSON file name for storing the parameters.
default: None (uses self.json_file_names[“lensed_param”])
- size
- Returns:
- lensed_param
dict Dictionary of lensed GW source parameters. The included parameters and their units are as follows (for default settings):
- lensed_param
Examples
>>> from ler import LeR >>> ler = LeR() >>> lensed_param = ler.lensed_cbc_statistics()
- lensed_sampling_routine(size, output_jsonfile, save_batch=True, resume=True)[source]
Generate lensed GW source parameters for a single batch.
This is the core sampling routine called by lensed_cbc_statistics. It samples lens parameters, calculates image properties, and computes detection probabilities for the images of lensed events.
- Parameters:
- size
int Number of samples to generate.
- output_jsonfile
str JSON file name for storing the parameters.
- save_batch
bool If True, saves parameters in batches during sampling.
default: True
- resume
bool If True, appends new samples to existing JSON file.
default: True
- size
- Returns:
- lensed_param
dict Dictionary of lensed GW source parameters.
- lensed_param
- lensed_rate(lensed_param=None, pdet_threshold=[0.5, 0.5], num_img=[1, 1], output_jsonfile=None, nan_to_num=True, pdet_type='boolean')[source]
Function to calculate the lensed rate.
This function calculates the detection rate for lensed events and stores the parameters of the detectable events in a JSON file.
- Parameters:
- lensed_param
dictorstr Dictionary of lensed GW source parameters or JSON file name.
default: None (uses self.json_file_names[“lensed_param”])
- pdet_threshold
floatorlist Threshold for detection probability.
default: [0.5, 0.5]
- num_img
intorlist Number of images corresponding to the pdet_threshold.
Together with pdet_threshold = [0.5, 0.5], it means that two images with pdet > 0.5.
Same condition can also be represented by pdet_threshold = 0.5 and num_img = 2.
default: [1, 1]
- output_jsonfile
str JSON file name for storing the parameters of the detectable events.
default: None (uses self.json_file_names[“lensed_param_detectable”])
- nan_to_num
bool If True, NaN values will be converted to 0.
default: True
- pdet_type
str Detectability condition type.
Options:
‘boolean’: Binary detection based on pdet_threshold
‘probability_distribution’: Uses pdet values directly
default: ‘boolean’
- lensed_param
- Returns:
- total_rate
float Total lensed rate (yr^-1).
- lensed_param
dict Dictionary of lensed GW source parameters of the detectable events. The included parameters and their units are as follows (for default settings):
- total_rate
Examples
>>> from ler import LeR >>> ler = LeR() >>> ler.lensed_cbc_statistics() >>> total_rate, lensed_param_detectable = ler.lensed_rate()
- rate_comparison_with_rate_calculation(unlensed_param=None, pdet_threshold_unlensed=0.5, output_jsonfile_unlensed=None, lensed_param=None, pdet_threshold_lensed=[0.5, 0.5], num_img_lensed=[1, 1], output_jsonfile_lensed=None, nan_to_num=True, pdet_type='boolean')[source]
Calculate and compare unlensed and lensed detection rates.
This function calculates both unlensed and lensed rates and computes their ratio. It stores the parameters of the detectable events in JSON files. Using this function eliminates the need to call unlensed_rate and lensed_rate separately.
- Parameters:
- unlensed_param
dictorstr Dictionary of GW source parameters or JSON file name.
default: None (uses self.json_file_names[“unlensed_param”])
- pdet_threshold_unlensed
float Detection probability threshold for unlensed events.
default: 0.5
- output_jsonfile_unlensed
str JSON file name for storing detectable unlensed parameters.
default: None
- lensed_param
dictorstr Dictionary of lensed GW source parameters or JSON file name.
default: None (uses self.json_file_names[“lensed_param”])
- pdet_threshold_lensed
floatorlist Detection probability threshold for lensed events.
default: [0.5, 0.5]
- num_img_lensed
list Number of images for lensed events.
default: [1, 1]
- output_jsonfile_lensed
str JSON file name for storing detectable lensed parameters.
default: None
- nan_to_num
bool If True, NaN values will be converted to 0.
default: True
- pdet_type
str Detectability condition type.
Options:
‘boolean’: Binary detection based on pdet_threshold
‘probability_distribution’: Uses pdet values directly
default: ‘boolean’
- unlensed_param
- Returns:
- rate_ratio
float Ratio of unlensed rate to lensed rate.
- unlensed_param_detectable
dict Dictionary of detectable unlensed GW source parameters.
- lensed_param_detectable
dict Dictionary of detectable lensed GW source parameters.
- rate_ratio
Examples
>>> from ler import LeR >>> ler = LeR() >>> ler.unlensed_cbc_statistics() >>> ler.lensed_cbc_statistics() >>> rate_ratio, unlensed_param, lensed_param = ler.rate_comparison_with_rate_calculation()
- rate_ratio()[source]
Calculate and display the unlensed to lensed merger rate ratio.
This function retrieves the unlensed_rate and lensed_rate from the JSON file specified in self.json_file_names[“ler_params”] and computes their ratio.
- Returns:
- rate_ratio
float Ratio of unlensed rate to lensed rate.
- rate_ratio
Examples
>>> from ler import LeR >>> ler = LeR() >>> ler.unlensed_cbc_statistics() >>> ler.lensed_cbc_statistics() >>> ler.unlensed_rate() >>> ler.lensed_rate() >>> ler.rate_ratio()
- selecting_n_unlensed_detectable_events(size=100, batch_size=50000, stopping_criteria=dict(relative_diff_percentage=0.5, number_of_last_batches_to_check=4), pdet_threshold=0.5, resume=True, output_jsonfile='n_unlensed_param_detectable.json', meta_data_file='meta_unlensed.json', pdet_type='boolean', trim_to_size=False)[source]
Generate a target number of detectable unlensed events by sampling in batches, with the option to stop once the cumulative rate has stabilized.
This function samples unlensed parameters and saves only the detectable events in a JSON file. It also records metadata including the total number of events and the cumulative rate.
- Parameters:
- size
int Target number of detectable samples to collect.
default: 100
- batch_size
int Batch size for sampling.
default: 50000
- stopping_criteria
dictorNone Criteria for stopping sample collection (but will not stop until n>size).
Keys:
‘relative_diff_percentage’: Maximum relative difference in rate (float)
‘number_of_last_batches_to_check’: Number of batches for comparison (int)
If None, stops when detectable events exceed size.
default: dict(relative_diff_percentage=0.5, number_of_last_batches_to_check=4)
- pdet_threshold
float Detection probability threshold.
default: 0.5
- resume
bool If True, resumes from last saved batch.
default: True
- output_jsonfile
str JSON file name for storing detectable parameters.
default: ‘n_unlensed_param_detectable.json’
- meta_data_file
str JSON file name for storing metadata.
default: ‘meta_unlensed.json’
- pdet_type
str Detectability condition type.
Options:
‘boolean’: Binary detection based on pdet_threshold
‘probability_distribution’: Uses pdet values directly
default: ‘boolean’
- trim_to_size
bool If True, trims final result to exactly size events.
default: False
- size
- Returns:
- param_final
dict Dictionary of unlensed GW source parameters of detectable events.
- param_final
Examples
>>> from ler import LeR >>> ler = LeR() >>> unlensed_param = ler.selecting_n_unlensed_detectable_events(size=100)
- selecting_n_lensed_detectable_events(size=100, stopping_criteria=dict(relative_diff_percentage=2, number_of_last_batches_to_check=4), batch_size=50000, pdet_threshold=[0.5, 0.5], num_img=[1, 1], resume=True, pdet_type='boolean', output_jsonfile='n_lensed_params_detectable.json', meta_data_file='meta_lensed.json', trim_to_size=False, nan_to_num=True)[source]
Generate a target number of detectable lensed events by sampling in batches, with the option to stop once the cumulative rate has stabilized.
This function samples lensed parameters and saves only the detectable events in a JSON file. It also records metadata including the total number of events and the cumulative rate.
- Parameters:
- size
int Target number of detectable samples to collect.
default: 100
- stopping_criteria
dictorNone Criteria for stopping sample collection (but will not stop until n>size).
Keys:
‘relative_diff_percentage’: Maximum relative difference in rate (float)
‘number_of_last_batches_to_check’: Number of batches for comparison (int)
If None, stops when detectable events exceed size.
default: dict(relative_diff_percentage=2, number_of_last_batches_to_check=4)
- batch_size
int Batch size for sampling.
default: 50000
- pdet_threshold
floatorlist Detection probability threshold.
default: [0.5, 0.5]
- num_img
list Number of images corresponding to each pdet_threshold.
default: [1, 1]
- resume
bool If True, resumes from last saved batch.
default: True
- pdet_type
str Detectability condition type.
Options:
‘boolean’: Binary detection based on pdet_threshold
‘probability_distribution’: Uses pdet values directly
default: ‘boolean’
- output_jsonfile
str JSON file name for storing detectable parameters.
default: ‘n_lensed_params_detectable.json’
- meta_data_file
str JSON file name for storing metadata.
default: ‘meta_lensed.json’
- trim_to_size
bool If True, trims final result to exactly size events.
default: False
- nan_to_num
bool If True, NaN values will be converted to 0.
default: False
- size
- Returns:
- param_final
dict Dictionary of lensed GW source parameters of detectable events.
- param_final
Examples
>>> from ler import LeR >>> ler = LeR() >>> lensed_param = ler.selecting_n_lensed_detectable_events(size=100)
- class ler.rates.CBCSourceParameterDistribution(z_min=0.0, z_max=10.0, event_type='BBH', source_priors=None, source_priors_params=None, cosmology=None, spin_zero=False, spin_precession=False, directory='./interpolator_json', create_new_interpolator=False)[source]
Bases:
ler.gw_source_population.cbc_source_redshift_distribution.CBCSourceRedshiftDistributionClass for sampling compact binary coalescence source parameters.
This class generates complete sets of intrinsic and extrinsic gravitational wave parameters for compact binary sources including masses, spins, sky positions, and orbital parameters. It supports BBH, BNS, NSBH, and primordial black hole populations with configurable prior distributions.
Key Features:
Multiple mass distribution models (PowerLaw+Gaussian, lognormal, bimodal)
Configurable spin priors (zero, aligned, precessing)
Isotropic sky position and orientation sampling
Built-in support for population III and primordial black holes
- Parameters:
- z_min
float Minimum redshift of the source population.
default: 0.0
- z_max
float Maximum redshift of the source population.
default: 10.0
- event_type
str Type of compact binary event to generate.
Options:
‘BBH’: Binary black hole (Population I/II)
‘BNS’: Binary neutron star
‘NSBH’: Neutron star-black hole
‘BBH_popIII’: Population III binary black hole
‘BBH_primordial’: Primordial binary black hole
default: ‘BBH’
- source_priors
dictorNone Dictionary of prior sampler functions for each parameter.
If None, uses default priors based on event_type.
default: None
- source_priors_params
dictorNone Dictionary of parameters for each prior sampler function.
If None, uses default parameters based on event_type.
default: None
- cosmology
astropy.cosmologyorNone Cosmology to use for distance calculations.
default: LambdaCDM(H0=70, Om0=0.3, Ode0=0.7, Tcmb0=0.0, Neff=3.04, m_nu=None, Ob0=0.0)
- spin_zero
bool If True, spin parameters are set to zero (no spin sampling).
default: False
- spin_precession
bool If True (and spin_zero=False), sample precessing spin parameters.
If False (and spin_zero=False), sample aligned/anti-aligned spins.
default: False
- directory
str Directory to store interpolator JSON files.
default: ‘./interpolator_json’
- create_new_interpolator
dictorbool Configuration for creating new interpolators.
If bool, applies to all interpolators.
default: False
- z_min
Examples
>>> from ler.gw_source_population import CBCSourceParameterDistribution >>> cbc = CBCSourceParameterDistribution(event_type='BBH') >>> params = cbc.sample_gw_parameters(size=1000) >>> print(list(params.keys()))
Instance Methods
CBCSourceParameterDistribution has the following methods:
Instance Attributes
CBCSourceParameterDistribution has the following attributes:
Attribute
Type
Unit
Description
floatMinimum redshift of source population
floatMaximum redshift of source population
astropy.cosmologyCosmology for distance calculations
boolWhether to ignore spin parameters
boolWhether to use precessing spins
strDirectory for interpolator files
gw_param_samplersdictDictionary of parameter sampler functions
gw_param_samplers_paramsdictDictionary of sampler function parameters
dictAvailable prior distributions
callableSampler for source frame masses
callableSampler for source redshift
callableSampler for geocentric time
callableSampler for right ascension
callableSampler for declination
callableSampler for coalescence phase
callableSampler for polarization angle
callableSampler for inclination angle
callableSampler for spin1 magnitude
callableSampler for spin2 magnitude
callableSampler for tilt1 angle
callableSampler for tilt2 angle
callableSampler for phi_12 angle
callableSampler for phi_jl angle
- property zs
Class object (of FunctionConditioning) for source redshift, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the redshift distribution
pdf: returns the probability density function of the redshift distribution
function: returns the redshift distribution function.
- Returns:
- zs
numpy.ndarray Array of redshift values.
- zs
- property source_frame_masses
Class object (of FunctionConditioning) for source frame masses, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the density profile slope distribution
- Returns:
- mass_1_source
numpy.ndarray Array of mass_1_source values in solar masses.
- mass_2_source
numpy.ndarray Array of mass_2_source values in solar masses.
- mass_1_source
Examples
>>> from ler.gw_source_population import CBCSourceParameterDistribution >>> cbc_source_param_dist = CBCSourceParameterDistribution() >>> cbc_source_param_dist.source_frame_masses(size=10)
- property geocent_time
Class object (of FunctionConditioning) for geocentric time, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the geocentric time distribution
pdf: returns the probability density function of the geocentric time distribution
function: returns the geocentric time distribution function.
- Returns:
- geocent_time
numpy.ndarray Array of geocentric time values.
- geocent_time
- property ra
Class object (of FunctionConditioning) for right ascension, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the right ascension distribution
pdf: returns the probability density function of the right ascension distribution
function: returns the right ascension distribution function.
- Returns:
- ra
numpy.ndarray Array of right ascension values.
- ra
- property dec
Class object (of FunctionConditioning) for declination, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the declination distribution
pdf: returns the probability density function of the declination distribution
function: returns the declination distribution function.
- Returns:
- dec
numpy.ndarray Array of declination values.
- dec
- property phase
Class object (of FunctionConditioning) for coalescence phase, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the coalescence phase distribution
pdf: returns the probability density function of the coalescence phase distribution
function: returns the coalescence phase distribution function.
- Returns:
- phase
numpy.ndarray Array of coalescence phase values.
- phase
- property psi
Class object (of FunctionConditioning) for polarization angle, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the polarization angle distribution
pdf: returns the probability density function of the polarization angle distribution
function: returns the polarization angle distribution function.
- Returns:
- geocent_time
numpy.ndarray Array of polarization angle values.
- geocent_time
- property theta_jn
Class object (of FunctionConditioning) for inclination angle, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the inclination angle distribution
pdf: returns the probability density function of the inclination angle distribution
function: returns the inclination angle distribution function.
- Returns:
- theta_jn
numpy.ndarray Array of inclination angle values, i.e. the angle between the line of sight and the orbital angular momentum (rad).
- theta_jn
- property a_1
Class object (of FunctionConditioning) for spin1 magnitude, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the spin1 magnitude distribution
pdf: returns the probability density function of the spin1 magnitude distribution
function: returns the spin1 magnitude distribution function.
- Returns:
- a_1
numpy.ndarray Array of spin magnitude values for the primary body.
- a_1
- property a_2
Class object (of FunctionConditioning) for spin2 magnitude, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the spin2 magnitude distribution
pdf: returns the probability density function of the spin2 magnitude distribution
function: returns the spin2 magnitude distribution function.
- Returns:
- a_2
numpy.ndarray Array of spin magnitude values for the secondary body.
- a_2
- property tilt_1
Class object (of FunctionConditioning) for tilt1 angle, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the tilt1 angle distribution
pdf: returns the probability density function of the tilt1 angle distribution
function: returns the tilt1 angle distribution function.
- Returns:
- tilt_1
numpy.ndarray Array of the spin tilt angle of the primary body, i.e. the angle between the spin vector and the orbital angular momentum for the primary body (rad).
- tilt_1
- property tilt_2
Class object (of FunctionConditioning) for tilt2 angle, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the tilt2 angle distribution
pdf: returns the probability density function of the tilt2 angle distribution
function: returns the tilt2 angle distribution function.
- Returns:
- tilt_2
numpy.ndarray Array of the spin tilt angle of the secondary body, i.e. the angle between the spin vector and the orbital angular momentum for the secondary body (rad).
- tilt_2
- property phi_12
Class object (of FunctionConditioning) for phi_12 angle, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the phi_12 angle distribution
pdf: returns the probability density function of the phi_12 angle distribution
function: returns the phi_12 angle distribution function.
- Returns:
- phi_12
numpy.ndarray Array of the spin tilt angle between the two spins, i.e., angle between the projections of the two spins onto the orbital plane (rad).
- phi_12
- property phi_jl
Class object (of FunctionConditioning) for phi_jl angle, with rvs/sampler as callback. Can also be a user defined callable sampler.
The class object contains the following attribute methods:
rvs: returns random samples from the phi_jl angle distribution
pdf: returns the probability density function of the phi_jl angle distribution
function: returns the phi_jl angle distribution function.
- Returns:
- phi_jl
numpy.ndarray Array of the angle values between the orientation of the total angular momentum around the orbital angular momentum (rad).
- phi_jl
- property available_gw_prior
Dictionary of all available prior distributions and their parameters.
This is a dynamically generated dictionary containing available samplers for each GW parameter type and their default parameter values.
- Returns:
- available_gw_prior
dict Nested dictionary organized by parameter type (e.g., ‘source_frame_masses’,
‘geocent_time’, etc.) with sampler names and default parameters.
- available_gw_prior
- z_min = 'None'
floatMinimum redshift of the source population
- z_max = 'None'
floatMaximum redshift of the source population
- event_type = 'None'
strType of event to generate.
e.g. ‘BBH’, ‘BNS’, ‘NSBH’
- source_priors = 'None'
dictDictionary of prior sampler functions.
- source_priors_params = 'None'
dictDictionary of prior sampler functions’ input parameters.
- cosmo
astropy.cosmologyCosmology to use.
- spin_zero = 'None'
boolIf True, spin prior is set to zero.
- spin_precession = 'False'
- directory = "'./interpolator_json'"
Directory path for storing interpolator JSON files.
- Returns:
- directory
str Path to the interpolator storage directory.
default: ‘./interpolator_json’
- directory
- sample_gw_parameters(size=1000, param=None)[source]
Sample all gravitational wave parameters for compact binaries.
Generates a complete set of intrinsic and extrinsic parameters including masses, redshift, luminosity distance, sky position, orientation, and optionally spin parameters.
- Parameters:
- size
int Number of samples to draw.
default: 1000
- param
dictorNone Dictionary of fixed parameter values.
Parameters in this dict will not be sampled.
default: None
- size
- Returns:
- gw_parameters
dict Dictionary of sampled GW parameters. The included parameters and their units are as follows (for default settings):
Parameter
Units
Description
zs
redshift of the source
geocent_time
s
GPS time of coalescence
ra
rad
right ascension
dec
rad
declination
phase
rad
phase of GW at reference frequency
psi
rad
polarization angle
theta_jn
rad
inclination angle
a_1
spin_1 of the compact binary
a_2
spin_2 of the compact binary
luminosity_distance
Mpc
luminosity distance
mass_1_source
Msun
mass_1 of the compact binary (source frame)
mass_2_source
Msun
mass_2 of the compact binary (source frame)
mass_1
Msun
mass_1 of the compact binary (detector frame)
mass_2
Msun
mass_2 of the compact binary (detector frame)
- gw_parameters
Examples
>>> from ler.gw_source_population import CBCSourceParameterDistribution >>> cbc = CBCSourceParameterDistribution() >>> params = cbc.sample_gw_parameters(size=1000) >>> print(list(params.keys()))
- binary_masses_BBH_powerlaw_gaussian(size, get_attribute=False, **kwargs)[source]
Sample source masses with PowerLaw+PEAK model for Population I/II BBH.
Implements the mass distribution model from LIGO-Virgo population analyses combining a power-law with a Gaussian peak component.
- Parameters:
- size
int Number of samples to draw.
- get_attribute
bool If True, return the sampler object instead of samples.
default: False
- **kwargs
dict Model parameters:
mminbh: Minimum BH mass (Msun), default: 4.98
mmaxbh: Maximum BH mass (Msun), default: 112.5
alpha: Power-law spectral index, default: 3.78
mu_g: Gaussian peak mean (Msun), default: 32.27
sigma_g: Gaussian peak width (Msun), default: 3.88
lambda_peak: Fraction in Gaussian component, default: 0.03
delta_m: Low-mass tapering range (Msun), default: 4.8
beta: Mass ratio power-law index, default: 0.81
- size
- Returns:
- mass_1_source
numpy.ndarray Array of primary masses in source frame (Msun).
- mass_2_source
numpy.ndarray Array of secondary masses in source frame (Msun).
- mass_1_source
Examples
>>> from ler.gw_source_population import CBCSourceParameterDistribution >>> cbc = CBCSourceParameterDistribution() >>> m1_src, m2_src = cbc.binary_masses_BBH_powerlaw_gaussian(size=1000)
- binary_masses_BBH_popIII_lognormal(size, get_attribute=False, **kwargs)[source]
Sample source masses for Population III BBH from lognormal distribution.
Based on Eqn. 1 and 4 of Ng et al. 2022 for Population III black holes.
- Parameters:
- size
int Number of samples to draw.
- get_attribute
bool If True, return the sampler object instead of samples.
default: False
- **kwargs
dict Model parameters:
m_min: Minimum BH mass (Msun), default: 5.0
m_max: Maximum BH mass (Msun), default: 150.0
Mc: Central mass scale (Msun), default: 30.0
sigma: Distribution width, default: 0.3
- size
- Returns:
- mass_1_source
numpy.ndarray Array of primary masses in source frame (Msun).
- mass_2_source
numpy.ndarray Array of secondary masses in source frame (Msun).
- mass_1_source
Examples
>>> from ler.gw_source_population import CBCSourceParameterDistribution >>> cbc = CBCSourceParameterDistribution(event_type='BBH_popIII') >>> m1_src, m2_src = cbc.binary_masses_BBH_popIII_lognormal(size=1000)
- binary_masses_BBH_primordial_lognormal(size, get_attribute=False, **kwargs)[source]
Sample source masses for primordial BBH from lognormal distribution.
Based on Eqn. 1 and 4 of Ng et al. 2022 for primordial black holes.
- Parameters:
- size
int Number of samples to draw.
- get_attribute
bool If True, return the sampler object instead of samples.
default: False
- **kwargs
dict Model parameters:
m_min: Minimum BH mass (Msun), default: 1.0
m_max: Maximum BH mass (Msun), default: 100.0
Mc: Central mass scale (Msun), default: 20.0
sigma: Distribution width, default: 0.3
- size
- Returns:
- mass_1_source
numpy.ndarray Array of primary masses in source frame (Msun).
- mass_2_source
numpy.ndarray Array of secondary masses in source frame (Msun).
- mass_1_source
- binary_masses_NSBH_broken_powerlaw(size, get_attribute=False, **kwargs)[source]
Sample source masses for NSBH from broken power-law distribution.
Uses gwcosmo-style broken power-law for black hole mass and power-law for neutron star mass.
- Parameters:
- size
int Number of samples to draw.
- get_attribute
bool If True, return the sampler object instead of samples.
default: False
- **kwargs
dict Model parameters:
mminbh: Minimum BH mass (Msun), default: 26
mmaxbh: Maximum BH mass (Msun), default: 125
alpha_1: Primary power-law index, default: 6.75
alpha_2: Secondary power-law index, default: 6.75
b: Break point, default: 0.5
delta_m: Tapering range (Msun), default: 5
mminns: Minimum NS mass (Msun), default: 1.0
mmaxns: Maximum NS mass (Msun), default: 3.0
alphans: NS mass power-law index, default: 0.0
- size
- Returns:
- mass_1_source
numpy.ndarray Array of BH masses in source frame (Msun).
- mass_2_source
numpy.ndarray Array of NS masses in source frame (Msun).
- mass_1_source
Examples
>>> from ler.gw_source_population import CBCSourceParameterDistribution >>> cbc = CBCSourceParameterDistribution(event_type='NSBH') >>> m1_src, m2_src = cbc.binary_masses_NSBH_broken_powerlaw(size=1000)
- binary_masses_uniform(size, get_attribute=False, **kwargs)[source]
Sample source masses from uniform distribution.
- Parameters:
- size
int Number of samples to draw.
- get_attribute
bool If True, return the sampler object instead of samples.
default: False
- **kwargs
dict Model parameters:
m_min: Minimum mass (Msun), default: 1.0
m_max: Maximum mass (Msun), default: 3.0
- size
- Returns:
- mass_1_source
numpy.ndarray Array of primary masses in source frame (Msun).
- mass_2_source
numpy.ndarray Array of secondary masses in source frame (Msun).
- mass_1_source
Examples
>>> from ler.gw_source_population import CBCSourceParameterDistribution >>> cbc = CBCSourceParameterDistribution() >>> m1_src, m2_src = cbc.binary_masses_uniform(size=1000)
- binary_masses_BNS_bimodal(size, get_attribute=False, **kwargs)[source]
Sample BNS masses from bimodal Gaussian distribution.
Based on Will M. Farr et al. 2020 Eqn. 6 for neutron star mass distribution combining two Gaussian peaks.
- Parameters:
- size
int Number of samples to draw.
- get_attribute
bool If True, return the sampler object instead of samples.
default: False
- **kwargs
dict Model parameters:
w: Weight of left peak, default: 0.643
muL: Mean of left peak (Msun), default: 1.352
sigmaL: Width of left peak (Msun), default: 0.08
muR: Mean of right peak (Msun), default: 1.88
sigmaR: Width of right peak (Msun), default: 0.3
mmin: Minimum mass (Msun), default: 1.0
mmax: Maximum mass (Msun), default: 2.3
- size
- Returns:
- mass_1_source
numpy.ndarray Array of primary masses in source frame (Msun).
- mass_2_source
numpy.ndarray Array of secondary masses in source frame (Msun).
- mass_1_source
Examples
>>> from ler.gw_source_population import CBCSourceParameterDistribution >>> cbc = CBCSourceParameterDistribution(event_type='BNS') >>> m1_src, m2_src = cbc.binary_masses_BNS_bimodal(size=1000)
- constant_values_n_size(size=100, get_attribute=False, **kwargs)[source]
Return array of constant values.
- Parameters:
- size
int Number of values to return.
default: 100
- get_attribute
bool If True, return the sampler object instead of samples.
default: False
- **kwargs
dict Model parameters:
value: Constant value to return, default: 0.0
- size
- Returns:
- values
numpy.ndarray Array of constant values.
- values
- sampler_uniform(size, get_attribute=False, **kwargs)[source]
Sample values from uniform distribution.
- Parameters:
- size
int Number of samples to draw.
- get_attribute
bool If True, return the sampler object instead of samples.
default: False
- **kwargs
dict Model parameters:
xmin: Minimum value, default: 0.0
xmax: Maximum value, default: 1.0
- size
- Returns:
- values
numpy.ndarray Array of uniformly distributed values in range [xmin, xmax].
- values
- sampler_cosine(size, get_attribute=False, **kwargs)[source]
Sample from cosine distribution for declination.
Samples values in range [-pi/2, pi/2] following a cosine distribution, appropriate for isotropic sky position declination.
- Parameters:
- size
int Number of samples to draw.
- get_attribute
bool If True, return the sampler object instead of samples.
default: False
- size
- Returns:
- values
numpy.ndarray Array of values in range [-pi/2, pi/2] (rad).
- values
- sampler_sine(size, get_attribute=False, **kwargs)[source]
Sample from sine distribution for inclination angles.
Samples values in range [0, pi] following a sine distribution, appropriate for isotropic orientation angles.
- Parameters:
- size
int Number of samples to draw.
- get_attribute
bool If True, return the sampler object instead of samples.
default: False
- size
- Returns:
- values
numpy.ndarray Array of values in range [0, pi] (rad).
- values
- ler.rates.load_json(file_name)[source]
Load a json file.
- Parameters:
- file_namestr
json file name for storing the parameters.
- Returns:
- paramdict
- ler.rates.append_json(file_name, new_dictionary, old_dictionary=None, replace=False)[source]
Append (values with corresponding keys) and update a json file with a dictionary. There are four options:
If old_dictionary is provided, the values of the new dictionary will be appended to the old dictionary and save in the ‘file_name’ json file.
If replace is True, replace the json file (with the ‘file_name’) content with the new_dictionary.
If the file does not exist, create a new one with the new_dictionary.
If none of the above, append the new dictionary to the content of the json file.
- Parameters:
- file_namestr
json file name for storing the parameters.
- new_dictionarydict
dictionary to be appended to the json file.
- old_dictionarydict, optional
If provided the values of the new dictionary will be appended to the old dictionary and save in the ‘file_name’ json file. Default is None.
- replacebool, optional
If True, replace the json file with the dictionary. Default is False.
- ler.rates.get_param_from_json(json_file)[source]
Function to get the parameters from json file.
- Parameters:
- json_filestr
json file name for storing the parameters.
- Returns:
- paramdict
- ler.rates.batch_handler(size, batch_size, sampling_routine, output_jsonfile, save_batch=True, resume=False, param_name='parameters')[source]
Function to run the sampling in batches.
- Parameters:
- sizeint
number of samples.
- batch_sizeint
batch size.
- sampling_routinefunction
sampling function. It should have ‘size’ as input and return a dictionary.
- output_jsonfilestr
json file name for storing the parameters.
- save_batchbool, optional
if True, save sampled parameters in each iteration. Default is True.
- resumebool, optional
if True, resume sampling from the last batch. Default is False.
- param_namestr, optional
name of the parameter. Default is ‘parameters’.
- Returns:
- dict_bufferdict
dictionary of parameters.
- class ler.rates.GWRATES(npool=int(4), z_min=0.0, z_max=10.0, event_type='BBH', cosmology=None, pdet_finder=None, json_file_names=None, interpolator_directory='./interpolator_json', create_new_interpolator=False, ler_directory='./ler_data', verbose=True, **kwargs)[source]
Bases:
ler.gw_source_population.CBCSourceParameterDistributionClass to sample GW events and calculate their detection rates.
This class provides functionality for sampling gravitational wave source parameters, detection probabilities, and computing detection rates for compact binary coalescence events. Parameters of simulated events are stored in JSON files (not as class attributes) to conserve RAM memory.
Key Features:
Sampling of GW event parameters
Detection probability calculation using
gwsnrpackage or custom functionsRate calculation for detectable events
Batch processing for memory efficiency
JSON-based parameter storage for reproducibility
- Parameters:
- npool
int Number of cores to use for parallel processing.
default: 4
- z_min
float Minimum redshift of the source population.
default: 0.0
- z_max
float Maximum redshift of the source population.
default: 10.0
- event_type
str Type of event to generate.
Options:
‘BBH’: Binary Black Hole
‘BNS’: Binary Neutron Star
‘NSBH’: Neutron Star-Black Hole
default: ‘BBH’
- cosmology
astropy.cosmologyorNone Cosmology to use for the calculation.
default: LambdaCDM(H0=70, Om0=0.3, Ode0=0.7, Tcmb0=0.0, Neff=3.04, m_nu=None, Ob0=0.0)
- pdet_finder
callableorNone Custom detection probability finder function.
If None, uses gwsnr’s pdet calculator.
The function should follow the signature:
def pdet_finder(gw_param_dict): return pdet_net_dictwhere pdet_net_dict.keys = [‘pdet_net’].
default: None
- json_file_names
dictorNone Names of the JSON files to store the necessary parameters.
default: dict(gwrates_params=”gwrates_params.json”, gw_param=”gw_param.json”, gw_param_detectable=”gw_param_detectable.json”)
- interpolator_directory
str Directory to store the interpolators.
default: ‘./interpolator_json’
- create_new_interpolator
boolordict Whether to create new interpolators.
default: False
- ler_directory
str Directory to store the output parameters.
default: ‘./ler_data’
- verbose
bool If True, print all chosen parameters during initialization.
default: True
- **kwargs
dict Additional keyword arguments passed to parent classes:
CBCSourceParameterDistributionandGWSNR(if pdet_finder is not provided).
- npool
Notes
GWRATESclass inherits fromCBCSourceParameterDistribution.Refer to that class for additional inherited attributes and methods.
Parameters are stored in JSON files for memory efficiency and reproducibility.
For stable rate estimates, use size >= 1e6 samples.
Examples
Basic usage:
>>> from ler.rates import GWRATES >>> gwrates = GWRATES() >>> gw_params = gwrates.gw_cbc_statistics() >>> gwrates.gw_rate()
Instance Methods
GWRATES class has the following methods:
Method
Description
Generate GW source parameters
Calculate the GW detection rate
Select n GW detectable events
Instance Attributes
GWRATES class has the following attributes:
Attribute
Type
Unit
Description
intNumber of parallel processing cores
floatMinimum source redshift
floatMaximum source redshift
strType of CBC event
astropy.cosmology|Cosmology for calculations
dictJSON file names for parameter storage
strDirectory for interpolator files
strDirectory for output parameter files
listList of detector names
callableDetection probability finder function
dictAll GWRATES initialization arguments
- property npool
Number of parallel processing cores.
- Returns:
- npool
int Number of logical cores to use for multiprocessing.
default: 4
- npool
- property z_min
Minimum redshift of the source population.
- Returns:
- z_min
float Minimum source redshift for sampling.
default: 0.0
- z_min
- property z_max
Maximum redshift of the source population.
- Returns:
- z_max
float Maximum source redshift for sampling.
default: 10.0
- z_max
- property event_type
Type of compact binary coalescence event.
- Returns:
- event_type
str Type of CBC event.
Options:
‘BBH’: Binary Black Hole
‘BNS’: Binary Neutron Star
‘NSBH’: Neutron Star-Black Hole
default: ‘BBH’
- event_type
- property cosmo
Astropy cosmology object for distance calculations.
- Returns:
- cosmo
astropy.cosmology Cosmology used for luminosity distance and comoving volume calculations.
default: LambdaCDM(H0=70, Om0=0.3, Ode0=0.7, Tcmb0=0.0, Neff=3.04, m_nu=None, Ob0=0.0)
- cosmo
- property json_file_names
Dictionary of JSON file names for parameter storage.
- Returns:
- json_file_names
dict Dictionary with keys:
‘gwrates_params’: GWRATES initialization parameters
‘gw_param’: GW event parameters
‘gw_param_detectable’: Detectable GW events
- json_file_names
- property interpolator_directory
Directory path for interpolator JSON files.
- Returns:
- interpolator_directory
str Path to directory containing interpolator data files.
default: ‘./interpolator_json’
- interpolator_directory
- property ler_directory
Directory path for LeR output files.
- Returns:
- ler_directory
str Path to directory for storing output parameter files.
default: ‘./ler_data’
- ler_directory
- property create_new_interpolator
Configuration dictionary for interpolator creation settings.
- Returns:
- create_new_interpolator
dict Dictionary specifying which interpolators to create.
Each key is an interpolator name, and values are dicts with:
‘create_new’: bool - Whether to create new interpolator
‘resolution’: int or list - Grid resolution for interpolation
Special key ‘gwsnr’ is a bool for GWSNR interpolator creation. Default: dict(
merger_rate_density = {‘create_new’: False, ‘resolution’: 500}, redshift_distribution = {‘create_new’: False, ‘resolution’: 500}, luminosity_distance = {‘create_new’: False, ‘resolution’: 500}, differential_comoving_volume = {‘create_new’: False, ‘resolution’: 500}, source_frame_masses = {‘create_new’: False, ‘resolution’: 500}, geocent_time = {‘create_new’: False, ‘resolution’: 500}, ra = {‘create_new’: False, ‘resolution’: 500}, dec = {‘create_new’: False, ‘resolution’: 500}, phase = {‘create_new’: False, ‘resolution’: 500}, psi = {‘create_new’: False, ‘resolution’: 500}, theta_jn = {‘create_new’: False, ‘resolution’: 500}, a_1 = {‘create_new’: False, ‘resolution’: 500}, a_2 = {‘create_new’: False, ‘resolution’: 500}, tilt_1 = {‘create_new’: False, ‘resolution’: 500}, tilt_2 = {‘create_new’: False, ‘resolution’: 500}, phi_12 = {‘create_new’: False, ‘resolution’: 500}, phi_jl = {‘create_new’: False, ‘resolution’: 500},
)
- create_new_interpolator
- property list_of_detectors
List of gravitational wave detector names.
- Returns:
- list_of_detectors
list List of detector identifiers used for pdet calculations.
Typically set from gwsnr.detector_list during initialization.
- list_of_detectors
- property pdet_finder
Detection probability finder function.
- Returns:
- pdet_finder
callable Function that calculates detection probability for GW events.
The function signature should be:
pdet_finder(gw_param_dict) -> dictwith key ‘pdet_net’.
- pdet_finder
- property gwrates_args
Dictionary of all GWRATES initialization arguments.
- Returns:
- gwrates_args
dict Dictionary containing all parameters used to initialize GWRATES and
its parent classes, useful for reproducibility.
- gwrates_args
- gw_cbc_statistics(size=100000, batch_size=50000, resume=True, save_batch=False, output_jsonfile=None)[source]
Generate GW source parameters with detection probabilities.
This function calls the _gw_sampling_routine function to generate the parameters in batches. The generated parameters are stored in a JSON file; if save_batch=True, it updates the file after each batch.
- Parameters:
- size
int Number of samples to generate.
default: 100000
- batch_size
int Batch size for sampling.
default: 50000
- resume
bool If True, resume from the last batch.
default: True
- save_batch
bool If True, save parameters after each batch.
If False, save all parameters at the end (faster).
default: False
- output_jsonfile
strorNone JSON file name for storing the parameters.
default: ‘gw_param.json’ (stored in ler_directory)
- size
- Returns:
- gw_param
dict dictionary of GW source parameters. The included parameters and their units are as follows (for default settings):
- gw_param
Examples
>>> from ler.rates import GWRATES >>> gwrates = GWRATES() >>> param = gwrates.gw_cbc_statistics()
- gw_rate(gw_param=None, pdet_threshold=0.5, pdet_type='boolean', output_jsonfile=None)[source]
Calculate the GW detection rate.
This function calculates the detection rate and stores the parameters of detectable events in a JSON file.
- Parameters:
- gw_param
dictorstrorNone Dictionary of GW source parameters or JSON file name.
default: None (uses self.json_file_names[“gw_param”])
- pdet_threshold
float Threshold for detection probability.
default: 0.5
- pdet_type
str Detectability condition type.
Options:
‘boolean’: Binary detection based on pdet_threshold
‘probability_distribution’: Uses pdet values directly
default: ‘boolean’
- output_jsonfile
strorNone JSON file name for storing detectable event parameters.
default: ‘gw_param_detectable.json’
- gw_param
- Returns:
- total_rate
float Total GW detection rate (yr^-1).
- gw_param
dict dictionary of GW source parameters of the detectable events. The included parameters and their units are as follows (for default settings):
- total_rate
Examples
>>> from ler.rates import GWRATES >>> gwrates = GWRATES() >>> gwrates.gw_cbc_statistics() >>> total_rate, gw_param = gwrates.gw_rate()
- rate_function(detectable_size, total_size, verbose=True)[source]
Helper function to calculate the detection rate via Monte Carlo integration.
- Parameters:
- detectable_size
intorfloat Number of detectable events.
- total_size
int Total number of simulated events.
- verbose
bool If True, print rate information.
default: True
- detectable_size
- Returns:
- rate
float Detection rate (yr^-1).
- rate
- selecting_n_gw_detectable_events(size=100, batch_size=50000, stopping_criteria=dict(relative_diff_percentage=0.5, number_of_last_batches_to_check=4), pdet_threshold=0.5, resume=True, output_jsonfile='gw_params_n_detectable.json', meta_data_file='meta_gw.json', pdet_type='boolean', trim_to_size=False)[source]
Generate a target number of detectable GW events by iterative batch sampling.
This function samples GW parameters in batches and saves only the detectable events to a JSON file. It optionally stops when the cumulative rate has stabilized based on the stopping criteria.
- Parameters:
- size
int Target number of detectable samples to collect.
default: 100
- batch_size
int Batch size for sampling.
default: 50000
- stopping_criteria
dictorNone Criteria for stopping sample collection (but will not stop until n>size).
Keys:
‘relative_diff_percentage’: Maximum relative difference in rate (float)
‘number_of_last_batches_to_check’: Number of batches for comparison (int)
If None, stops when detectable events exceed size.
default: dict(relative_diff_percentage=0.5, number_of_last_batches_to_check=4)
- pdet_threshold
float Threshold for detection probability.
default: 0.5
- resume
bool If True, resume from the last batch.
default: True
- output_jsonfile
str JSON file name for storing detectable event parameters.
default: ‘gw_params_n_detectable.json’
- meta_data_file
str JSON file name for storing metadata.
default: ‘meta_gw.json’
- pdet_type
str Detectability condition type.
Options:
‘boolean’: Binary detection based on pdet_threshold
‘probability_distribution’: Uses pdet values directly
default: ‘boolean’
- trim_to_size
bool If True, trim final result to exactly the specified size.
default: False
- size
- Returns:
- param_final
dict dictionary of GW source parameters of the detectable events. The included parameters and their units are as follows (for default settings):
Parameter
Units
Description
zs
redshift of the source
geocent_time
s
GPS time of coalescence
ra
rad
right ascension
dec
rad
declination
phase
rad
phase of GW at reference frequency
psi
rad
polarization angle
theta_jn
rad
inclination angle
a_1
spin of the primary compact binary
a_2
spin of the secondary compact binary
luminosity_distance
Mpc
luminosity distance
mass_1_source
Msun
mass of the primary compact binary (source frame)
mass_2_source
Msun
mass of the secondary compact binary (source frame)
mass_1
Msun
mass_1 of the compact binary (detector frame)
mass_2
Msun
mass_2 of the compact binary (detector frame)
pdet_L1
pdet of L1
pdet_H1
pdet of H1
pdet_V1
pdet of V1
pdet_net
pdet of the network
- param_final
Examples
>>> from ler.rates import GWRATES >>> gwrates = GWRATES() >>> gw_param = gwrates.selecting_n_gw_detectable_events(size=100)