diff --git a/compas_python_utils/compas_runner.py b/compas_python_utils/compas_runner.py index 052b440fc..e28aa0e9c 100644 --- a/compas_python_utils/compas_runner.py +++ b/compas_python_utils/compas_runner.py @@ -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 diff --git a/compas_python_utils/cosmic_integration/ClassCOMPAS.py b/compas_python_utils/cosmic_integration/ClassCOMPAS.py index 4a24dd15e..0c691711a 100644 --- a/compas_python_utils/cosmic_integration/ClassCOMPAS.py +++ b/compas_python_utils/cosmic_integration/ClassCOMPAS.py @@ -16,7 +16,7 @@ ) from exc -class COMPASData(object): +class COMPASData: def __init__( self, path=None, @@ -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 diff --git a/compas_python_utils/cosmic_integration/ClassCosmicIntegrator.py b/compas_python_utils/cosmic_integration/ClassCosmicIntegrator.py index 86fa1cbba..592d1a709 100644 --- a/compas_python_utils/cosmic_integration/ClassCosmicIntegrator.py +++ b/compas_python_utils/cosmic_integration/ClassCosmicIntegrator.py @@ -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 diff --git a/compas_python_utils/cosmic_integration/ClassMSSFR.py b/compas_python_utils/cosmic_integration/ClassMSSFR.py index d5dc32766..7731a39d3 100644 --- a/compas_python_utils/cosmic_integration/ClassMSSFR.py +++ b/compas_python_utils/cosmic_integration/ClassMSSFR.py @@ -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. @@ -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): @@ -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): diff --git a/compas_python_utils/cosmic_integration/FastCosmicIntegration.py b/compas_python_utils/cosmic_integration/FastCosmicIntegration.py index 0f0818248..6c2c14cfb 100644 --- a/compas_python_utils/cosmic_integration/FastCosmicIntegration.py +++ b/compas_python_utils/cosmic_integration/FastCosmicIntegration.py @@ -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) @@ -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: @@ -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' @@ -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}') @@ -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' @@ -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() @@ -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: @@ -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) diff --git a/compas_python_utils/cosmic_integration/binned_cosmic_integrator/binary_population.py b/compas_python_utils/cosmic_integration/binned_cosmic_integrator/binary_population.py index cb8b23d28..ff9b8616f 100644 --- a/compas_python_utils/cosmic_integration/binned_cosmic_integrator/binary_population.py +++ b/compas_python_utils/cosmic_integration/binned_cosmic_integrator/binary_population.py @@ -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, @@ -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, @@ -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, @@ -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) @@ -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( @@ -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: diff --git a/compas_python_utils/cosmic_integration/binned_cosmic_integrator/detection_matrix.py b/compas_python_utils/cosmic_integration/binned_cosmic_integrator/detection_matrix.py index 25f7e272b..98c6ad7d7 100644 --- a/compas_python_utils/cosmic_integration/binned_cosmic_integrator/detection_matrix.py +++ b/compas_python_utils/cosmic_integration/binned_cosmic_integrator/detection_matrix.py @@ -1,6 +1,5 @@ import numpy as np import os -from typing import Dict, List import h5py as h5 from tqdm.auto import trange @@ -18,7 +17,7 @@ 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, @@ -26,7 +25,7 @@ def __init__( 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 @@ -57,7 +56,7 @@ 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, @@ -65,7 +64,7 @@ def from_compas_output( 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) @@ -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, diff --git a/compas_python_utils/cosmic_integration/binned_cosmic_integrator/io.py b/compas_python_utils/cosmic_integration/binned_cosmic_integrator/io.py index 32115f59a..b73b2b4ef 100644 --- a/compas_python_utils/cosmic_integration/binned_cosmic_integrator/io.py +++ b/compas_python_utils/cosmic_integration/binned_cosmic_integrator/io.py @@ -1,5 +1,4 @@ import h5py -from typing import Dict import numpy as np @@ -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): diff --git a/compas_python_utils/cosmic_integration/binned_cosmic_integrator/plotting.py b/compas_python_utils/cosmic_integration/binned_cosmic_integrator/plotting.py index 22a68be00..5caa6a245 100644 --- a/compas_python_utils/cosmic_integration/binned_cosmic_integrator/plotting.py +++ b/compas_python_utils/cosmic_integration/binned_cosmic_integrator/plotting.py @@ -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 @@ -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] @@ -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 diff --git a/compas_python_utils/cosmic_integration/generate_frame_file.py b/compas_python_utils/cosmic_integration/generate_frame_file.py index 631e79818..7142cb592 100644 --- a/compas_python_utils/cosmic_integration/generate_frame_file.py +++ b/compas_python_utils/cosmic_integration/generate_frame_file.py @@ -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 @@ -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) diff --git a/compas_python_utils/cosmic_integration/selection_effects.py b/compas_python_utils/cosmic_integration/selection_effects.py index bcd1ebd15..e6a21eeab 100644 --- a/compas_python_utils/cosmic_integration/selection_effects.py +++ b/compas_python_utils/cosmic_integration/selection_effects.py @@ -1,5 +1,4 @@ #! /usr/bin/env python3 -# -*- coding: utf-8 -*- """ Created for Python 3 @@ -7,7 +6,6 @@ @email: sgaebel@star.sr.bham.ac.uk """ -from __future__ import division, print_function import h5py import numpy as np import os @@ -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 @@ -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): """ diff --git a/compas_python_utils/cosmic_integration/totalMassEvolvedPerZ.py b/compas_python_utils/cosmic_integration/totalMassEvolvedPerZ.py index 78907e88d..6370f2e43 100644 --- a/compas_python_utils/cosmic_integration/totalMassEvolvedPerZ.py +++ b/compas_python_utils/cosmic_integration/totalMassEvolvedPerZ.py @@ -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) diff --git a/compas_python_utils/debugging_utils.py b/compas_python_utils/debugging_utils.py index 7856668c3..7e7617e8e 100644 --- a/compas_python_utils/debugging_utils.py +++ b/compas_python_utils/debugging_utils.py @@ -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 diff --git a/compas_python_utils/detailed_evolution_plotter/plot_detailed_evolution.py b/compas_python_utils/detailed_evolution_plotter/plot_detailed_evolution.py index 27a94ed75..c52a877e0 100644 --- a/compas_python_utils/detailed_evolution_plotter/plot_detailed_evolution.py +++ b/compas_python_utils/detailed_evolution_plotter/plot_detailed_evolution.py @@ -214,16 +214,16 @@ def plotStellarTypeAttributesAndEccentricity(ax=None, Data=None, mask=None, use_ ### Plot stellar types stellarTypes, useTypes, typeNameMap = getStellarTypes(Data) - handle1 = ax1.plot(Data['Time'][()][mask], typeNameMap(Data['Stellar_Type(1)'][()][mask]), linestyle='-', c='r', + ax1.plot(Data['Time'][()][mask], typeNameMap(Data['Stellar_Type(1)'][()][mask]), linestyle='-', c='r', label='Stellar Type 1') - handle2 = ax1.plot(Data['Time'][()][mask], typeNameMap(Data['Stellar_Type(2)'][()][mask]), linestyle='-', c='b', + ax1.plot(Data['Time'][()][mask], typeNameMap(Data['Stellar_Type(2)'][()][mask]), linestyle='-', c='b', label='Stellar Type 2') ax1.set_ylabel('Stellar Type') ax1.set_yticks(range(useTypes.shape[0])) ax1.set_yticklabels([stellarTypes[typeNum] for typeNum in useTypes]) ### Plot eccentricity - handle3 = ax2.plot(Data['Time'][()][mask], Data['Eccentricity'][()][mask] - .01, linestyle='-', c='k', + ax2.plot(Data['Time'][()][mask], Data['Eccentricity'][()][mask] - .01, linestyle='-', c='k', label='Eccentricity') # the minor subtraction makes the curve easier to find ax2.set_ylabel('Eccentricity', labelpad=10) ax2.set_yticks([0, .25, .5, .75, 1.0]) @@ -272,7 +272,7 @@ def plotHertzsprungRussell(ax=None, Data=None, events=None, mask=None, use_latex # Add lines of const radii for R in np.logspace(-9, 5, 15): - exp = "{:.1e}".format(R) + exp = f"{R:.1e}" exp = exp[-3] + exp[-1] T_K = np.logspace(3, 7, 41) # in K T = T_K / 6e3 # Tsol=6e3K @@ -297,9 +297,9 @@ def get_L(t): # assumes K Lrgt = get_L(Trgt / 6e3) alpha = 0.4 if use_latex: - str = r"$10^{{{exp}}}\,R_\odot$".format(exp=exp) + str = rf"$10^{{{exp}}}\,R_\odot$" else: - str = "10^{exp} Rsun".format(exp=exp) + str = f"10^{exp} Rsun" if (Tbot > Trgt) and (Tbot < xlim[1]): ax.text(x=Tbot, y=Lbot, s=str, alpha=alpha) elif (Lrgt > Lbot) and (Lrgt < ylim[1]): @@ -435,7 +435,7 @@ def space_out(original_vals, min_separation=None): ########################################################### -class Event(object): +class Event: def __init__(self, Data, index, eventClass, stellarTypeMap, use_latex=True, **kwargs): @@ -480,7 +480,7 @@ def getEventDetails(self, use_latex=True, **kwargs): image_num = None if eventClass == 'Beg': - eventString = r'Zero-age main-sequence, metallicity Z={:5.4f}'.format(self.Z1) + eventString = rf'Zero-age main-sequence, metallicity Z={self.Z1:5.4f}' image_num = 2 elif eventClass == 'MT': @@ -521,19 +521,19 @@ def getEventDetails(self, use_latex=True, **kwargs): elif mtValue == 6: self.eventClass = 'End' self.endState = 'Merger' - eventString = r'Stellar Merger: {}+{}'.format(self.stypeName1, self.stypeName2) + eventString = rf'Stellar Merger: {self.stypeName1}+{self.stypeName2}' image_num = 37 else: - raise ValueError("Unknown MT: {}".format(mtValue)) + raise ValueError(f"Unknown MT: {mtValue}") elif eventClass == 'SN': whichStar = kwargs['whichStar'] - remType = Data['Stellar_Type({})'.format(whichStar)][ii] + remType = Data[f'Stellar_Type({whichStar})'][ii] remnantTypeName = self.stellarTypeMap[remType] - compType = Data['Stellar_Type({})'.format(2 if whichStar == 1 else 1)][ii] + compType = Data[f'Stellar_Type({2 if whichStar == 1 else 1})'][ii] disrupted = (Data['Eccentricity'][ii] > 1 or Data['SemiMajorAxis'][ii] < 0) status = '. Orbit becomes unbound' if disrupted else '' - eventString = r'Star {} undergoes supernova and forms a {}{}'.format(whichStar, remnantTypeName, status) + eventString = rf'Star {whichStar} undergoes supernova and forms a {remnantTypeName}{status}' if disrupted: if compType < 13: # normal companion if remType == 13: # with NS @@ -562,12 +562,12 @@ def getEventDetails(self, use_latex=True, **kwargs): elif eventClass == 'Stype': whichStar = kwargs['whichStar'] - stypePre = self.stellarTypeMap[Data['Stellar_Type({})'.format(whichStar)][ii - 1]] - stypePost = self.stellarTypeMap[Data['Stellar_Type({})'.format(whichStar)][ii]] + stypePre = self.stellarTypeMap[Data[f'Stellar_Type({whichStar})'][ii - 1]] + stypePost = self.stellarTypeMap[Data[f'Stellar_Type({whichStar})'][ii]] if use_latex: - eventString = r'Star {}: {}-$>${}'.format(whichStar, stypePre, stypePost) + eventString = rf'Star {whichStar}: {stypePre}-$>${stypePost}' else: - eventString = 'Star {}: {}->{}'.format(whichStar, stypePre, stypePost) + eventString = f'Star {whichStar}: {stypePre}->{stypePost}' elif eventClass == 'End': state = kwargs['state'] @@ -588,7 +588,7 @@ def getEventDetails(self, use_latex=True, **kwargs): T0 = a ** 4 / 4 / beta Tdelay = T0 * (1 - e ** 2) ** (7 / 2) * ( 1 + 0.31 * e ** 10 + 0.27 * e ** 20 + 0.2 * e ** 1000) / 3.15e7 / 1e6 - eventString = r'Double compact object ({}+{}) merging in {:.2e} Myr'.format(self.stypeName1, self.stypeName2, Tdelay) + eventString = rf'Double compact object ({self.stypeName1}+{self.stypeName2}) merging in {Tdelay:.2e} Myr' self.time=self.time+Tdelay if (stype1 == 13) and (stype2 == 13): @@ -601,7 +601,7 @@ def getEventDetails(self, use_latex=True, **kwargs): rotate_image = True elif state == "Unbound": - eventString = r'Unbound: {}+{}'.format(self.stypeName1, self.stypeName2) + eventString = rf'Unbound: {self.stypeName1}+{self.stypeName2}' if (stype1 == 13) and (stype2 < 13): image_num = 19 elif (stype1 < 13) and (stype2 == 13): @@ -616,11 +616,11 @@ def getEventDetails(self, use_latex=True, **kwargs): image_num = 23 else: - eventString = r'Evolution ended by run duration: {}+{}'.format(self.stypeName1, self.stypeName2) + eventString = rf'Evolution ended by run duration: {self.stypeName1}+{self.stypeName2}' image_num = 2 else: - raise ValueError("Unknown event class: {}".format(self.eventClass)) + raise ValueError(f"Unknown event class: {self.eventClass}") if image_num != None: self.eventImage = self.getEventImage(image_num, rotate_image) @@ -640,7 +640,7 @@ def getEventImage(self, image_num, rotate_image): return img -class allEvents(object): +class allEvents: def __init__(self, Data): self.Data = Data @@ -743,8 +743,7 @@ def printEvolutionaryHistory(Data=None, events=None): def printFormattedEvolutionLine(time, event, m1, t1, m2, t2, a, e): # All values are floats except event which is a string and t1, t2 which are ints (stellar types) print( - "{:10.6f} {:31} {:7.3f} {:2} {:7.3f} {:2} {:8.3f} {:5.3f}".format(time, event, m1, t1, m2, t2, a, - e)) + f"{time:10.6f} {event:31} {m1:7.3f} {t1:2} {m2:7.3f} {t2:2} {a:8.3f} {e:5.3f}") def safe_save_figure(fig, filename, **kwargs): diff --git a/compas_python_utils/h5sample.py b/compas_python_utils/h5sample.py index 578bf59ab..5889fba1b 100644 --- a/compas_python_utils/h5sample.py +++ b/compas_python_utils/h5sample.py @@ -4,7 +4,7 @@ or upsample a COMPAS h5 file (sample with replacements) to contain a larger set of systems. """ import argparse -from typing import Optional, List +from typing import Optional import sys import h5py @@ -177,7 +177,7 @@ def create_parser() -> argparse.ArgumentParser: return parser -def parse_args(args: List[str]) -> argparse.Namespace: +def parse_args(args: list[str]) -> argparse.Namespace: return create_parser().parse_args(args) diff --git a/compas_python_utils/h5view.py b/compas_python_utils/h5view.py index 2b7eb6a99..6f4642e2e 100644 --- a/compas_python_utils/h5view.py +++ b/compas_python_utils/h5view.py @@ -150,7 +150,7 @@ def printSummary(h5name = None, h5file = None, excludeList = ''): lastModified = datetime.datetime.fromtimestamp(mtime) # ... formatted fileSize = os.path.getsize(h5name) # file size (in bytes) - strFileSize = ('{:<11.4f}').format(fileSize / 1024.0 / 1024.0 / 1024.0) # ... formatted in GB + strFileSize = (f'{fileSize / 1024.0 / 1024.0 / 1024.0:<11.4f}') # ... formatted in GB print('\n\nSummary of HDF5 file', h5name) print('='*(21 + len(h5name))) @@ -223,7 +223,7 @@ def printSummary(h5name = None, h5file = None, excludeList = ''): try: uniqueSeedsStr = str(len(np.unique(h5file[group]['SEED']))) - except Exception as e: + except Exception: uniqueSeedsStr = " " print(('{:<' + str(maxFilenameLen) + '} {:>' + str(max(7, widthColumns)) + '} {:>' + str(max(7, widthEntries)) + '} {:>' + str(max(12, widthEntries)) + '}') diff --git a/compas_python_utils/preprocessing/sampleMoeDiStefano.py b/compas_python_utils/preprocessing/sampleMoeDiStefano.py index caa751884..b83bf65ab 100644 --- a/compas_python_utils/preprocessing/sampleMoeDiStefano.py +++ b/compas_python_utils/preprocessing/sampleMoeDiStefano.py @@ -509,7 +509,7 @@ def createParameterGridfile(gridname, nSamples, m1Min=5, m1Max=100, testing=Fals continue # don't include in overall count nEntries += 1 - fwrite.write('--initial-mass-1 {} --initial-mass-2 {} --orbital-period {} --eccentricity {}\n'.format(m1, m2, P, e)) + fwrite.write(f'--initial-mass-1 {m1} --initial-mass-2 {m2} --orbital-period {P} --eccentricity {e}\n') def parse_args(cli_args=[]): default_n = int(1e5) diff --git a/compas_python_utils/preprocessing/stroopwafelInterface.py b/compas_python_utils/preprocessing/stroopwafelInterface.py index c52ce4d78..7db4f2e21 100644 --- a/compas_python_utils/preprocessing/stroopwafelInterface.py +++ b/compas_python_utils/preprocessing/stroopwafelInterface.py @@ -146,7 +146,7 @@ def interesting_systems(batch): if sample.properties['SEED'] in interesting_systems_seeds: sample.properties['is_hit'] = 1 return len(dns) - except IOError as error: + except OSError: return 0 def selection_effects(sw): @@ -181,7 +181,6 @@ def rejected_systems(locations, dimensions): num_rejected (int): number of systems which can be rejected """ m1 = dimensions[0] - q = dimensions[1] a = dimensions[2] mass_1 = [location.dimensions[m1] for location in locations] mass_2 = [location.properties['Mass_2'] for location in locations] @@ -252,7 +251,6 @@ def main(): except: print("Invalid runSubmit + compas ConfigDefault.yaml file, using default stroopwafel options") - userunSubmit = False print("Output folder is: ", output_folder) if os.path.exists(output_folder): @@ -285,7 +283,8 @@ def main(): only_hits=False) # Run it to create weights, if you want only hits in the output, then make only_hits = True end_time = time.time() - print("Total running time = %d seconds" % (end_time - start_time)) + elapsed_time = end_time - start_time + print (f"Total running time = {elapsed_time:.0f} seconds") if __name__ == '__main__': diff --git a/misc/examples/Tutorials/DataAnalysis.py b/misc/examples/Tutorials/DataAnalysis.py index 09c64ad64..4f428fd56 100644 --- a/misc/examples/Tutorials/DataAnalysis.py +++ b/misc/examples/Tutorials/DataAnalysis.py @@ -205,7 +205,7 @@ def calculateTotalMassesNaive(pathData=None): end = time.time() timeDiffNaive = end-start -print('%s seconds, using for loops.' %(timeDiffNaive)) +print(f'{timeDiffNaive} seconds, using for loops.') # - # # Optimizing the above loop @@ -273,7 +273,7 @@ def calculateTotalMassesNaive(pathData=None): print(seedsDC) print(seedsSP[mask]) print(m1Zams[mask]) -print("The occurrence rate of DCOs is {}/{}".format(sum(mask), len(mask))) +print(f"The occurrence rate of DCOs is {sum(mask)}/{len(mask)}") # - printCompasDetails(DCs, [1636090389, 1636091089, 1636091116]) @@ -283,8 +283,6 @@ def calculateTotalMassesNaive(pathData=None): def calculateTotalMassesOptimized(pathData=None): Data = h5.File(pathToData) - - totalMasses = [] # Retrieve the categories SPs = Data['BSE_System_Parameters'] @@ -317,9 +315,9 @@ def calculateTotalMassesOptimized(pathData=None): nrDCOs = len(seedsDC) print('Compare') -print('%s seconds, using For Loops.' %(timeDiffNaive)) -print('%s seconds, using Optimizations.' %(timeDiffOptimized)) -print('Using %s DCO systems' %(nrDCOs)) +print(f'{timeDiffNaive} seconds, using For Loops.') +print(f'{timeDiffOptimized} seconds, using Optimizations.') +print(f'Using {nrDCOs} DCO systems') # - # *Note:* The time difference will depend heavily on the number of systems under investigation, as well as the number of bypassed For Loops. If you used the path to the pre-generated tutorial data set (with few, intentionally specified systems), you should see very little improvement. @@ -335,8 +333,6 @@ def calculateTotalMassesOptimized(pathData=None): def calculateTotalMassesDNS(pathToData=None): Data = h5.File(pathToData) - totalMasses = [] - SPs = Data['BSE_System_Parameters'] DCs = Data['BSE_Double_Compact_Objects'] @@ -371,7 +367,7 @@ def calculateTotalMassesDNS(pathToData=None): # calculate number of DNS systems nrDNSs = len(mTotDNS) -print('%s seconds for all %s DNS systems.' %(timeDiffDNS, nrDNSs)) +print(f'{timeDiffDNS} seconds for all {nrDNSs} DNS systems.') # - # The `printCompasDetails` function can also optionally take a mask as argument. This is especially useful for those output categories which have multiple events for a single seed. Using both seeds and mask inputs can help to extract a specific type of event from several for the given seeds. diff --git a/misc/examples/methods_paper_plots/fig_16_Chirpmass_distribution/Fig16_pythonSubmit.py b/misc/examples/methods_paper_plots/fig_16_Chirpmass_distribution/Fig16_pythonSubmit.py index fa5c40100..2f009998a 100644 --- a/misc/examples/methods_paper_plots/fig_16_Chirpmass_distribution/Fig16_pythonSubmit.py +++ b/misc/examples/methods_paper_plots/fig_16_Chirpmass_distribution/Fig16_pythonSubmit.py @@ -766,7 +766,7 @@ def cleanStringParameter(str_param): # escape any unescaped spaces or quotes within the string escapes = [" ", "'", "\""] for escape in escapes: - str_param = re.sub(r"(?= 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: @@ -483,7 +483,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' @@ -569,11 +569,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}') @@ -593,12 +593,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 Double_Compact_Objects[COMPAS.DCOmask] , len(redshifts) - DCO = h_new['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' @@ -608,7 +604,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() @@ -676,14 +672,14 @@ 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( './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') + plt.savefig( './Rate_Info'+f"mu0{mu0}_muz{muz}_alpha{alpha}_sigma0{sigma0}_sigmaz{sigmaz}"+'.png', bbox_inches='tight') if show_plot: plt.show() else: diff --git a/online-docs/pages/User guide/Post-processing/CHE_paper_tutorial/old_selection_effects.py b/online-docs/pages/User guide/Post-processing/CHE_paper_tutorial/old_selection_effects.py index 9e2cfc6b7..3f97cd0bd 100644 --- a/online-docs/pages/User guide/Post-processing/CHE_paper_tutorial/old_selection_effects.py +++ b/online-docs/pages/User guide/Post-processing/CHE_paper_tutorial/old_selection_effects.py @@ -1,12 +1,10 @@ # ! /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 @@ -145,11 +143,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 @@ -164,7 +162,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): """ diff --git a/online-docs/pages/User guide/Post-processing/CHE_paper_tutorial/old_totalMassEvolvedPerZ.py b/online-docs/pages/User guide/Post-processing/CHE_paper_tutorial/old_totalMassEvolvedPerZ.py index fea5476c4..94ef580cb 100644 --- a/online-docs/pages/User guide/Post-processing/CHE_paper_tutorial/old_totalMassEvolvedPerZ.py +++ b/online-docs/pages/User guide/Post-processing/CHE_paper_tutorial/old_totalMassEvolvedPerZ.py @@ -35,17 +35,17 @@ def CDFbrokenPowerLaw(x, x1, x2, x3, x4, a1, a2, a3, C1): bottom = N1+N2+N3 mask1 = (x>=x1) & (x=x2) & (x=x3) & (x<=x4) - top3 = N1 + N2 + (((1./(a3+1)) * C3 * (x[mask3]**(a3+1)) - (1./(a3+1)) * C3 * (x3**(a3+1)))) + top3 = N1 + N2 + ((1./(a3+1)) * C3 * (x[mask3]**(a3+1)) - (1./(a3+1)) * C3 * (x3**(a3+1))) yvalues[mask3] = top3/bottom return yvalues @@ -61,8 +61,6 @@ def invertCDFbrokenPowerLaw(CDF, x1, x2, x3, x4, a1, a2, a3, C1): N2 = float(((1./(a2+1)) * C2 * (x3**(a2+1))) - ((1./(a2+1)) * C2 * (x2**(a2+1)))) N3 = float(((1./(a3+1)) * C3 * (x4**(a3+1))) - ((1./(a3+1)) * C3 * (x3**(a3+1)))) - bottom = N1+N2+N3 - CDFx2 = CDFbrokenPowerLaw(np.array([x2,x2]), x1, x2, x3, x4, a1, a2, a3, C1)[0] CDFx3 = CDFbrokenPowerLaw(np.array([x3,x3]), x1, x2, x3, x4, a1, a2, a3, C1)[0] @@ -132,7 +130,6 @@ def createSampleUniverse(binaryFraction=1., x1=0.01, x2=0.08, x3=0.5, x4=200, a1 def inverseCDF(C, CDF, index, xmin, xmax): #CDF sincle powerlaw - a = (1./(index + 1)) * C * CDF**(index+1) b = (1./(index + 1)) * C * xmin**(index+1) c = (1./(index + 1)) * C * xmax**(index+1) top = ((CDF * (c-b))+b)*(index + 1) diff --git a/online-docs/pages/User guide/Post-processing/notebooks/DataAnalysis.ipynb b/online-docs/pages/User guide/Post-processing/notebooks/DataAnalysis.ipynb index 00a7a1284..529b258b6 100644 --- a/online-docs/pages/User guide/Post-processing/notebooks/DataAnalysis.ipynb +++ b/online-docs/pages/User guide/Post-processing/notebooks/DataAnalysis.ipynb @@ -8033,7 +8033,7 @@ "end = time.time()\n", "time_diff_naive = end-start\n", "\n", - "print('%s seconds, using for loops.' %(time_diff_naive)) " + "print(f'{time_diff_naive} seconds, using for loops.') " ] }, { @@ -8179,7 +8179,7 @@ "# - see numpy.isin documentation for details\n", "mask = np.isin(seeds_SP, seeds_DC)\n", "\n", - "print(\"The occurrence rate of DCOs is {}/{}\".format(sum(mask), len(mask)))" + "print(f\"The occurrence rate of DCOs is {sum(mask)}/{len(mask)}\")" ] }, { @@ -8348,7 +8348,6 @@ "def calculate_total_masses_optimized(path_data=None):\n", " data = h5.File(path_to_data)\n", " \n", - " total_masses = []\n", " \n", " # Retrieve the categories\n", " SPs = data['BSE_System_Parameters']\n", @@ -8398,9 +8397,9 @@ "n_DCos = len(seeds_DC)\n", "\n", "print('Compare')\n", - "print('%s seconds, using For Loops.' %(time_diff_naive)) \n", - "print('%s seconds, using Optimizations.' %(time_diff_optimized)) \n", - "print('Using %s DCO systems' %(n_DCos))" + "print(f'{time_diff_naive} seconds, using For Loops.') \n", + "print(f'{time_diff_optimized} seconds, using Optimizations.') \n", + "print(f'Using {n_DCos} DCO systems')" ] }, { @@ -8450,7 +8449,6 @@ "def calculate_total_masses_bbh(path_to_data=None):\n", " data = h5.File(path_to_data)\n", " \n", - " total_masses = []\n", " \n", " SPs = data['BSE_System_Parameters']\n", " DCs = data['BSE_Double_Compact_Objects']\n", @@ -8500,7 +8498,7 @@ "# calculate number of BBH systems\n", "n_bbh = len(m_tot_bbh)\n", " \n", - "print('%s seconds for all %s BBH systems.' %(time_diff_bbh, n_bbh)) " + "print(f'{time_diff_bbh} seconds for all {n_bbh} BBH systems.') " ] }, { diff --git a/online-docs/pages/User guide/Post-processing/notebooks/DataAnalysis.py b/online-docs/pages/User guide/Post-processing/notebooks/DataAnalysis.py index 15bd6a4da..25f7dbd5b 100644 --- a/online-docs/pages/User guide/Post-processing/notebooks/DataAnalysis.py +++ b/online-docs/pages/User guide/Post-processing/notebooks/DataAnalysis.py @@ -227,7 +227,7 @@ def calculate_total_masses_naive(path_data=None): end = time.time() time_diff_naive = end-start -print('%s seconds, using for loops.' %(time_diff_naive)) +print(f'{time_diff_naive} seconds, using for loops.') # %% [markdown] # ### I) Optimizing the above loop @@ -297,7 +297,7 @@ def calculate_total_masses_naive(path_data=None): # - see numpy.isin documentation for details mask = np.isin(seeds_SP, seeds_DC) -print("The occurrence rate of DCOs is {}/{}".format(sum(mask), len(mask))) +print(f"The occurrence rate of DCOs is {sum(mask)}/{len(mask)}") # %% seeds_DC = DCs['SEED'][()] @@ -311,8 +311,6 @@ def calculate_total_masses_naive(path_data=None): # %% def calculate_total_masses_optimized(path_data=None): data = h5.File(path_to_data) - - total_masses = [] # Retrieve the categories SPs = data['BSE_System_Parameters'] @@ -345,9 +343,9 @@ def calculate_total_masses_optimized(path_data=None): n_DCos = len(seeds_DC) print('Compare') -print('%s seconds, using For Loops.' %(time_diff_naive)) -print('%s seconds, using Optimizations.' %(time_diff_optimized)) -print('Using %s DCO systems' %(n_DCos)) +print(f'{time_diff_naive} seconds, using For Loops.') +print(f'{time_diff_optimized} seconds, using Optimizations.') +print(f'Using {n_DCos} DCO systems') # %% [markdown] # *Note:* The time difference will depend heavily on the number of systems under investigation, as well as the number of bypassed For Loops. If you used the path to the pre-generated tutorial data set, you should see very little improvement. @@ -366,8 +364,6 @@ def calculate_total_masses_optimized(path_data=None): def calculate_total_masses_bbh(path_to_data=None): data = h5.File(path_to_data) - total_masses = [] - SPs = data['BSE_System_Parameters'] DCs = data['BSE_Double_Compact_Objects'] @@ -402,7 +398,7 @@ def calculate_total_masses_bbh(path_to_data=None): # calculate number of BBH systems n_bbh = len(m_tot_bbh) -print('%s seconds for all %s BBH systems.' %(time_diff_bbh, n_bbh)) +print(f'{time_diff_bbh} seconds for all {n_bbh} BBH systems.') # %% [markdown] # Note that the `print_compas_details_dataframe` function can also optionally take a mask as argument. The mask array must have the same length as the data arrays for the given category. diff --git a/online-docs/pages/User guide/Post-processing/notebooks/spin_prescriptions/spin_class.py b/online-docs/pages/User guide/Post-processing/notebooks/spin_prescriptions/spin_class.py index bbb57cfc8..6cbea7597 100644 --- a/online-docs/pages/User guide/Post-processing/notebooks/spin_prescriptions/spin_class.py +++ b/online-docs/pages/User guide/Post-processing/notebooks/spin_prescriptions/spin_class.py @@ -6,7 +6,7 @@ -class calculate_spin(object): +class calculate_spin: """ This class calculates the Black Hole (BH) or Neutron Star (NS) spin based on a given spin prescription It returns the spin of the compact object M1, and compact object M2 @@ -20,7 +20,7 @@ def __init__(self, data_path=None, spin_model_name='uniform'): if (self.path is None): print("Warning: your hdf5 path is set to 'None'") elif not os.path.isfile(data_path): - raise ValueError("h5 file not found. Wrong path given?", "path given = %s"%data_path) + raise ValueError("h5 file not found. Wrong path given?", f"path given = {data_path}") elif os.path.isfile(data_path): self.h5file = h5.File(data_path) @@ -350,7 +350,7 @@ def MESA(self): -class calculate_spin_olderCOMPASdata(object): +class calculate_spin_olderCOMPASdata: """ This class calculates the Black Hole (BH) or Neutron Star (NS) spin based on a given spin prescription It returns the spin of the compact object M1, and compact object M2 @@ -364,7 +364,7 @@ def __init__(self, data_path=None, spin_model_name='uniform'): if (self.path is None): print("Warning: your hdf5 path is set to 'None'") elif not os.path.isfile(data_path): - raise ValueError("h5 file not found. Wrong path given?", "path given = %s"%data_path) + raise ValueError("h5 file not found. Wrong path given?", f"path given = {data_path}") elif os.path.isfile(data_path): self.h5file = h5.File(data_path) @@ -431,8 +431,6 @@ def setCOMPASData(self): self.M1formedSecond = (whichSN2==1) # mask that is 1 if the compact object M1 formed first in the DCO # did M2 form in the first SN? self.M2formedSecond = (whichSN2==2) # mask that is 1 if the compact object M2 formed first in the DCO - mask_SN1not1or2 = (whichSN2!=1) & (whichSN2!=2) - self.mWR = fSN['MassStarSN'][...].squeeze()[maskSNdco][1::2] # obtain the CO core mass before the SNe diff --git a/py_tests/conftest.py b/py_tests/conftest.py index f7e5f01c5..432aa0001 100644 --- a/py_tests/conftest.py +++ b/py_tests/conftest.py @@ -1,5 +1,5 @@ import os -from typing import Any, Dict +from typing import Any import subprocess import h5py @@ -46,7 +46,7 @@ def test_archive_dir(): return TEST_ARCHIVE_DIR -def get_compas_data(path: str) -> Dict[str, Any]: +def get_compas_data(path: str) -> dict[str, Any]: """Reads in a COMPAS h5 file and returns a dict with some data from the file.""" data = {} with h5py.File(path, "r") as f: diff --git a/py_tests/test_example_notebooks.py b/py_tests/test_example_notebooks.py index 1d8b872ef..212ffbdf8 100644 --- a/py_tests/test_example_notebooks.py +++ b/py_tests/test_example_notebooks.py @@ -53,6 +53,6 @@ def __execute_ipynb(notebook_filename: str, execute_dir: str = None) -> bool: ) success = False finally: - with open(notebook_filename, mode="wt") as f: + with open(notebook_filename, mode="w") as f: nbformat.write(notebook, f) return success diff --git a/py_tests/test_run_submit.py b/py_tests/test_run_submit.py index e19e4f9b0..1101b38fd 100644 --- a/py_tests/test_run_submit.py +++ b/py_tests/test_run_submit.py @@ -1,5 +1,3 @@ -from typing import List - from yaml.scanner import ScannerError from compas_python_utils.preprocessing.runSubmit import ( @@ -28,7 +26,7 @@ def _make_tmp_ini(tmp_path) -> str: Make a temporary ini file for testing uncomment all default options to ensure they can be parsed """ - with open(DEFAULT_CONFIG_FILE, "r") as f: + with open(DEFAULT_CONFIG_FILE) as f: lines = f.read() lines = lines.replace("\n#", "\n") ini = f"{tmp_path}/test.ini" @@ -37,7 +35,7 @@ def _make_tmp_ini(tmp_path) -> str: return ini, lines -def _check_if_expected_kwgs_in_stdout(capsys, expected_kwgs: List[str]): +def _check_if_expected_kwgs_in_stdout(capsys, expected_kwgs: list[str]): """Check that all expected_kwgs are in stdout""" stdout = capsys.readouterr().out for expected_kwarg in expected_kwgs: diff --git a/ruff.toml b/ruff.toml index 605e0fee0..42f649edc 100644 --- a/ruff.toml +++ b/ruff.toml @@ -5,4 +5,9 @@ target-version = "py39" select = [ # https://docs.astral.sh/ruff/rules/unused-import/ "F401", + # https://docs.astral.sh/ruff/rules/unused-variable/ + "F841", + # https://docs.astral.sh/ruff/rules/#pyupgrade-up + # https://github.com/asottile/pyupgrade + "UP", ] diff --git a/setup.py b/setup.py index 928f0df5d..5522255f3 100644 --- a/setup.py +++ b/setup.py @@ -108,11 +108,11 @@ def read(*parts): def find_meta(meta, meta_file=read(META_PATH)): meta_match = re.search( - r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), meta_file, re.M + rf"^__{meta}__ = ['\"]([^'\"]*)['\"]", meta_file, re.M ) if meta_match: return meta_match.group(1) - raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta)) + raise RuntimeError(f"Unable to find __{meta}__ string.") def find_version(version_file=read(CPP_VERSION_FILE)):