Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion compas_python_utils/compas_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import subprocess
import sys
from pathlib import Path
from typing import Iterable, Optional, Sequence
from typing import Optional
from collections.abc import Iterable, Sequence


PACKAGE_ROOT = Path(__file__).resolve().parent
Expand Down
4 changes: 2 additions & 2 deletions compas_python_utils/cosmic_integration/ClassCOMPAS.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
) from exc


class COMPASData(object):
class COMPASData:
def __init__(
self,
path=None,
Expand All @@ -31,7 +31,7 @@ def __init__(
if self.path is None:
print("Template COMPASData object created with no data path")
elif not os.path.isfile(path):
raise ValueError( "h5 file not found. Wrong path given? {}".format(path))
raise ValueError( f"h5 file not found. Wrong path given? {path}")

# Crucial values to be able to calculate MSSFR
self.metallicityGrid = None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from . import ClassMSSFR
from .cosmology import get_cosmology
import selection_effects
class CosmicIntegrator(object):
class CosmicIntegrator:
"""

The cosmological integrator calculates the rate
Expand Down
6 changes: 3 additions & 3 deletions compas_python_utils/cosmic_integration/ClassMSSFR.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@



class MSSFR(object):
class MSSFR:
"""
This class is to calculate the metallicity specific star formation
rate in a specific metallicity bin.
Expand Down Expand Up @@ -416,7 +416,7 @@ def Ma2015ZM(self, ZZSun, z):

def Langer2005ZM(self, ZZsun, z):
Mstar = 7.64*10**10
logM = np.log10((((ZZsun*(10**(0.3*z)))**2)*Mstar))
logM = np.log10(((ZZsun*(10**(0.3*z)))**2)*Mstar)
return logM

def Langer2005OffsetZM(self, ZZsun, z):
Expand Down Expand Up @@ -500,7 +500,7 @@ def SFR_Strolger(self, tGyrs):

SFR = 10**9 *a * (tGyrs**b * np.exp(-tGyrs/c) + d*np.exp(d*(tGyrs-t0)/c))
if np.isnan(SFR.any()):
raise ValueError("Nan in SFR calculation for %s" %(self.SFRprescription))
raise ValueError(f"Nan in SFR calculation for {self.SFRprescription}")
return SFR #Msun yr-1 Gpc-3 in comoving volume

def SFR_Neijssel(self, z):
Expand Down
24 changes: 10 additions & 14 deletions compas_python_utils/cosmic_integration/FastCosmicIntegration.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ def compute_snr_and_detection_grids(dco_type, sensitivity="O1", snr_threshold=8.
"""
# If DCO type includes a WD, return empty arrays since we currently only support LVK sensitivity
if dco_type in ["WDWD", "NSWD", "WDBH"]:
warnings.warn("!! Detected rate is not computed since DCO type {} doesn't work with LVK sensitivity {}".format(dco_type, sensitivity))
warnings.warn(f"!! Detected rate is not computed since DCO type {dco_type} doesn't work with LVK sensitivity {sensitivity}")

# get interpolator given sensitivity
interpolator = selection_effects.SNRinterpolator(sensitivity)
Expand Down Expand Up @@ -419,7 +419,7 @@ def find_detection_rate(path, dco_type="BHBH", merger_output_filename=None, weig


for arg, arg_str in nonnegative_args:
assert arg >= 0.0, "{} must be nonnegative".format(arg_str)
assert arg >= 0.0, f"{arg_str} must be nonnegative"

# warn if input is not advisable
if redshift_step > max_redshift_detection:
Expand Down Expand Up @@ -570,7 +570,7 @@ def append_rates(path, detection_rate, formation_rate, merger_rate, redshifts, C

#################################################
# Create a new group where we will store data
new_rate_group = 'Rates_mu0{}_muz{}_alpha{}_sigma0{}_sigmaz{}'.format(mu0, muz, alpha, sigma0, sigmaz)
new_rate_group = f'Rates_mu0{mu0}_muz{muz}_alpha{alpha}_sigma0{sigma0}_sigmaz{sigmaz}'
if append_binned_by_z:
new_rate_group = new_rate_group + '_zBinned'

Expand Down Expand Up @@ -656,11 +656,11 @@ def append_rates(path, detection_rate, formation_rate, merger_rate, redshifts, C
if rate_list_names[i] in h_new[new_rate_group].keys():
del h_new[new_rate_group][rate_list_names[i]]
# write rates as a new data set
dataNew = h_new[new_rate_group].create_dataset(rate_list_names[i], data=data)
h_new[new_rate_group].create_dataset(rate_list_names[i], data=data)

#Always close your files again ;)
h_new.close()
print(('Done with append_rates :) your new files are here: {}'.format(path)))
print(f'Done with append_rates :) your new files are here: {path}')



Expand All @@ -684,12 +684,8 @@ def delete_rates(path, mu0=0.035, muz=-0.23, sigma0=0.39, sigmaz=0., alpha=0., a
#Open hdf5 file that we will write on
print('pathToData', path)
with h5.File(path, 'r+') as h_new:
# The rate info is shaped as BSE_Double_Compact_Objects[COMPAS.DCOmask] , len(redshifts)
DCO = h_new['BSE_Double_Compact_Objects']#

#################################################
# Name of the group that has the data stored
new_rate_group = 'Rates_mu0{}_muz{}_alpha{}_sigma0{}_sigmaz{}'.format(mu0, muz, alpha, sigma0, sigmaz)
new_rate_group = f'Rates_mu0{mu0}_muz{muz}_alpha{alpha}_sigma0{sigma0}_sigmaz{sigmaz}'
if append_binned_by_z:
new_rate_group = new_rate_group + '_zBinned'

Expand All @@ -699,7 +695,7 @@ def delete_rates(path, mu0=0.035, muz=-0.23, sigma0=0.39, sigmaz=0., alpha=0., a
h_new.close()
return
else:
print('You want to remove this group, %s, from the hdf5 file, removing now..'%(new_rate_group))
print(f'You want to remove this group, {new_rate_group}, from the hdf5 file, removing now..')
del h_new[new_rate_group]
#Always close your files again ;)
h_new.close()
Expand Down Expand Up @@ -777,13 +773,13 @@ def plot_rates(save_dir, formation_rate, merger_rate, detection_rate, redshifts,
#Plotvalues

# Add text upper left corner
axes[0,0].text(0.05, 0.8, "mu0=%s \nmuz=%s \nsigma0=%s \nsigmaz=%s \nalpha=%s"%(mu0,muz,sigma0,sigmaz,alpha), transform=axes[0,0].transAxes, size = fs)
axes[0,0].text(0.05, 0.8, f"mu0={mu0} \nmuz={muz} \nsigma0={sigma0} \nsigmaz={sigmaz} \nalpha={alpha}", transform=axes[0,0].transAxes, size = fs)

for ax in axes.flatten():
ax.tick_params(labelsize=0.9*fs)

# Save and show :)
plt.savefig(save_dir +'Rate_Info'+"mu0%s_muz%s_alpha%s_sigma0%s_sigmaz%s"%(mu0,muz,alpha,sigma0, sigmaz)+'.png', bbox_inches='tight')
plt.savefig(save_dir +'Rate_Info'+f"mu0{mu0}_muz{muz}_alpha{alpha}_sigma0{sigma0}_sigmaz{sigmaz}"+'.png', bbox_inches='tight')
if show_plot:
plt.show()
else:
Expand Down Expand Up @@ -863,7 +859,7 @@ def parse_cli_args():
def set_cosmology(cosmology_name="Planck18"):
# Set cosmology using astropy, print a warning if TNG fit is used with Planck18 cosmology (since TNG uses Planck15)
if cosmology_name == "Planck18": print("USING PLANCK18 AS COSMOLOGY! If working with TNG fit, you may want to use Planck15 instead for self-consistency.")
else: print("Using %s as cosmology!"%cosmology_name)
else: print(f"Using {cosmology_name} as cosmology!")

return getattr(importlib.import_module('astropy.cosmology'), cosmology_name)

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import numpy as np
import h5py
from .gpu_utils import xp
from typing import List, Optional
from typing import Optional

from ..totalMassEvolvedPerZ import (
analytical_star_forming_mass_per_binary_using_kroupa_imf,
Expand Down Expand Up @@ -57,7 +57,7 @@ def __init__(
t_delay: np.ndarray,
z_zams: np.ndarray,
n_systems: int,
dcos_included: List[str],
dcos_included: list[str],
m1_min: float = None,
m1_max: float = None,
m2_min: float = None,
Expand Down Expand Up @@ -94,7 +94,7 @@ def __init__(
def from_compas_h5(
cls,
path: str,
dcos_included: List[str] = ["BBH"],
dcos_included: list[str] = ["BBH"],
m1_min: float = None,
m1_max: float = None,
m2_min: float = None,
Expand Down Expand Up @@ -148,7 +148,7 @@ def from_compas_h5(
@staticmethod
def _generate_mask(
path: str,
dcos_included: List[str],
dcos_included: list[str],
) -> xp.ndarray:
type_mask = _generate_dco_mask(path, dcos_included)

Expand Down Expand Up @@ -258,7 +258,7 @@ def __str__(self):

def _generate_dco_mask(
compas_path: str,
dcos_included: List[str]
dcos_included: list[str]
) -> xp.ndarray:
# Load fundamental DCO variables
t1, t2 = _load_data(
Expand All @@ -283,7 +283,7 @@ def _generate_dco_mask(
return type_mask


def _load_data(path: str, group: str, var_names: List[str], mask: Optional[xp.ndarray] = None):
def _load_data(path: str, group: str, var_names: list[str], mask: Optional[xp.ndarray] = None):
with h5py.File(path, "r") as f:
data = [f[group][v][...].squeeze().flatten() for v in var_names]
if mask is not None:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import numpy as np
import os
from typing import Dict, List
import h5py as h5
from tqdm.auto import trange

Expand All @@ -18,15 +17,15 @@ class DetectionMatrix:
def __init__(
self,
compas_path: str,
cosmological_parameters: Dict,
cosmological_parameters: dict,
rate_matrix: np.ndarray,
chirp_mass_bins: np.array,
redshift_bins: np.array,
n_systems: int,
n_dcos: int,
outdir: str = None,
sens: str = 'O1',
dcos_included: List[str] = ["BBH"],
dcos_included: list[str] = ["BBH"],
bootstrapped_rate_matrices: np.ndarray = None
):
self.compas_path = compas_path
Expand Down Expand Up @@ -57,15 +56,15 @@ def outdir(self, outdir):
def from_compas_output(
cls,
compas_path: str,
cosmological_parameters: Dict = dict(aSF=0.01, dSF=4.70, mu_z=-.23, sigma_z=0),
cosmological_parameters: dict = dict(aSF=0.01, dSF=4.70, mu_z=-.23, sigma_z=0),
max_detectable_redshift: float = 1.0,
chirp_mass_bins: int = None,
redshift_bins: int = None,
outdir: str = None,
save_plots: bool = False,
n_bootstrapped_matrices: int = 0,
sens: str = 'O1',
dcos_included: List[str] = ["BBH"],
dcos_included: list[str] = ["BBH"],
) -> "DetectionMatrix":

dco_population = BinaryPopulation.from_compas_h5(compas_path, dcos_included=dcos_included)
Expand Down Expand Up @@ -126,7 +125,7 @@ def save(self):
with h5.File(f"{self.outdir}/{self.label}.h5", "w") as f:
recursively_save_dict_contents_to_group(f, '/', self.to_dict())

def to_dict(self) -> Dict:
def to_dict(self) -> dict:
return dict(
compas_path=self.compas_path,
cosmological_parameters=self.cosmological_parameters,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import h5py
from typing import Dict
import numpy as np


Expand All @@ -15,7 +14,7 @@ def recursively_load_dict_contents_from_group(h5file: h5py.File, group: str):
return output


def recursively_save_dict_contents_to_group(h5file: h5py.File, group: str, dic: Dict):
def recursively_save_dict_contents_to_group(h5file: h5py.File, group: str, dic: dict):
for key, item in dic.items():
item = encode_for_hdf5(key, item)
if isinstance(item, dict):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import numpy as np
import matplotlib.pyplot as plt
from corner import corner
from typing import List
import warnings
from .conversions import m1_m2_to_eta_chirp_mass

Expand Down Expand Up @@ -127,7 +126,7 @@ def plot_sfr_and_metallicity(
p_draw_metallicity: np.array,
metallicity_label: str,
sf_label: str,
redshift_range: List, logZ_range: List,
redshift_range: list, logZ_range: list,
) -> plt.Figure:
fig, axes = plt.subplots(3, 1, figsize=(5, 8))
ax = axes[0]
Expand Down Expand Up @@ -220,7 +219,7 @@ def plot_snr_grid(


def plot_binary_population(
data: np.ndarray, params: List[str]
data: np.ndarray, params: list[str]
) -> plt.Figure:
n_sys = len(data)
# mask out the outliers
Expand Down
6 changes: 3 additions & 3 deletions compas_python_utils/cosmic_integration/generate_frame_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ def multiple_injections (path="/Users/ilyam/Work/COMPASresults/popsynth/Arash/",
filename="mergers.txt", dz=0.001, Tobs=1./365.25/24/60, T0=1234567):
random.seed()
#path="./"
input=open(path+filename, 'r')
input=open(path+filename)
input.readline()
input.readline()
count=0
Expand Down Expand Up @@ -59,8 +59,8 @@ def one_injection (m1, m2, z, distance, T0, Tobs):
waveform_generator=waveform_generator)


for interferometer in interferometers:
signal = interferometer.get_detector_response(waveform_generator.frequency_domain_strain(), injection_parameters)
# for interferometer in interferometers:
# signal = interferometer.get_detector_response(waveform_generator.frequency_domain_strain(), injection_parameters)
#interferometer.plot_data(signal=signal, outdir=path, label='DCO)


Expand Down
8 changes: 3 additions & 5 deletions compas_python_utils/cosmic_integration/selection_effects.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created for Python 3

@author: Sebastian M. Gaebel
@email: sgaebel@star.sr.bham.ac.uk
"""

from __future__ import division, print_function
import h5py
import numpy as np
import os
Expand Down Expand Up @@ -155,11 +153,11 @@ def __init__(self, first_arg, second_arg, mode='scipy'):
"""
if isinstance(first_arg, str) and isinstance(second_arg, str):
if not os.path.isfile(first_arg):
raise FileNotFoundError('HDF5 file expected: %r' % first_arg)
raise FileNotFoundError(f'HDF5 file expected: {first_arg!r}')
with h5py.File(first_arg, 'r') as hdf:
mass_axis = hdf['mass_axis'][...]
if second_arg not in hdf['snr_values']:
raise ValueError('Group %r not found.' % second_arg)
raise ValueError(f'Group {second_arg!r} not found.')
snr_grid = hdf['snr_values'][second_arg][...]
else:
mass_axis = first_arg
Expand All @@ -174,7 +172,7 @@ def __init__(self, first_arg, second_arg, mode='scipy'):
self.mass_axis = np.log(mass_axis)
self.snr_grid = snr_grid
else:
raise ValueError('Invalid mode: %r' % mode)
raise ValueError(f'Invalid mode: {mode!r}')

def __call__(self, m1, m2):
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import h5py as h5
import functools

@functools.lru_cache()
@functools.lru_cache
def __get_imf_normalisation_values(m1=0.01, m2=0.08, m3=0.5, m4=200.0, a12=0.3, a23=1.3, a34=2.3):
b1 = 1 / (
(m2 ** (1 - a12) - m1 ** (1 - a12)) / (1 - a12)
Expand Down
2 changes: 1 addition & 1 deletion compas_python_utils/debugging_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ def _remap_stype(int_stype):
# event type: CEE, RLOF 2->1, RLOF 1->2
char_m = '&' if is_mrg else '=' if is_cee else '<' if is_rl2 else '>'
# event string for this star, _ is event separator
event_str += "{}{}{}_".format(char_l, char_m, char_r)
event_str += f"{char_l}{char_m}{char_r}_"
# return event string for this star (pop the last underscore first)
event_str = np.array(event_str[:-1], dtype=np.str_)
return event_str
Expand Down
Loading
Loading