Population#

class cogsworth.pop.Population(n_binaries, processes=None, final_kstar1=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], final_kstar2=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], sfh_model=None, galactic_potential={'bulge': <HernquistPotential: m=5.00e+09 solMass, c=1.00 kpc (kpc,Myr,solMass,rad)>, 'disk': <MN3ExponentialDiskPotential: m=4.77e+10 solMass, h_R=2.60 kpc, h_z=0.30 kpc (kpc,Myr,solMass,rad)>, 'halo': <NFWPotential: m=5.54e+11 solMass, r_s=15.63 kpc, a=1.00 , b=1.00 , c=1.00  (kpc,Myr,solMass,rad)>, 'nucleus': <HernquistPotential: m=1.81e+09 solMass, c=0.07 kpc (kpc,Myr,solMass,rad)>}, v_dispersion=<Quantity 5. km / s>, max_ev_time=<Quantity 12. Gyr>, timestep_size=<Quantity 1. Myr>, SSE_settings={}, BSE_settings={}, ini_file=None, use_default_BSE_settings=False, sampling_params={}, sampling_mask='', bcm_default_timestep=None, bcm_timestep_conditions=[], store_entire_orbits=True, bpp_columns=None, bcm_columns=None, error_file_path='./', integrator=<class 'gala.integrate.pyintegrators.dopri853.DOPRI853Integrator'>, integrator_kwargs={}, orbit_integration_retry_settings={})[source]#

Bases: object

Class for creating and evolving populations of binaries throughout the Milky Way

Parameters:
n_binariesint

How many binaries to sample for the population

processesint, optional

How many processes to run if you want multithreading, by default all cores available on machine

final_kstar1list, optional

Desired final types for primary star, by default list(range(16))

final_kstar2list, optional

Desired final types for secondary star, by default list(range(16))

sfh_modelStarFormationHistory or CompositeStarFormationHistory, optional

A StarFormationHistory or CompositeStarFormationHistory class to use for sampling the initial galaxy parameters, by default None, which uses Wagg2022

galactic_potentialPotential, optional

Galactic potential to use for evolving the orbits of binaries, by default MilkyWayPotential

v_dispersionQuantity [velocity], optional

Velocity dispersion to apply relative to the local circular velocity, by default 5*u.km/u.s

max_ev_timeQuantity [time], optional

Maximum evolution time for both COSMIC and Gala, by default 12.0*u.Gyr

timestep_sizeQuantity [time], optional

Size of timesteps to use in galactic evolution, by default 1*u.Myr

SSE_settingsdict, optional

Any single stellar evolution (SSE) settings to pass to COSMIC, superseded by ini_file if provided. By default, assumed to be {‘stellar_engine’: ‘sse’}

BSE_settingsdict, optional

Any BSE settings to pass to COSMIC, superseded by ini_file if provided

ini_filestr, optional

Path to an ini file to use for the COSMIC stellar evolution, supersedes BSE_settings by default None

use_default_BSE_settingsbool, optional

Whether to use the default COSMIC BSE settings, by default False. If False then at least one of BSE_settings or ini_file must be provided.

bcm_default_timestepfloat, optional

If provided, this will be used as the default timestep for the BCM output in COSMIC (i.e. in cases where the conditions in bcm_timestep_conditions are not met). By default, this is set to None and the default COSMIC behaviour is used, which only outputs the first and last timesteps. Setting a small number here will significantly slow down the evolution, but give you more resolved evolution for each binary.

bcm_timestep_conditionsList of lists, optional

Any timestep conditions to pass to COSMIC evolution. This will affect the rows that are output in the the BCM table, by default only the first and last timesteps are output. For more details check out the relevant COSMIC docs

sampling_paramsdict, optional

Any additional parameters to pass to the COSMIC sampling (see COSMIC docs for the full list)

sampling_maskstr, optional

A query string to apply as a mask to the sampled binaries after sampling, only binaries matching the mask are retained. This is applied before sampling the galaxy, and any evolution. Syntax is the same as for pandas query strings, see pandas.DataFrame.query() for details, and the columns available are the same as those in the initial_binaries table. For example, you could set this to “mass_1 > 7” to only keep binaries where the primary mass is greater than 7 solar masses. Or something more complex like “(mass_1 > 7) or (mass_2 > 2 and ecc > 0.5)”

store_entire_orbitsbool, optional

Whether to store the entire orbit for each binary, by default True. If not then only the final PhaseSpacePosition will be stored. This cuts down on both memory usage and disk space used if you save the Population (as well as how long it takes to reload the data).

bpp_columnslist, optional

Which columns COSMIC should store in the bpp table. If None, default columns are used. See https://cosmic-popsynth.github.io/COSMIC/pages/output_info.html for a list of columns.

bcm_columnslist, optional

Which columns COSMIC should store in the bcm table. If None, default columns are used. See https://cosmic-popsynth.github.io/COSMIC/pages/output_info.html for a list of columns.

error_file_pathstr, optional

Path to a folder in which to store any error files generated during evolution, by default “./”

integratorIntegrator, optional

The integrator used by gala for evolving the orbits of binaries in the galactic potential (default is DOPRI853Integrator).

integrator_kwargsdict, optional

Any additional keyword arguments to pass to the gala integrator, by default an empty dict

orbit_integration_retry_settingsdict, optional

Settings for retrying orbit integrations that fail on the first attempt. Potential settings are:

  • “max_retries”: int

    The maximum number of times to retry an orbit integration that fails (default is 2)

  • “timestep_multiplier”: float

    The factor by which to multiply the timestep size for each retry (default is 0.1, i.e. reduce the timestep by a factor of 10 for each retry)

Attributes Summary

bcm

A table of the evolutionary history of each binary at dynamically chosen timesteps.

bin_nums

An array of the unique identifiers for each binary in a population.

bpp

A table of the evolutionary history of each binary.

classes

A table of classes that apply to each binary.

disrupted

A mask of whether a binary was disrupted during its evolution.

escaped

A mask of whether a binary escaped the galaxy during its evolution.

final_bpp

The final state of each binary in the population.

final_pos

The final position of each binary (or star from a disrupted binary) in the galaxy.

final_primary_pos

The final position of each primary star in the galaxy.

final_primary_vel

The final velocity of each primary star in the galaxy.

final_secondary_pos

The final position of each secondary star in the galaxy.

final_secondary_vel

The final velocity of each secondary star in the galaxy.

final_vel

The final velocity of each binary (or star from a disrupted binary) in the galaxy.

initC

Alias for initial_binaries

initial_binaries

The initial binaries that were sampled to generate the population.

initial_galaxy

The initial sampled galactic star formation history.

kick_info

A table of the kicks that occur for each binary.

mass_binaries

The total mass in binaries needed to generate the population.

mass_singles

The total mass in single stars needed to generate the population.

n_bin_req

The number of binary stars needed to generate the population.

n_singles_req

The number of single stars needed to generate the population.

observables

A table of the observable properties of each binary.

orbits

The orbits of each system within the galaxy from its birth until max_ev_time.

primary_orbits

The orbits of primary stars

secondary_orbits

The orbits of secondary stars

Methods Summary

copy()

Create a copy of the population

create_population([with_timing])

Create an entirely evolved population of binaries.

get_citations([filename])

Print the citations for the packages/papers used in the population

get_final_mw_skycoord()

Get the final positions and velocities as an astropy SkyCoord object

get_gaia_observed_bin_nums([ra, dec, ...])

Get a list of bin_nums of systems that are bright enough to be observed by Gaia.

get_healpix_inds([ra, dec, nside])

Get the indices of the healpix pixels that each binary is in

get_observables(**kwargs)

Get observables associated with the binaries at present day.

perform_galactic_evolution([progress_bar])

Use gala to perform the orbital integration for each evolved binary

perform_stellar_evolution()

Perform the (binary) stellar evolution of the sampled binaries

plot_cartoon_binary(bin_num, **kwargs)

Plot a cartoon of the evolution of a single binary

plot_hrd(**kwargs)

Plot the HR diagram for the population at present day

plot_map([ra, dec, nside, coord, cmap, ...])

Plot a healpix map of the final positions of all binaries in population

plot_orbit(bin_num[, show_sn, show_merger, ...])

Plot the Galactic orbit of a binary system

plot_sky_locations([fig, ax, show, ...])

Plot the final positions of the binaries in the Milky Way galactocentric frame

sample_initial_binaries()

Sample the initial binary parameters for the population.

sample_initial_galaxy()

Sample the initial galactic times, positions and velocities

save(file_name[, overwrite])

Save a Population to disk as an HDF5 file.

to_COMPASPopulation(**kwargs)

Convert to a COMPASPopulation object from interop module

to_legwork_sources([distances, ...])

Convert the final state of the population to a LEGWORK Source class (only including bound binaries)

translate_tables(**kwargs)

Translate the COSMIC BSE tables to human readable format

Attributes Documentation

bcm[source]#

A table of the evolutionary history of each binary at dynamically chosen timesteps.

Each row of this table corresponds to a timestep in the evolution of a binary. Timesteps are set based on user-defined bcm_default_timestep and bcm_timestep_conditions. The columns of the table are described in detail in the COSMIC documentation.

Returns:
bcmDataFrame

The evolutionary history of each binary at dynamically chosen timesteps. Note this will be None if no timestep conditions have been set (in bcm_default_timestep or bcm_timestep_conditions).

Raises:
Warning

If no timestep conditions (bcm_timestep_condition) have been set for the BCM table.

ValueError

If no stellar evolution has been performed yet.

bin_nums[source]#

An array of the unique identifiers for each binary in a population.

This is a helper function which pulls from the bin_nums available in final_bpp, or initC, or initial_binaries if available. If none of these are available, an error is raised.

Returns:
bin_numsndarray

An array of the unique identifiers for each binary in the population.

Raises:
ValueError

If no binaries have been sampled or evolved yet.

bpp[source]#

A table of the evolutionary history of each binary.

Each row of this table corresponds to an important timestep in the evolution of a binary. Events that log a timestep include: stellar type of a star changing, mass transfer, a supernova, a common envelope event, a binary merger, or a disruption. The columns of the table are described in detail in the COSMIC documentation.

Returns:
bppDataFrame

The evolutionary history of each binary.

Raises:
ValueError

If no stellar evolution has been performed yet.

classes[source]#

A table of classes that apply to each binary.

Each row corresponds to a binary and the columns are a boolean of whether they meet the criteria for a class. For a full description of classes and their criteria, run list_classes().

Returns:
classesDataFrame

The classes that apply to each binary.

disrupted[source]#

A mask of whether a binary was disrupted during its evolution.

Returns:
disruptedndarray, shape (len(self),)

A mask of whether a binary was disrupted during its evolution.

escaped[source]#

A mask of whether a binary escaped the galaxy during its evolution.

This is calculated by comparing the final velocity of the binary to the escape velocity at its final position.

Returns:
escapedndarray, shape (len(self),)

A mask of whether a binary escaped the galaxy during its evolution.

final_bpp[source]#

The final state of each binary in the population.

This is simply the final row from the bpp table for each binary.

Returns:
final_bppDataFrame

The final state of each binary in the population.

final_pos[source]#

The final position of each binary (or star from a disrupted binary) in the galaxy.

Returns:
final_posndarray, shape (len(self) + self.disrupted.sum(), 3)

The final position of each binary (or star from a disrupted binary) in the galaxy.

final_primary_pos[source]#

The final position of each primary star in the galaxy.

Returns:
final_primary_posndarray, shape (len(self), 3)

The final position of each primary star in the galaxy.

final_primary_vel[source]#

The final velocity of each primary star in the galaxy.

Returns:
final_primary_velndarray, shape (len(self), 3)

The final velocity of each primary star in the galaxy.

final_secondary_pos[source]#

The final position of each secondary star in the galaxy.

Returns:
final_secondary_posndarray, shape (len(self), 3)

The final position of each secondary star in the galaxy.

final_secondary_vel[source]#

The final velocity of each secondary star in the galaxy.

Returns:
final_secondary_velndarray, shape (len(self), 3)

The final velocity of each secondary star in the galaxy.

final_vel[source]#

The final velocity of each binary (or star from a disrupted binary) in the galaxy.

Returns:
final_velndarray, shape (len(self) + self.disrupted.sum(), 3)

The final velocity of each binary (or star from a disrupted binary) in the galaxy.

initC[source]#

Alias for initial_binaries

initial_binaries[source]#

The initial binaries that were sampled to generate the population.

Returns:
initial_binariesDataFrame

The initial binaries that were sampled to generate the population.

Raises:
ValueError

If no binaries have been sampled yet.

initial_galaxy[source]#

The initial sampled galactic star formation history.

This contains the initial conditions for the galaxy that was sampled to generate the population. This includes the birth times, positions, velocities, and metallicities of the stars in the galaxy.

Returns:
initial_galaxyStarFormationHistory or CompositeStarFormationHistory

The initial galaxy that was sampled to generate the population.

Raises:
ValueError

If no galaxy has been sampled yet.

kick_info[source]#

A table of the kicks that occur for each binary.

Each row of this table corresponds to a potential supernova kick, such that there are two rows for each binary in the population. The columns of the table are described in detail in the COSMIC documentation.

Returns:
kick_infoDataFrame

Information about the kicks that occur for each binary.

Raises:
ValueError

If no stellar evolution has been performed yet.

mass_binaries[source]#

The total mass in binaries needed to generate the population.

Returns:
mass_binariesfloat

The total mass in binaries

Raises:
ValueError

If no population sampled yet.

mass_singles[source]#

The total mass in single stars needed to generate the population.

Returns:
mass_singlesfloat

The total mass in single stars needed to generate the population (in solar masses).

Raises:
ValueError

If no population sampled yet.

n_bin_req[source]#

The number of binary stars needed to generate the population.

Returns:
n_bin_reqint

The number of binary stars needed to generate the population.

Raises:
ValueError

If no population sampled yet.

n_singles_req[source]#

The number of single stars needed to generate the population.

Returns:
n_singles_reqint

The number of single stars needed to generate the population.

Raises:
ValueError

If no population sampled yet.

observables[source]#

A table of the observable properties of each binary.

Returns:
observablesDataFrame

The observable properties of each binary. Columns are defined in get_observables().

Raises:
ValueError

If no observables have been calculated yet.

orbits[source]#

The orbits of each system within the galaxy from its birth until max_ev_time.

This list will have length = len(self) + self.disrupted.sum(), where the first section are for bound binaries and disrupted primaries and the last section are for disrupted secondaries.

Returns:
orbitslist of Orbit, shape (len(self) + self.disrupted.sum(),)

The orbits of each system within the galaxy from its birth until max_ev_time.

Raises:
ValueError

If no orbits have been calculated yet.

primary_orbits[source]#

The orbits of primary stars

Returns:
primary_orbitsOrbit, shape (len(self),)

The orbits of the primary stars in the population

secondary_orbits[source]#

The orbits of secondary stars

Returns:
secondary_orbitsOrbit, shape (len(self),)

The orbits of the secondary stars in the population

Methods Documentation

copy()[source]#

Create a copy of the population

create_population(with_timing=True)[source]#

Create an entirely evolved population of binaries.

This will sample the initial binaries and initial galaxy and then perform both the cosmic and gala evolution.

Parameters:
with_timingbool, optional

Whether to print messages about the timing, by default True

get_citations(filename=None)[source]#

Print the citations for the packages/papers used in the population

get_final_mw_skycoord()[source]#

Get the final positions and velocities as an astropy SkyCoord object

..warning:

This function assumes the final positions and velocities are in the MW galactocentric frame
get_gaia_observed_bin_nums(ra=None, dec=None, gaia_G_filter='Gaia_G_EDR3')[source]#

Get a list of bin_nums of systems that are bright enough to be observed by Gaia.

This is calculated based on the Gaia selection function provided by gaiaunlimited. This function returns a random sample of systems where systems are included in the observed subset with a probability given by Gaia’s completeness at their location.

E.g. if Gaia’s completeness is 0 for a source of a given magnitude and location then it will never be included. Similarly, if the completeness is 1 then it will always be included. However, if the completeness is 0.5 then it will only be included in the list of bin_nums half of the time.

Parameters:
randarray or None

Right ascension of the binaries. Either supply value or set to “auto” to use the RA from the population’s observables.

decndarray or None

Declination of the binaries. Either supply value or set to “auto” to use the Dec from the population’s observables.

gaia_G_filterstr

The name of the Gaia G-band filter to use for apparent magnitude (e.g. “Gaia_G_EDR3”).

Returns:
primary_observedndarray

A list of binary numbers (that can be used in tables like final_bpp) for which the bound binary/disrupted primary would be observed

secondary_observedndarray

A list of binary numbers (that can be used in tables like final_bpp) for which the disrupted secondary would be observed

get_healpix_inds(ra=None, dec=None, nside=128)[source]#

Get the indices of the healpix pixels that each binary is in

Parameters:
rafloat or str

Either the right ascension of the system in radians or “auto” to automatically calculate assuming Milky Way galactocentric coordinates

decfloat or str

Either the declination of the system in radians or “auto” to automatically calculate assuming Milky Way galactocentric coordinates

nsideint, optional

Healpix nside parameter, by default 128

Returns:
pixndarray

The indices for each system

get_observables(**kwargs)[source]#

Get observables associated with the binaries at present day.

These include: extinction due to dust, absolute and apparent bolometric magnitudes for each star, apparent magnitudes in each filter and observed temperature and surface gravity for each binary.

For bound binaries and stellar mergers, only the column {filter}_app_1 is relevant. For disrupted binaries, {filter}_app_1 is for the primary star and {filter}_app_2 is for the secondary star.

Parameters:
**kwargs to pass to :func:`~cogsworth.obs.observables.get_photometry`
perform_galactic_evolution(progress_bar=True)[source]#

Use gala to perform the orbital integration for each evolved binary

Parameters:
progress_barbool, optional

Whether to show a progress bar for the orbital integration, by default True

perform_stellar_evolution()[source]#

Perform the (binary) stellar evolution of the sampled binaries

plot_cartoon_binary(bin_num, **kwargs)[source]#

Plot a cartoon of the evolution of a single binary

Parameters:
bin_numint

Which binary to plot

**kwargsvarious

Keyword arguments to pass, see plot_cartoon_evolution() for options

Returns:
fig, axfigure, axis

Figure and axis of the plot

plot_hrd(**kwargs)[source]#

Plot the HR diagram for the population at present day

Parameters:
**kwargsvarious

Keyword arguments to pass, see plot_hrd() for options

Returns:
fig, axfigure, axis

Figure and axis of the plot

plot_map(ra=None, dec=None, nside=128, coord='C', cmap='magma', norm='log', unit=None, show=True, **mollview_kwargs)[source]#

Plot a healpix map of the final positions of all binaries in population

Parameters:
nsideint, optional

Healpix nside parameter, by default 128

coordstr, optional

Which coordinates to plot. One of [“C[elestial]”, “G[alactic”, “E[quatorial]”], by default “C”

cmapstr, optional

A matplotlib colormap to use for the plot, by default “magma”

normstr, optional

How to normalise the total number of binaries (anything linear or log), by default “log”

unitstr, optional

A label to use for the unit of the colour bar, by default “\(\log_{10}(N_{\rm binaries})\)” if norm==log and “\(N_{\rm binaries}\)” if norm==linear

showbool, optional

Whether to immediately show the plot, by default True

**mollview_kwargs

Any additional arguments that you want to pass to healpy’s mollview

plot_orbit(bin_num, show_sn=True, show_merger=True, sn_kwargs={}, show=True, show_legend=True, **kwargs)[source]#

Plot the Galactic orbit of a binary system

Parameters:
bin_numint

Which binary to plot

show_snbool, optional

Whether to show the position of the SNe, by default True

show_mergerbool, optional

Whether to show the position of a merger, by default True

sn_kwargsdict, optional

Any additional arguments to pass to the SN scatter plot call, by default {}

showbool, optional

Whether to immediately show the plot

show_legendbool, optional

Whether to show the legend

**kwargsvarious

Any additional arguments to pass to cogsworth.plot.plot_galactic_orbit()

Returns:
fig, axesfigure, ndarray

Figure and axes of the plot

Raises:
ValueError

If the bin_num isn’t in the population

plot_sky_locations(fig=None, ax=None, show=True, show_galactic_plane=True, **kwargs)[source]#

Plot the final positions of the binaries in the Milky Way galactocentric frame

sample_initial_binaries()[source]#

Sample the initial binary parameters for the population.

sample_initial_galaxy()[source]#

Sample the initial galactic times, positions and velocities

save(file_name, overwrite=False)[source]#

Save a Population to disk as an HDF5 file.

Parameters:
file_namestr

A file name to use. Either no file extension or “.h5”.

overwritebool, optional

Whether to overwrite any existing files, by default False

Raises:
FileExistsError

If overwrite=False and files already exist

to_COMPASPopulation(**kwargs)[source]#

Convert to a COMPASPopulation object from interop module

Parameters:
**kwargsvarious

Any arguments to pass to COMPASPopulation

Returns:
cpCOMPASPopulation

The COMPASPopulation object

to_legwork_sources(distances=None, assume_mw_galactocentric=False)[source]#

Convert the final state of the population to a LEGWORK Source class (only including bound binaries)

Parameters:
distancesnp.ndarray, optional

Custom distance to each source, by default None

assume_mw_galactocentricbool, optional

Assume population is in Milky Way and galactocentric coordinate system - such that distances can be calculated assuming the present location of the Earth, by default False

Returns:
sourcesSource

LEGWORK sources

Raises:
ValueError

When distances aren’t provided and assume_mw_galactocentric=False

translate_tables(**kwargs)[source]#

Translate the COSMIC BSE tables to human readable format

Parameters:
**kwargsvarious

Any arguments to pass to translate_COSMIC_tables()