posydon.popsyn
posydon.popsyn.GRB
posydon.popsyn.analysis
Module for analyzing binary population simulation results.
- posydon.popsyn.analysis.get_subsets(path, find_n=None, select_oneline=None, select_history=None, select_columns=None, verbose=True)[source]
Get the oneline and history subsets for a selection of binaries.
You select binaries from an HDF5 population by providing a function that operates either on oneline or history and returns a boolean mask in- dicating which rows correspond to the binaries of interest. E.g.,
- def find_no_end(df):
return df[“event_f”] != “END”
can be used to find binaries that ended abruptly, based on the information in the oneline table. Therefore, we set select_oneline=find_no_end. If no selector has been set, all binaries are selected (combine this with the select_columns argument to get a column subset of the data.)
- Parameters:
path (str) – The fullpath of the HDF5 file.
find_n (int or None) – The number of binaries to select (at most) or None to select all.
select_oneline (function or None) – The function to operate on chunks of the oneline table.
select_history (function or None) – The function to operate on chunks of the oneline table.
select_columns (None or str or array) – If None, all columns will be returned. If a string, only those columns with name containing this string will be returned. An array of strings can be used for multiple such patterns.
- Returns:
The subsets of the dataframes with the data for the selected binaries.
- Return type:
oneline, history
posydon.popsyn.binarypopulation
Create, evolve and save a binary star population.
Large populations are RAM limited when holding an arbitrary number of BinaryStar instances. Therefore, by default the BinaryPopulation will generate binaries, evolve, and try to save them to disk one at a time.
Create a BinaryPopulation instance from an inifile: I. CREATING A POPULATION ———————— a) One-liner for creating a BinaryPopulation from an inifile:
> BinaryPopulation.from_ini(‘<PATH_TO_POSYDON>’ ‘/posydon/popsyn/population_params_default.ini’)
- class posydon.popsyn.binarypopulation.BinaryGenerator(sampler=generate_independent_samples, RNG=None, **kwargs)[source]
Bases:
object
Generate binaries to be included in a BinaryPopulation.
Initialize the BinaryGenerator instance.
- draw_initial_binary(**kwargs)[source]
Return a binary for evolution in a population.
- Parameters:
index (int) – Sets binary index. Defaults to number of generated binaries.
- Returns:
binary
- Return type:
- class posydon.popsyn.binarypopulation.BinaryPopulation(**kwargs)[source]
Bases:
object
Handle a binary star population.
Initialize the binary population object.
- Parameters:
number_of_binaries (int) – Size of the population
population_properties (SimulationProperties) – Instance of simulationproperties holding steps.
- combine_saved_files(absolute_filepath, file_names, **kwargs)[source]
Combine various temporary files in a given folder.
- evolve(**kwargs)[source]
Evolve a binary population.
- Parameters:
indices (list, optional) – Custom binary indices to use. Default is range(number_of_binaries). If running with MPI, indices are split between processes if given.
breakdown_to_df (bool, True) – Breakdown a binary after evolution, converting to dataframe and removing the binary instance from memory.
tqdm (bool, False) – Show tqdm progress bar during evolution.
- Return type:
None
- class posydon.popsyn.binarypopulation.PopulationManager(file_name=None, **kwargs)[source]
Bases:
object
Manage a population of binaries.
Initialize a PopulationManager instance.
- breakdown_to_df(binary, **kwargs)[source]
Breakdown to a pandas DataFrame.
Breakdown a binary into more convenient data type, store it, and remove the BinaryStar instance from self.
- from_hdf(indices=None, where=None, restore=False)[source]
Load a BinaryStar instance from an hdf file of a saved population.
- generate(**kwargs)[source]
Generate a binary by drawing from the binary_generator.
This can be a callable or a generator.
- save(fname, **kwargs)[source]
Save binaries to an hdf file using pandas HDFStore.
Any object dtype columns not parsed by infer_objects() is converted to a string.
- Parameters:
fname (str) – Name of hdf file saved.
mode ({'a', 'w', 'r', 'r+'}, default 'a') – See pandas HDFStore docs
complib ({'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib') – Compression library. See HDFStore docs
complevel (int, 0-9, default 9) – Level of compression. See HDFStore docs
kwargs (dict) – Arguments for BinaryStar methods to_df and to_oneline_df.
- Return type:
None
posydon.popsyn.defaults
Default binary population parameters.
posydon.popsyn.independent_sample
Generate the initial parameters for a binary population.
- posydon.popsyn.independent_sample.binary_fraction_value(binary_fraction_const=1, binary_fraction_scheme='const', m1=None, **kwargs)[source]
Getting the binary fraction depending on the scheme. The two possible option are a constant binary fraction and a binary fraction based on the values given in Moe and Di Stefano (2017).
- posydon.popsyn.independent_sample.generate_eccentricities(number_of_binaries=1, eccentricity_scheme='thermal', **kwargs)[source]
Generate random eccentricities.
Use the scheme defined in this particular instance of BinaryPopulation.
- Parameters:
number_of_binaries (int) – Number of binaries that require randomly sampled orbital separations
eccentricity_scheme (string) – Distribution from which eccentricities are randomly drawn
**kwargs (dictionary) – kwargs from BinaryPopulation class
- Returns:
eccentricities – Randomly drawn eccentricities
- Return type:
ndarray of floats
- posydon.popsyn.independent_sample.generate_independent_samples(orbital_scheme='period', **kwargs)[source]
Randomly generate a population of binaries at ZAMS.
- Parameters:
orbital_scheme (str (default: 'period')) – The scheme to use to get either orbital periods or separations
**kwargs (dictionary) – kwargs from BinaryPopulation class
- Returns:
orbital_scheme_set (ndarray of floats) – Randomly drawn orbital separations/periods depending on the scheme
eccentricity_set (ndarray of floats) – Randomly drawn eccentricities
m1_set (ndarray of floats) – Randomly drawn primary masses
m2_set (ndarray of floats) – Randomly drawn secondary masses
- posydon.popsyn.independent_sample.generate_orbital_periods(primary_masses, number_of_binaries=1, orbital_period_min=0.35, orbital_period_max=10**3.5, orbital_period_scheme='Sana+12_period_extended', **kwargs)[source]
Randomaly generate orbital periods for a sample of binaries.
- posydon.popsyn.independent_sample.generate_orbital_separations(number_of_binaries=1, orbital_separation_min=5, orbital_separation_max=1e5, log_orbital_separation_mean=None, log_orbital_separation_sigma=None, orbital_separation_scheme='log_uniform', **kwargs)[source]
Generate random orbital separations.
Use the scheme defined in this particular instance of BinaryPopulation.
- Parameters:
number_of_binaries (int) – Number of binaries that require randomly sampled orbital separations
orbital_separation_min (float) – Minimum orbital separation in solar radii
orbital_separation_max (float) – Maximum orbital separation in solar radii
log_orbital_separation_mean (float) – Mean of the lognormal distribution.
log_orbital_separation_sigma (float) – Standard deviation of the lorgnormal distribution.
orbital_separation_scheme (string) – Distribution from which the orbital separations are randomly drawn
- Returns:
orbital_separations – Randomly drawn orbital separations
- Return type:
ndarray of floats
- posydon.popsyn.independent_sample.generate_primary_masses(number_of_binaries=1, primary_mass_min=7, primary_mass_max=120, primary_mass_scheme='Salpeter', **kwargs)[source]
Generate random primary masses.
Use the scheme defined in this particular instance of BinaryPopulation.
- Parameters:
- Returns:
primary_masses – Randomly drawn primary masses
- Return type:
ndarray of floats
- posydon.popsyn.independent_sample.generate_secondary_masses(primary_masses, number_of_binaries=1, secondary_mass_min=0.35, secondary_mass_max=120, secondary_mass_scheme='flat_mass_ratio', **kwargs)[source]
Generate random secondary masses.
Use the scheme defined in this particular instance of BinaryPopulation.
- Parameters:
primary_masses (ndarray of floats) – Previously drawn primary masses
number_of_binaries (int) – Number of binaries that require randomly sampled orbital separations
secondary_mass_min (float) – Minimum secondary mass
secondary_mass_max (float) – Maximum secondary mass
secondary_mass_scheme (string) – Distribution from which the secondary masses are randomly drawn
- Returns:
secondary_masses – Randomly drawn secondary masses
- Return type:
ndarray of floats
posydon.popsyn.io
Handle I/O operations for the population synthesis code.
- posydon.popsyn.io.binarypop_kwargs_from_ini(path, verbose=False)[source]
Convert an inifile into kwargs for the BinaryPopulation class.
- posydon.popsyn.io.clean_binary_history_df(binary_df, extra_binary_dtypes_user=None, extra_S1_dtypes_user=None, extra_S2_dtypes_user=None)[source]
Take a posydon binary history DataFrame from the BinaryStar.to_df method and clean the data for saving by setting Data Types of the columns explicitly.
- Parameters:
binary_df (DataFrame) – A pandas Dataframe containing binary history
extra_binary_dtypes_user (dict, optional) – A dictionary with extra column names as keys, and their associated data types as values.
extra_S1_dtypes_user (dict, optional) – Same as above, but only for star 1.
extra_S2_dtypes_user (dict, optional) – Same as above, but only for star 2.
- Returns:
binary_df – A cleaned binary history ready for saving to HDF.
- Return type:
DataFrame
- posydon.popsyn.io.clean_binary_oneline_df(oneline_df, extra_binary_dtypes_user=None, extra_S1_dtypes_user=None, extra_S2_dtypes_user=None)[source]
Take a posydon binary oneline DataFrame from the BinaryStar.to_oneline_df method and clean the data for saving by setting Data Types of the columns explicitly.
This method is similar to clean_binary_history_df since they have many overalapping columns, with a few extras and different naming.
Note: there may be edge cases not handed if new scalar_names are added.
- Parameters:
binary_df (DataFrame) – A pandas Dataframe containing binary history
extra_binary_dtypes_user (dict, optional) – A dictionary with extra column names as keys, and their associated data types as values.
extra_S1_dtypes_user (dict, optional) – Same as above, but only for star 1.
extra_S2_dtypes_user (dict, optional) – Same as above, but only for star 2.
- Returns:
binary_df – A cleaned binary history ready for saving to HDF.
- Return type:
DataFrame
- posydon.popsyn.io.parse_inifile(path, verbose=False)[source]
Parse an inifile for evolving binary populations.
posydon.popsyn.normalized_pop_mass
Compute the underlying stellar population mass for a given simulation.
- posydon.popsyn.normalized_pop_mass.initial_total_underlying_mass(simulated_mass=None, simulated_mass_single=None, simulated_mass_binaries=None, f_bin=0.7, **kwargs)[source]
Compute the initial total mass of the population.
- Parameters:
- simulated_mass, simulated_mass_single, simulated_mass_binariesfloat
Total simulated mass, simulated mass of binary systems and simulated mass of single stars, respectively.
- f_bin: float
The binary fraction of your population in “nature”. If not provided, the default value is set to 0.7
- primary_mass_min: float
minimum initial mass of the primary star
- primary_mass_max: float
maximum initial mass of the primary star
- binary_fraction_const: float
Binary fraction used in the simulations
- primary_mass_scheme: string
Kroupa2001 or Salpeter options
- secondary_mass_scheme: string
mass ratio distribution
- ———-
- :returns: * **underlying_total_mass (float) – The underlying total mass of the population: float**
f_corr_single_stars, f_corr_binaries; float – Correction factors for singles and binaries, respectively.
posydon.popsyn.rate_calculation
- posydon.popsyn.rate_calculation.get_comoving_distance_from_redshift(z)[source]
Compute the comoving distance from redshift.
- Parameters:
z (double) – Cosmological redshift.
- Returns:
Comoving distance in Mpc corresponding to the redhisft z.
- Return type:
double
- posydon.popsyn.rate_calculation.get_cosmic_time_from_redshift(z)[source]
Compute the cosmic time from redshift.
- Parameters:
z (double) – Cosmological redshift.
- Returns:
Return age of the cosmic time in Gyr given the redshift z.
- Return type:
double
- posydon.popsyn.rate_calculation.get_redshift_bin_centers(delta_t)[source]
Compute the redshift bin centers.
- Parameters:
delta_t (double) – Time interval in Myr.
- Returns:
Redshift bin centers.
- Return type:
array doubles
- posydon.popsyn.rate_calculation.get_redshift_bin_edges(delta_t)[source]
Compute the redshift bin edges.
- Parameters:
delta_t (double) – Time interval in Myr.
- Returns:
Redshift bin edges.
- Return type:
array doubles
- posydon.popsyn.rate_calculation.get_redshift_from_cosmic_time(t_cosm)[source]
Compute the cosmological redshift given the cosmic time.
- Parameters:
t_cosm (float, ndarray of floats) – Cosmic time(s) for which you want to know the redhisft.
- Returns:
Cosmolgocial redshift(s) corresponding to t_cosm.
- Return type:
ndarray of floats
Note
The function uses the interpolator redshift_from_cosmic_time_interpolator,
which is created each time the function is called. z_at_value from astropy can be used for single values, but it is too slow for arrays.
- posydon.popsyn.rate_calculation.get_shell_comoving_volume(z_hor_i, z_hor_f, sensitivity='infinite')[source]
Compute comoving volume corresponding to a redshift shell.
- Parameters:
z_hor_i (double) – Cosmological redshift. Lower bound of the integration.
z_hor_f (double) – Cosmological redshift. Upper bound of the integration.
sensitivity (string) – hoose which GW detector sensitivity you want to use. At the moment only ‘infinite’ is available, i.e. p_det = 1.
- Returns:
Retruns the comoving volume between the two shells z_hor_i and z_hor_f in Gpc^3.
- Return type:
double
posydon.popsyn.sample_from_file
Get the initial parameters for a binary population.
- posydon.popsyn.sample_from_file.get_kick_samples_from_file(**kwargs)[source]
Read a kicks for population of binaries from a file.
- Parameters:
**kwargs (dictionary) – kwargs from BinaryPopulation class, which should contain read_samples_from_file
- Returns:
s1_natal_kick_array_set (ndarray of floats) – natal kick array for the primary star containing: kick velocity, azimuthal angle, polar angle, mean anomaly
s2_natal_kick_array_set (ndarray of floats) – natal kick array for the secondary star containing: kick velocity, azimuthal angle, polar angle, mean anomaly
- posydon.popsyn.sample_from_file.get_samples_from_file(orbital_scheme='', **kwargs)[source]
Read a population of binaries at ZAMS from a file.
- Parameters:
orbital_scheme (str) – Scheme to get the orbit: ‘separation’, ‘period’
**kwargs (dictionary) – kwargs from BinaryPopulation class, which should contain read_samples_from_file
- Returns:
orbital_scheme_set (ndarray of floats) – orbital separations/periods depending on the scheme
eccentricity_set (ndarray of floats) – eccentricities
m1_set (ndarray of floats) – primary masses
m2_set (ndarray of floats) – secondary masses
posydon.popsyn.selection_effects
Simple utility for generating detection weights
Uses grid of detection probabilities to estimate detection probabilities
Anticipates data as Pandas dataframe with series [‘m1’, ‘q’, ‘z’, ‘chieff’]
- class posydon.popsyn.selection_effects.KNNmodel(grid_path, sensitivity_key, verbose=False)[source]
Bases:
object
K-nearest neighbor model that instantiates based on detection probability grid
When instantiating, must supply path to the grid, and key that represents GW network and sensitivity.
Instantiates KNNmodel class and trains the KNN.
- grid_pathstring
Path to grid of detection probabilities.
- sensitivity_keystring
- GW detector sensitivity and network configuration you want to use,
see arXiv:1304.0670v3
- detector sensitivities are taken from: https://dcc.ligo.org/LIGO-T2000012-v2/public
- available sensitivity keys (for Hanford, Livingston, Virgo network):
‘O3actual_H1L1V1’ : aligo_O3actual_H1.txt, aligo_O3actual_L1.txt, avirgo_O3actual.txt ‘O4low_H1L1V1’ : aligo_O4low.txt, aligo_O4low.txt, avirgo_O4high_NEW.txt ‘O4high_H1L1V1’ : aligo_O4high.txt, aligo_O4high.txt, avirgo_O4high_NEW.txt ‘design_H1L1V1’ : AplusDesign.txt, AplusDesign.txt, avirgo_O5high_NEW.txt
detection probabilities are calculated using the IMRPhenomXHM approximant with a network SNR threshold of 10
- verboseboolean
Adds verbosity.
- predict_pdet(data, verbose=False)[source]
Gives relative weight to each system in data based on its proximity to the points on the grid. Each system in data should have a primary mass m1, mass ratio q, redshift z, and effective spin chieff This function will determine detection probabilities using nearest neighbor algorithm in [log(m1), q, log(z), chieff] space Need to specify bounds (based on the trained grid) so that the grid and data get normalized properly
- dataPandas dataframe
Data you wish to predict detection probabilities for. Required series in the dataframe:
‘m1’ : primary source-frame mass ‘q’ : mass ratio (secondary mass/primary mass) ‘z’ : redshift of merger ‘chieff’ : effective inspiral spin
- verboseboolean
Adds verbosity.
posydon.popsyn.star_formation_history
Implements the selection of different star-formation history scenarios.
- posydon.popsyn.star_formation_history.SFR_Z_fraction_at_given_redshift(z, SFR, sigma, metallicity_bins, Z_max, select_one_met)[source]
‘Fraction of the SFR at a given redshift z in a given metallicity bin as in Eq. (B.8) of Bavera et al. (2020).
- Parameters:
z (np.array) – Cosmological redshift.
SFR (string) – Star formation rate assumption: - Madau+Fragos17 see arXiv:1606.07887 - Madau+Dickinson14 see arXiv:1403.0007 - IllustrisTNG see see arXiv:1707.03395 - Neijssel+19 see arXiv:1906.08136
sigma (double / string) – Standard deviation of the log-metallicity distribution. If string, it can be ‘Bavera+20’ or ‘Neijssel+19’.
metallicity_bins (array) – Metallicity bins edges in absolute metallicity.
Z_max (double) – Maximum metallicity in absolute metallicity.
select_one_met (bool) – If True, the function returns the fraction of the SFR in the given metallicity bin. If False, the function returns the fraction of the SFR in the given metallicity bin and the fraction of the SFR in the metallicity bin
- Returns:
Fraction of the SFR in the given metallicity bin at the given redshift. In absolute metallicity.
- Return type:
array
- posydon.popsyn.star_formation_history.get_formation_times(N_binaries, star_formation='constant', **kwargs)[source]
Get formation times of binaries in a population based on a SFH scenario.
- Parameters:
N_binaries (int) – Number of formation ages to produce.
star_formation (str, {constant, burst}) – Constant - random formation times from a uniform distribution. Burst - all stars are born at the same time.
burst_time (float, 0 (years)) – Sets birth time in years.
min_time (float, 0 (years)) – If constant SF, sets minimum of random sampling.
max_time (float, age_of_universe (years)) – If constant SF, sets maximum of random sampling.
RNG (<class, np.random.Generator>) – Random generator instance.
- Returns:
The formation times array.
- Return type:
array
- posydon.popsyn.star_formation_history.get_illustrisTNG_data(verbose=False)[source]
Load IllustrisTNG SFR dataset.
- posydon.popsyn.star_formation_history.integrated_SFRH_over_redshift(SFR, sigma, Z, Z_max)[source]
Integrated SFR history over z as in Eq. (B.10) of Bavera et al. (2020).
- Parameters:
SFR (string) – Star formation rate assumption: - Madau+Fragos17 see arXiv:1606.07887 - Madau+Dickinson14 see arXiv:1403.0007 - Neijssel+19 see arXiv:1906.08136
Z (double) – Metallicity.
- Returns:
The total mass of stars formed per comoving volume at a given metallicity Z.
- Return type:
double
- posydon.popsyn.star_formation_history.mean_metallicity(SFR, z)[source]
Empiric mean metallicity function.
- Parameters:
SFR (string) – Star formation rate assumption: - Madau+Fragos17 see arXiv:1606.07887 - Madau+Dickinson14 see arXiv:1403.0007 - Neijssel+19 see arXiv:1906.08136
z (double) – Cosmological redshift.
- Returns:
Mean metallicty of the universe at the given redhist.
- Return type:
double
- posydon.popsyn.star_formation_history.star_formation_rate(SFR, z)[source]
Star formation rate in M_sun yr^-1 Mpc^-3.
- Parameters:
SFR (string) – Star formation rate assumption: - Madau+Fragos17 see arXiv:1606.07887 - Madau+Dickinson14 see arXiv:1403.0007 - Neijssel+19 see arXiv:1906.08136 - IllustrisTNG see see arXiv:1707.03395
z (double) – Cosmological redshift.
- Returns:
The total mass of stars in M_sun formed per comoving volume Mpc^-3 per year.
- Return type:
double
posydon.popsyn.synthetic_population
Processing of population files.
This module contains classes and functions to process population files. Population files are HDF5 files containing the history and oneline dataframes of a population of binary systems. The history dataframe contains the detailed evolution of each binary system, while the oneline dataframe contains the final state of each binary system.
Classes
- PopulationRunner
A class to handle the evolution of binary populations.
- Population
A class to handle population files.
- History
A class to handle the history dataframe of a population file.
- Oneline
A class to handle the oneline dataframe of a population file.
- TransientPopulation
A class to handle transient populations.
- Rates
A class to handle the cosmic rates of in a population file.
- class posydon.popsyn.synthetic_population.DFInterface[source]
Bases:
object
A class to handle the interface between the population file and the History and Oneline classes.
- select(key, where=None, start=None, stop=None, columns=None)[source]
Select a subset of the key table based on the given conditions.
- Parameters:
key (str) – The key of the table to select from.
where (str, optional) – A string representing the query condition to apply to the data.
start (int, optional) – The starting index of the data to select.
stop (int, optional) – The ending index of the data to select.
columns (list, optional) – A list of column names to select.
- Returns:
The selected data as a DataFrame.
- Return type:
pandas.DataFrame
- class posydon.popsyn.synthetic_population.History(filename, verbose=False, chunksize=100000)[source]
Bases:
DFInterface
A class to handle the history dataframe of a population file.
This class provides methods to handle the history dataframe of a population file. It allows accessing and manipulating the history table based on various keys and conditions.
- lengths
The number of rows of each binary in the history dataframe.
- Type:
pd.DataFrame
- indices
The binary indices of the history dataframe.
- Type:
np.ndarray
Initialise the history dataframe.
This class is used to handle the history dataframe of a population file. On initialisation, the history_lengths are calculated and stored in the population file, if not present in the file. The history dataframe is not loaded into memory.
- Parameters:
- head(n=10)[source]
Return the first n rows of the history table
- Parameters:
n (int, optional) – The number of rows to return. Default is 10.
- Returns:
The first n rows of the history table.
- Return type:
pandas.DataFrame
- select(where=None, start=None, stop=None, columns=None)[source]
Select a subset of the history table based on the given conditions.
This method allows you to query and retrieve a subset of data from the history table stored in an HDFStore file. You can specify conditions using the where parameter, which is a string representing the query condition to apply to the data. You can also specify the starting and ending indices of the data to select using the start and stop parameters. Additionally, you can choose to select specific columns by providing a list of column names using the columns parameter.
- Parameters:
where (str, optional) – A string representing the query condition to apply to the data. It is only possible to query on the index or string columns.
start (int, optional) – The starting index of the data to select.
stop (int, optional) – The ending index of the data to select.
columns (list, optional) – A list of column names to select.
- Returns:
The selected data as a DataFrame.
- Return type:
pandas.DataFrame
- class posydon.popsyn.synthetic_population.Oneline(filename, verbose=False, chunksize=100000)[source]
Bases:
DFInterface
A class to handle the oneline dataframe of a population file.
The Oneline class provides methods to manipulate and retrieve data from the oneline dataframe of a population file.
- indices
The binary indices of the oneline dataframe.
- Type:
np.ndarray
Initialize a Oneline class instance.
- Parameters:
- head(n=10)[source]
Get the first n rows of the oneline table.
- Parameters:
n (int, optional) – The number of rows to return. Default is 10.
- Returns:
The first n rows of the oneline table.
- Return type:
pd.DataFrame
- select(where=None, start=None, stop=None, columns=None)[source]
Select a subset of the oneline table based on the given conditions.
This method allows you to filter and extract a subset of rows from the oneline table stored in an HDF file. You can specify conditions to filter the rows, define the range of rows to select, and choose specific columns to include in the subset.
- Parameters:
where (str, optional) – A condition to filter the rows of the oneline table. Default is None. It is only possible to query on the index or string columns.
start (int, optional) – The starting index of the subset. Default is None.
stop (int, optional) – The ending index of the subset. Default is None.
columns (list, optional) – The column names to include in the subset. Default is None.
- Returns:
The selected subset of the oneline table.
- Return type:
pd.DataFrame
Examples
# Select rows based on a condition >>> df = Oneline.select(where=”event == ‘ZAMS’”)
# Select rows from index 10 to 20 >>> df = Oneline.select(start=10, stop=20)
# Select specific columns >>> df = Oneline.select(columns=[‘S1_mass_i’, ‘S1_mass_f’])
- class posydon.popsyn.synthetic_population.Population(filename, metallicity=None, ini_file=None, verbose=False, chunksize=1000000)[source]
Bases:
PopulationIO
A class to handle population files.
This class provides methods to handle population files. It includes methods to read and write population files, as well as methods to access and manipulate the history and oneline dataframes.
- formation_channels
The formation channels dataframe of the population.
- Type:
pd.DataFrame
- mass_per_metallicity
The mass per metallicity dataframe of the population.
- Type:
pd.DataFrame
- solar_metallicities
The solar metallicities of the population.
- Type:
np.ndarray
- metallicities
The metallicities of the population.
- Type:
np.ndarray
- indices
The indices of the binaries in the population.
- Type:
np.ndarray
- history_lengths
The number of rows of each binary in the history dataframe. The index is the binary index.
- Type:
pd.DataFrame
Initialize the Population object.
The Population object is initialised by creating History and Oneline objects, which refer back to the population file (filename). The formation channels are also linked to the population file, if present. The mass per metallicity data is loaded from the file, if present, or calculated and saved to the file if not present.
If the mass per metallicity data is not present in the file, you can provide a metallicity and the ini file (used to create the population) to calculate and save the mass per metallicity data. You only need to do this once for a given population file. However, all systems in the population will be given the same metallicity.
- Parameters:
filename (str) – The path to the population file
metallicity (float, optional) – The metallicity of the population in solar units.
ini_file (str, optional) – The path to the ini file used to create the population.
verbose (bool, optional) – If True, print additional information.
chunksize (int, optional) – The chunksize to use when reading the population file.
- Raises:
ValueError – If the provided filename does not contain ‘.h5’ extension. If the population file does not contain a history table. If the population file does not contain an oneline table. If the population file does not contain an ini_parameters table. If the population file does not contain a mass_per_metallicity table and no metallicity for the file was given.
Examples
# When the population file contains a mass_per_metallicity table >>> pop = Population(‘/path/to/population_file.h5’)
# When the population file does not contain a mass_per_metallicity table >>> pop = Population(‘/path/to/population_file.h5’, metallicity=0.02, ini_file=’/path/to/ini_file.ini’)
- calculate_formation_channels(mt_history=False)[source]
Calculate the formation channels of the population.
mt_history is a boolean that determines if the detailed mass-transfer history from the HMS-HMS grid is included in the formation channels.
- Parameters:
mt_history (bool, optional) – If True, include the mass-transfer history in the formation channels. Default is False.
- Raises:
ValueError – If the mt_history_HMS_HMS column is not present in the oneline dataframe.
- calculate_underlying_mass(f_bin=0.7, overwrite=False)[source]
Calculate the underlying mass of the population.
Adds the underlying mass of the population to the mass_per_metallicity table.
This method calculates the underlying mass of the population based on the simulated mass of the population and the boundaries of the sampled mass distribution. You can specify the fraction of binaries in the population using the f_bin parameter.
- property columns
Returns a dictionary containing the column names of the history and oneline dataframes.
- Returns:
A dictionary with keys ‘history’ and ‘oneline’, where the values are the column names of the respective dataframes.
- Return type:
- create_transient_population(func, transient_name, oneline_cols=None, hist_cols=None)[source]
Given a function, create a TransientPopulation
This method creates a transient population using the provided function. func is given the history, oneline, and formation channels dataframes as arguments. The function should return a dataframe containing the transient population, which needs to contain the columns ‘time’ and ‘metallicity’.
Processing is done in chunks to avoid memory issues and a pandas DataFrame is stored at ‘/transients/transient_name’ in the population file.
The creation of the transient population can be sped up by limiting the oneline_cols and hist_cols to only the columns needed for the function. If you do not provide these, all columns will be used, which can be slow for large populations.
- Parameters:
func (function) –
Function to apply to the parsed population to create a transient population. The function needs to take 3 arguments:
history_chunk : pd.DataFrame
oneline_chunk : pd.DataFrame
formation_channels_chunk : pd.DataFrame
and return a pd.DataFrame containing the transient population, which needs to contain the columns ‘time’ and ‘metallicity’.
oneline_cols (list of str, optional) – Columns to extract from the oneline dataframe. Default is all columns.
hist_cols (list of str, optional) – Columns to extract from the history dataframe. Default is all columns.
- Returns:
A TransientPopulation object for interfacing with the transient population or None if no systems are present in the TransientPopulation.
- Return type:
TransientPopulation or None
- Raises:
ValueError – If the transient population requires a time column or if the transient population contains duplicate columns.
Examples
See the tutorials for examples of how to use this method.
- export_selection(selection, filename, overwrite=False, append=False, history_chunksize=1000000)[source]
Export a selection of the population to a new file
This method exports a selection of systems from the population to a new file. The selected systems are specified by their indices in the population.
By default the selected systems will overwrite the file if it already exists. If overwrite is set to False, the selected systems will be appended to the existing file if it already exists and the indices will be shifted based on the current length of data in the file that is being appended to.
- Parameters:
- Raises:
ValueError – If the filename does not contain “.h5” extension.
Warning
- ReplaceValueWarning
If there is no “metallicity” column in the oneline dataframe and the population file contains multiple metallicities.
Notes
The exported systems will be appended to the existing file if it already exists.
The indices of the exported systems will be shifted based on the current length of data in the file.
The “oneline” and “history” dataframes of the selected systems will be written to the file.
If available, the “formation_channels” dataframe and “history_lengths” dataframe of the selected systems will also be written to the file.
The “metallicity” column of the oneline dataframe will be added if it is not present, using the metallicity of the population file.
The “mass_per_metallicity” dataframe will be updated with the number of selected systems.
Examples
# Export systems with indices [0, 1, 2] to a new file named “selected.h5” >>> population.export_selection([0, 1, 2], “selected.h5”)
# Export systems with indices [3, 4, 5] to an existing file named “existing.h5” >>> population.export_selection([3, 4, 5], “existing.h5”)
# Export systems with indices [6, 7, 8] to a new file named “selected.h5” in chunks of 2 >>> population.export_selection([6, 7, 8], “selected.h5”, history_chunksize=2)
- property formation_channels
Retrieves the formation channels from the population file.
- Returns:
The formation channels if available, otherwise None.
- Return type:
pandas.DataFrame or None
- class posydon.popsyn.synthetic_population.PopulationIO[source]
Bases:
object
A class to handle the input/output of population files.
This class provides methods to load and save population files in HDF5 format. It also includes methods to load and save metadata and ini parameters.
- mass_per_metallicity
A DataFrame containing mass per metallicity data.
- Type:
pandas.DataFrame
- class posydon.popsyn.synthetic_population.PopulationRunner(path_to_ini, verbose=False)[source]
Bases:
object
A class to handle the evolution of binary populations.
- binary_populations
The binary populations.
- Type:
Initialize the binary populations from an ini file.
- Parameters:
- Raises:
ValueError – If the provided path_to_ini does not have a ‘.ini’ extension.
Notes
This method initializes the PopulationRunner object by reading the binary population parameters from an ini file specified by path_to_ini. It also allows for optional verbosity, which, when set to True, enables additional information to be printed in operation of the class.
The path_to_ini should be a valid path to an ini file. If the provided path_to_ini does not have a ‘.ini’ extension, a ValueError is raised.
Examples
>>> sp = PopulationRunner('/path/to/ini/file.ini') >>> sp = PopulationRunner('/path/to/ini/file.ini', verbose=True)
- evolve(overwrite=False)[source]
Evolve the binary populations.
This method is responsible for evolving the binary populations. It iterates over each population in the binary_populations list and calls the evolve method on each population. After evolving each population, it merges them using the merge_parallel_runs method.
Note
The merge_parallel_runs method is called only if the comm attribute of the population is None.
- merge_parallel_runs(pop)[source]
Merge the parallel runs of the population.
- Parameters:
pop (BinaryPopulation) – The binary population whose files have to be merged.
- class posydon.popsyn.synthetic_population.Rates(filename, transient_name, SFH_identifier, verbose=False, chunksize=100000)[source]
Bases:
TransientPopulation
Class representing rates of a transient population.
- weights
The weights of the transient population.
- Type:
pandas.DataFrame
- z_birth
The redshift of the birth bins.
- Type:
pandas.DataFrame
- z_events
The redshift of the events.
- Type:
pandas.DataFrame
- intrinsic_rate_density
The intrinsic rate density of the transient population.
- Type:
pandas.DataFrame
- edges_metallicity_bins
The edges of the metallicity bins of the star formation history.
- Type:
np.ndarray
- centers_metallicity_bins
The centers of the metallicity bins of the star formation history.
- Type:
np.ndarray
- edges_redshift_bins
The edges of the redshift bins of the star formation history.
- Type:
np.ndarray
- centers_redshift_bins
The centers of the redshift bins of the star formation history.
- Type:
np.ndarray
Initialize the Rates object.
This method initializes a Rates object by linking it to the population file with the specified transient name and star formation history identifier. The path in the file is ‘/transients/{transient_name}/rates/{SFH_identifier}’.
- calculate_intrinsic_rate_density(mt_channels=False)[source]
Compute the intrinsic rate density over redshift of the transient population.
Besides returning the intrinsic rate density, this method also stores the results in the HDF5 file for further analysis. This can be accessed using the intrinsic_rate_density attribute of the Rates class.
- Parameters:
mt_channels (bool, optional) – Flag indicating whether to calculate the intrinsic rate density for each channel separately. Default is False.
- Returns:
DataFrame containing the intrinsic rate density values.
- Return type:
pandas.DataFrame
- calculate_observable_population(observable_func, observable_name)[source]
Calculate an observable population.
The observable population is calculated based on the provided observable function. It should recalculate your weights based on an observability probability given certain transinet parameters.
This function requires the following input chunks: 1. transient_pop_chunk 2. z_events_chunk 3. weights_chunk The observable function should output a DataFrame with the same shape as the weights_chunk.
The observable population is stored in the HDF5 file at the location ‘/transients/{transient_name}/rates/observable/{observable_name}’.
- Parameters:
observable_func (function) – The observability function that takes the TransientPopulation as input.
observable_name (str) – The name of the observable.
Note
If the observable population already exists in the file, it will be overwritten.
- property centers_metallicity_bins
Return the centers of the metallicity bins.
- Returns:
Returns sampled metallicities of the population. This corresponds to the center of each metallicity bin.
- Return type:
array float
- property centers_redshift_bins
Compute redshift bin centers.
- Returns:
We devide the cosmic time history of the Universe in equally spaced bins of cosmic time of self.MODEL[‘delta_t’] (100 Myr default) an compute the redshift corresponding to center of these bins.
- Return type:
array floats
- property edges_metallicity_bins
Return the edges of the metallicity bins.
- Returns:
Returns the edges of all metallicity bins. We assume metallicities were binned in log-space.
- Return type:
array float
- property edges_redshift_bins
Compute redshift bin edges.
- Returns:
We devide the cosmic time history of the Universe in equally spaced bins of cosmic time of self.MODEL[‘delta_t’] (100 Myr default) an compute the redshift corresponding to edges of these bins.
- Return type:
array floats
- property intrinsic_rate_density
Return the intrinsic rate density of the transient population at the specified SFH_identifier and transient_name.
The data is read from the HDF5 file at ‘/transients/{transient_name}/rates/{SFH_identifier}/intrinsic_rate_density’.
- Returns:
The intrinsic rate density of the transient population.
- Return type:
pandas.DataFrame
- observable_population(observable_name)[source]
Return the observable population based on the provided name.
This method returns the observable population based on the provided name, which can take a while to load if the population is large. It loads the observable population from ‘/transients/{transient_name}/rates/observable/{observable_name}’ in the HDF5 file.
- Parameters:
observable_name (str) – The name of the observable population to return.
- Returns:
The observable population based on the provided name.
- Return type:
pandas.DataFrame
- property observable_population_names
Return the names of the observable populations in the associated file.
- Returns:
The names of the observable populations.
- Return type:
- plot_hist_properties(prop, intrinsic=True, observable=None, bins=50, channel=None, **kwargs)[source]
Plot a histogram of a given property available in the transient population.
This method plots a histogram of a given property available in the transient population. The property can be intrinsic or observable, and the histogram can be plotted for a specific channel if provided.
- Parameters:
prop (str) – The property to plot the histogram for.
intrinsic (bool, optional) – If True, plot the intrinsic property. Default is True.
observable (str, optional) – The observable population name to plot the histogram for. Default is None.
bins (int, optional) – The number of bins to use for the histogram. Default is 50.
channel (str, optional) – The channel to plot the histogram for. Default is None. A channel column must be present in the transient population.
**kwargs – Additional keyword arguments to pass to the plot
- Raises:
ValueError – If the specified property is not a valid property in the transient population. If the specified observable is not a valid observable population. If the specified channel is not present in the transient population.
- plot_intrinsic_rate(channels=False, **kwargs)[source]
Plot the intrinsic rate density of the transient population.
- select_rate_slice(key, start=None, stop=None)[source]
Selects a slice of a rates dataframe at key.
This method allows you to select a slice in rows from the diffferent rates dataframes. The slice is selected based on the start and stop indices. The key specifies which rates dataframe to select, and must be one of [‘weights’, ‘z_events’, ‘birth’].
- Parameters:
- Returns:
The selected slice of rates.
- Return type:
pandas.DataFrame
- Raises:
ValueError – If the key is not one of [‘weights’, ‘z_events’, ‘birth’].
- property weights
Retrieves the weights from the HDFStore.
The rows are indexed by the binary index of the events, while to columns are indexed by the redshift of the birth bins.
- Returns:
The weights DataFrame.
- Return type:
pandas.DataFrame
- property z_birth
Retrieves the ‘birth’ data from the HDFStore.
The ‘birth’ DataFrame contains the redshift and age of the Universe of the birth bins with columns ‘z’ and ‘t’.
- Returns:
The ‘birth’ DataFrame, which contains the redshift and age of the Universe of the birth bins.
- Return type:
pandas.DataFrame
- property z_events
Returns the ‘z_events’ data from the HDFStore.
The ‘z_events’ data contains the redshifts at which the events occur. The rows of the returned DataFrame are indexed by the binary index of the events. The columns of the returned DataFrame are indexed by the redshift of the birth bins.
- Returns:
The ‘z_events’ data from the HDFStore.
- Return type:
pandas.DataFrame
- class posydon.popsyn.synthetic_population.TransientPopulation(filename, transient_name, verbose=False, chunksize=100000)[source]
Bases:
Population
A class representing a population of transient events.
This class allows you to calculate additional properties of the population, such as the efficiency of events per Msun for each solar metallicity, and to calculate the cosmic weights of the transient population.
- population
DataFrame containing the whole transient population.
- Type:
pandas.DataFrame
- efficiency
DataFrame containing the efficiency of events per Msun for each solar metallicity.
- Type:
pandas.DataFrame
Initialise the TransientPopulation object.
This method initializes the TransientPopulation object by linking it to the population file. The transient population linked is located at ‘/transients/{transient_name}’ in the population file.
- Parameters:
filename (str) – The name of the file containing the population. The file should be in HDF5 format.
transient_name (str) – The name of the transient population within the file.
verbose (bool, optional) – If True, additional information will be printed during the initialization process.
chunksize (int, optional) – The chunksize to use when reading the population file (default is 100000).
- Raises:
ValueError – If the specified transient population name is not found in the file.
Notes
The population data is stored in an HDF5 file format. The file should contain a group named ‘/transients’ which holds all the transient populations. The specified transient population name should be a valid group name within ‘/transients’. If the transient population has associated efficiencies, they will be loaded as well.
Examples
>>> filename = 'population_data.h5' >>> transient_name = 'BBH' >>> population = TransientPopulation(filename, transient_name, verbose=True)
- calculate_cosmic_weights(SFH_identifier, MODEL_in=None)[source]
Calculate the cosmic weights of the transient population.
This method calculates the cosmic weights of the transient population based on the provided star formation history identifier and model parameters. It performs various calculations and stores the results in an HDF5 file at the location ‘/transients/{transient_name}/rates/{SFH_identifier}’. This allows for multiple star formation histories to be used with the same transient population.
The default MODEL parameters are used if none are provided, which come from the IllustrisTNG model.
- Parameters:
- Returns:
An instance of the Rates class.
- Return type:
- Raises:
ValueError – If a parameter name in MODEL_in is not valid.
Notes
This function calculates the cosmic weights of the transient population based on the provided star formation history identifier and model parameters. It performs various calculations and stores the results in an HDF5 file.
The cosmic weights are computed for each event in the population, taking into account the metallicity, redshift, and birth time of the events. The weights are calculated using the provided model parameters and the underlying mass distribution.
The calculated weights, along with the corresponding redshifts of the events, are stored in the HDF5 file for further analysis. These can be accessed using the Rates class.
Examples
>>> transient_population = TransientPopulation('filename.h5', 'transient_name') >>> transient_population.calculate_cosmic_weights('IllustrisTNG', MODEL_in=DEFAULT_MODEL)
- property columns
Return the columns of the transient population.
- Returns:
A list of column names in the transient population.
- Return type:
- get_efficiency_over_metallicity()[source]
Compute the efficiency of events per Msun for each solar_metallicities.
This method calculates the efficiency of events per solar mass for each solar metallicity value in the transient population. It first checks if the efficiencies have already been computed and if so, overwrites them. Then, it iterates over each metallicity value and calculates the efficiency by dividing the count of events with the underlying stellar mass. The efficiencies are stored in a DataFrame with the metallicity values as the index and the ‘total’ column representing the efficiency for all channels. If the ‘channel’ column is present, it also computes the merger efficiency per channel and adds the results to the DataFrame.
- plot_delay_time_distribution(metallicity=None, ax=None, bins=100, color='black')[source]
Plot the delay time distribution of the transient population.
This method plots the delay time distribution of the transient population. If a specific metallicity is provided, the delay time distribution of the population at that metallicity will be plotted. Otherwise, the delay time distribution of the entire population will be plotted.
- Parameters:
metallicity (float or None) – The metallicity value to select a specific population. If None, the delay time distribution of the entire population will be plotted.
ax (matplotlib.axes.Axes or None) – The axes object to plot the distribution on. If None, a new figure and axes will be created.
bins (int) – The number of bins to use for the histogram.
color (str) – The color of the histogram.
- Raises:
ValueError – If the specified metallicity is not present in the population.
Notes
The delay time distribution is normalized by the total mass of the population if no metallicity is specified.
Otherwise, it is normalized by the mass of the population at the specified metallicity.
- plot_efficiency_over_metallicity(**kwargs)[source]
Plot the efficiency over metallicity.
- Parameters:
channel (bool, optional) – If True, plot the subchannels. Default is False.
- plot_popsyn_over_grid_slice(grid_type, met_Zsun, **kwargs)[source]
Plot the transients over the grid slice.
- property population
Returns the entire transient population as a pandas DataFrame.
This method retrieves the transient population data from a file and returns it as a pandas DataFrame. Please note that if the transient population is too large, it may consume a significant amount of memory.
- Returns:
A DataFrame containing the transient population data.
- Return type:
pd.DataFrame
- select(where=None, start=None, stop=None, columns=None)[source]
Select a subset of the transient population.
This method allows you to filter and extract a subset of rows from the transient table stored in an HDF file. You can specify conditions to filter the rows, define the range of rows to select, and choose specific columns to include in the subset.
- Parameters:
where (str, optional) – A condition to filter the rows of the transient table. Default is None. It is only possible to search on the index or string columns.
start (int, optional) – The starting index of the subset. Default is None.
stop (int, optional) – The ending index of the subset. Default is None.
columns (list, optional) – The column names to include in the subset. Default is None.
- Returns:
The selected subset of the transient table.
- Return type:
pd.DataFrame
Examples
# Select rows based on a condition >>> df = transpop.select(where=”S1_state == ‘BH’”)
# Select rows from index 10 to 20 >>> df = transpop.select(start=10, stop=20)
# Select specific columns >>> df = transpop.select(columns=[‘time’, ‘metallicity’])