posydon.utils

posydon.utils.common_functions

Common functions to be used while running populations.

posydon.utils.common_functions.CEE_parameters_from_core_abundance_thresholds(star, verbose=False)[source]

Find the envelope mass for different core boundary abundance thresholds.

The results are meant to be used in collabration with the respective lambda_CE_*cent, lambda_CE_pure_He_star_10cent.

Parameters:

star (SingleStar object holding the history of its attributes.)

Returns:

  • None

  • It updates the following values in the star object

  • m_core_CE_1cent (float) – core mass (using an element abundance of 1%)

  • m_core_CE_10cent (float) – core mass (using an element abundance of 10%)

  • m_core_CE_30cent (float) – core mass (using an element abundance of 30%)

  • m_core_CE_pure_He_star_10cent (float) – core mass (using an element abundance of 10% in He)

  • r_core_CE_1cent (float) – core radius (using an element abundance of 1%)

  • r_core_CE_10cent (float) – core radius (using an element abundance of 10%)

  • r_core_CE_30cent (float) – core radius (using an element abundance of 30%)

  • r_core_CE_pure_He_star_10cent (float) – core radius (using an element abundance of 10% in He)

  • lambda_CE_1cent (float) – lambda value (using an element abundance of 1%)

  • lambda_CE_10cent (float) – lambda value (using an element abundance of 10%)

  • lambda_CE_30cent (float) – lambda value (using an element abundance of 30%)

  • lambda_CE_pure_He_star_10cent (float) – lambda value (using an element abundance of 10% in He)

posydon.utils.common_functions.CO_radius(M, COtype)[source]

Calculate the radius of a compact object based on its type and mass.

Parameters:
  • M (float) – CO mass in Msun

  • COtype (str) – Tyep of compact object. Accepted values: “BH”, “NS”, “WD”

Returns:

Compact object radius in solar radii

Return type:

float

posydon.utils.common_functions.He_MS_lifetime(mass)[source]

Calculate the lifetime of He burning in a star.

Parameters:

mass (type) – Mass of star in solar masses

Returns:

He MS time duration in yr.

Return type:

float

class posydon.utils.common_functions.PchipInterpolator2(*args, positive=False, **kwargs)[source]

Bases: object

Interpolation class.

Initialize the interpolator.

posydon.utils.common_functions.Schwarzschild_Radius(M)[source]

Calculate the Schwarzschild Radius of BH with mass M.

Parameters:

M (float) – BH mass in Msun

Returns:

Schwarzschild Radius in solar radii

Return type:

float

posydon.utils.common_functions.beaming(binary)[source]

Calculate the geometrical beaming of a super-Eddington accreting source [1], [2].

Compute the super-Eddington isotropic-equivalent accretion rate and the beaming factor of a star. This does not change the intrinsic accretion onto the accretor and is an observational effect due to the inflated structure of the accretion disc that beams the outgoing X-ray emission. This is important for observing super-Eddington X-ray sources (e.g. ultraluminous X-ray sources). In case of a BH we are assuming that it has zero spin which is not a good approximation for high accretion rates.

Parameters:

binary (BinaryStar) – The binary object.

Returns:

The super-Eddington isotropic-equivalent accretion rate and beaming factor respcetively in solar units.

Return type:

list

References

[1]

Shakura, N. I. & Sunyaev, R. A. 1973, A&A, 24, 337

[2]

King A. R., 2008, MNRAS, 385, L113

posydon.utils.common_functions.bondi_hoyle(binary, accretor, donor, idx=-1, wind_disk_criteria=True, scheme='Hurley+2002')[source]

Calculate the Bondi-Hoyle accretion rate of a binary [1].

Parameters:
  • binary (BinaryStar) – The binary which accretion rate is required.

  • accretor (SingleStar) – The accretor in the binary.

  • donor (SingleStar) – The donor in the binary.

  • idx (int) – default: -1

  • wind_disk_criteria (bool) – default: True, see [5]

  • scheme (str) –

    There are different options:

    • ’Hurley+2002’ : following [3]

    • ’Kudritzki+2000’ : following [7]

Returns:

The Bondi-Hoyle accretion rate in solar units.

Return type:

float

Notes

An approximation is used for the accretion rate [2] and the wind velocity of the donor is moddeled as in [3], [6]. Also see [4].

References

[1]

Bondi, H., & Hoyle, F. 1944, MNRAS, 104, 273

[2]

Boffin, H. M. J., & Jorissen, A. 1988, A&A, 205, 155

[3] (1,2)

Hurley, J. R., Tout, C. A., & Pols, O. R. 2002, MNRAS, 329, 897

[4]

Belczynski, K., Kalogera, V., Rasio, F. A., et al. 2008, ApJS, 174, 223

[5]

Sen, K. ,Xu, X. -T., Langer, N., El Mellah, I. , Schurmann, C., & Quast, M., 2021, A&A

[6]

Sander A. A. C., Vink J. S., 2020, MNRAS, 499, 873

[7]

Kudritzki, R.-P., & Puls, J. 2000, ARA&A, 38, 613

posydon.utils.common_functions.calculate_H2recombination_energy(profile, tolerance=0.001)[source]

Compute the recombination energy of H2 per shell in erg.

Parameters:
  • profile (array) – Donor’s star profile from MESA

  • tolerance (float) – The tolerance of numerical difference in two floats when comparing and testing results.

Returns:

specific_donor_H2recomb_energy – recombination energy of H2 per shell in ergs

Return type:

array

posydon.utils.common_functions.calculate_Mejected_for_integrated_binding_energy(profile, Ebind_threshold, mc1_i, rc1_i, m1_i=0.0, radius1=0.0, factor_internal_energy=1.0, tolerance=0.001)[source]

Calculate the mass lost from the envelope for an energy budget of Ebind_threshold

Parameters:
  • profile (numpy.array) – Donor’s star profile from MESA

  • Ebind_threshold (float) – Orbital energy used from the spiral in to partial unbind the envelope. Positive We integrate from surface to calcualte the partial loss of mass during CE that merges.

  • factor_internal_energy (float) – The factor to multiply with internal energy to be taken into account when we calculate the binding energy of the enevelope

  • verbose (bool) – In case we want information about the CEE (the default is False).

Returns:

Ebind_i – The total binding energy of the envelope of the star

Return type:

float

posydon.utils.common_functions.calculate_Patton20_values_at_He_depl(star)[source]

Calculate the carbon core mass and abundance very close to ignition.

This is important for using the Patton+2020 SN prescription

Parameters:

star (SingleStar object holding the history of its attributes.)

Returns:

  • None

  • It updates the following values in the star object

  • co_core_mass_at_He_depletion (float) – co_core_mass at He core depletion (almost at the same time as carbon core ignition)

  • avg_c_in_c_core_at_He_depletion (float) – avg carbon abundance inside CO_core_mass at He core depletion (almost at the same time as carbon core ignition)

posydon.utils.common_functions.calculate_binding_energy(donor_mass, donor_radius, donor_dm, specific_internal_energy, ind_core, factor_internal_energy, verbose, tolerance=0.001)[source]

Calculate the total binding energy of the envelope of the star.

Parameters:
  • donor_mass (array) – Enclosed mass coordinate of the donor star from its profile.

  • donor_radius (array) – Radius coordinate of the donor star from its profile.

  • donor_dm (array) – Mass enclosed per shell in the donor star’s profile.

  • specific_internal_energy (array) – Specific internal energy of the donor star.

  • ind_core (int) – The value of the shell position of the core - envelope boundary, at the donor’s MESA profile

  • factor_internal_energy (float) – The factor to multiply with internal energy to be taken into account when we calculate the binding energy of the enevelope

  • verbose (bool) – In case we want information about the CEE (the default is False).

Returns:

Ebind_i – The total binding energy of the envelope of the star

Return type:

float

posydon.utils.common_functions.calculate_core_boundary(donor_mass, donor_star_state, profile, mc1_i=None, core_element_fraction_definition=None, CO_core_in_Hrich_star=False)[source]

Calculate the shell where the core is - envelope boundary.

Parameters:
  • donor_mass (array) – Profile column of enclosed mass of the star.

  • donor_star_state (string) – The POSYDON evolutionary state of the donor star

  • profile (numpy.array) – Donor’s star profile from MESA

  • mc1_i (float) – core mass and total mass of the donor star.

  • core_element_fraction_definition (float) – The mass fraction of the envelope abundant chemical element at the core-envelope boundary to derive the donor’s core mass from the profile

  • CO_core_in_Hrich_star (Bool) – This should be true if we want to calculate the boundary of CO core in a H-rich star (and not of the helium core).

Returns:

ind_core – The value of the cell position of the core - envelope boundary, at the donor’s MESA profile (for a profile that starts from the surface). More specifically, it returns the index of the first cell (starting from the surface), that the elements conditions for the core are met. - Returns 0 for a star that is all core - Returns -1 for a star that is all envelope.

Return type:

int

posydon.utils.common_functions.calculate_lambda_from_profile(profile, donor_star_state, m1_i=np.nan, radius1=np.nan, common_envelope_option_for_lambda=DEFAULT_CE_OPTION_FOR_LAMBDA, core_element_fraction_definition=0.1, ind_core=None, common_envelope_alpha_thermal=1.0, tolerance=0.001, CO_core_in_Hrich_star=False, verbose=False)[source]

Calculate common-enevelope lambda from the profile of a star.

We also pass a more accurate calculation of the donor core mass for the purposes of common-envelope evolution.

Parameters:
  • profile (numpy.array) – Donor’s star profile from MESA

  • donor_star_state (string) – The POSYDON evolutionary state of the donor star

  • common_envelope_option_for_lambda (str) –

    Available options: * ‘default_lambda’: using for lambda the constant value of common_envelope_lambda_default parameter * ‘lambda_from_profile_gravitational’: calculating the lambda parameter from the donor’s profile by using the gravitational binding energy from the surface to the core (needing “mass”, and “radius” as columns in the profile) * ‘lambda_from_profile_gravitational_plus_internal’: as above

    but taking into account a factor of common_envelope_alpha_thermal * internal energy too in the binding energy (needing also “energy” as column in the profile)

    • ’lambda_from_profile_gravitational_plus_internal_minus_recombination’

    as above but not taking into account the recombination energy in the internal energy (needing also “y_mass_fraction_He”, “x_mass_fraction_H” “neutral_fraction_H”, “neutral_fraction_He”, and “avg_charge_He” as column in the profile)

  • core_element_fraction_definition (float) – The mass fraction of the envelope abundant chemical element at the core-envelope boundary to derive the donor’s core mass from the profile.

  • ind_core (int) – The value of the cell position of the core - envelope boundary, at the donor’s MESA profile (for a profile that starts from the surface). More specifically, it returns the index of the first cell (starting from the surface), that the elements conditions for the core are met. It is 0 for a star that is all core and -1 for a star that is all envelope. If it is not given (None), it will be calculated inside the function.

  • common_envelope_alpha_thermal (float) – Used and explained depending on the common_envelope_option_for_lambda option above.

  • tolerance (float) – The tolerance of numerical difference in two floats when comparing and testing results.

  • CO_core_in_Hrich_star (Bool) – This should be true if we want to calculate the boundary of CO core in a H-rich star (and not of the helium core).

  • verbose (bool) – In case we want information about the CEE.

Returns:

  • lambda_CE (float) – lambda_CE for the envelope of the donor in CEE, calculated from profile

  • mc1_i (float) – More accurate calculation of the donor core mass for the purposes of CEE.

  • rc1_i (float) – More accurate calculation of the donor core radius for the purposes of CEE.

posydon.utils.common_functions.calculate_recombination_energy(profile, tolerance=0.001)[source]

Compute the recombination energy per shell in erg.

Parameters:
  • profile (numpy.array) – Donor’s star profile from MESA

  • tolerance (float) – The tolerance of numerical difference in two floats when comparing and testing results.

Returns:

specific_donor_recomb_energy – recombination energy per shell in ergs

Return type:

array

posydon.utils.common_functions.check_state_of_star(star, i=None, star_CO=False)[source]

Get the state of a SingleStar.

Parameters:
  • star (SingleStar) – The star for which the state will be computed.

  • i (integer) – Index of the model for which we want to calculate the state of the SingleStar object. Default = -1 (the final).

  • star_CO (bool) – True if we want to assume a compact object (WD/NS/BH). False if the state will be calculated by its attributes.

Returns:

state – state at of the star object at index i of the history.

Return type:

str

posydon.utils.common_functions.check_state_of_star_history_array(star, N=1, star_CO=False)[source]

Calculate the evolutionary states with an array of history data.

Parameters:
  • star (SingleStar) – The star for which the state will be computed.

  • N (int) – Number of history steps (from the end), to calculate the state.

  • star_CO (bool) – If True, assume it’s a compact object.

Returns:

The state(s) in a list.

Return type:

list of str

posydon.utils.common_functions.convert_metallicity_to_string(Z)[source]

Check if metallicity is supported by POSYDON v2.

posydon.utils.common_functions.cumulative_mass_transfer_flag(MT_cases, shift_cases=False)[source]

Get the cumulative MT string from a list of integer MT casses.

Parameters:
  • MT_cases (list of integers) – A list of MT cases.

  • shift_cases (bool) – Flag to shift non-physical cases like A1 after B1 will turn into B1.

Returns:

A string summarizing the mass transfer cases.

Return type:

str

posydon.utils.common_functions.cumulative_mass_transfer_numeric(MT_cases)[source]

Summarize the history of MT cases in a short list of integers.

Parameters:

MT_cases (array-like) – A list of the integer MT flags at sequential history steps.

Returns:

  • list of int – A shorter list of integer MT flags, following these rules: i. If undetermined MT at any step, it is indicated in the beginning

    (as a warning) and ignored later.

    1. If no RLO anywhere, then this is the only element in the returned list (or the second if undetermined MT at any step). Intermediate no-RLO phases (between RLO cases) are ignored.

    2. Consequent same cases are reported only once (e.g., A, A, A -> A.)

  • The end result is a list of integers indicating whether undetermined MT

  • anywhere, if no RLO everywhere, or “changes” of MT cases.

posydon.utils.common_functions.cumulative_mass_transfer_string(cumulative_integers)[source]

Convert a cumulative MT sequence to a string.

Parameters:

cumulative_integers (list of int) – Typically, the output of cumulative_mass_transfer_numeric.

Returns:

A summarization of the mass-tranfer cases in the form of a string, as opposed to the output of cumulative_mass_transfer_numeric (see this function to understand the rules of summarization). The character ? in the beginning of the string indicates undetermined MT case at some point of the evolution. no_RLO indicates no RLO at any evolutionary step. caseA, caseB, etc., denote the corresponding MT cases. When multiple cases are found, they are indicated only when the begin, and are combined using /. For example:

?no_RLO : undetermined MT at few steps, otherwise no RLO. caseA : case A MT only (possible no_RLO at some points). ?caseA/B : undetermined MT somewhere, then case A, then case B. caseA/B/A : case A, then B, and A again (although unphysical).

Return type:

str

posydon.utils.common_functions.eddington_limit(binary, idx=-1)[source]

Calculate the Eddington limit & radtiative efficiency of compact object.

Parameters:

binary (BinaryStar) – The binary object.

Returns:

The Eddington accretion limit and radiative efficiency in solar units.

Return type:

list

posydon.utils.common_functions.flip_stars(binary)[source]

Short summary.

Parameters:

binary (type) – Description of parameter binary.

Returns:

Description of returned object.

Return type:

type

posydon.utils.common_functions.get_binary_state_and_event_and_mt_case(binary, interpolation_class=None, i=None, verbose=False)[source]

Infer the binary state, event and mass transfer case.

Parameters:
  • binary (BinaryStar) – The POSYDON binary star.

  • i (int) – The index of the history in which we want to calculate the state of the binary object. Default (None) is the current state.

Returns:

  • binary_state (str) – One of ‘detached’, ‘contact’, ‘RLO1’ and ‘RLO2’.

  • binary_event (str) – Options are ‘oRLO1’ or ‘oRLO2’ (onset of RLO, the start of RLO), ‘oCE1’, ‘oCE2’, ‘oDoubleCE1’, ‘oDoubleCE2’, ‘CC1’, ‘CC2’.

  • mass transfer case (str) – ‘caseA’, ‘caseB’, etc.

Examples

If ‘detached’ then returns [‘detached’, None, None].

If ‘contact’ then returns [‘contact’, None] or [‘oCE1’, ‘oDoubleCE1’] or [‘oDoubleCE2’, None].

If RLO then returns either [‘RLO1’, None, ‘caseXX’] or [‘RLO2’, None, ‘caseXX’] or maybe [‘RLO2’, ‘oRLO2’, ‘caseXX’].

posydon.utils.common_functions.get_binary_state_and_event_and_mt_case_array(binary, N=None, verbose=False)[source]

Calculate the evolutionary states with an array of history data.

Parameters:
  • binary (POSYDON BinaryStar object)

  • N (array) – index of the history in which we want to calculate the state of the SingleStar object

Returns:

  • binary_state (str(see in check_state_of_star))

  • binary_event

  • MT_case

posydon.utils.common_functions.get_i_He_depl(history)[source]

Get the index of He depletion in the history

Parameters:

history (numpy-array) – Stellar history from MESA

Returns:

index of He depletion (-1 if no He depletion is found)

Return type:

int

posydon.utils.common_functions.get_internal_energy_from_profile(common_envelope_option_for_lambda, profile, tolerance=0.001)[source]

Calculate the specific internal energy per shell of the donor.

Parameters:
  • common_envelope_option_for_lambda (str) –

    Available options: * ‘default_lambda’: using for lambda the constant value of common_envelope_lambda_default parameter * ‘lambda_from_profile_gravitational’: calculating the lambda parameter from the donor’s profile by using the gravitational binding energy from the surface to the core (needing “mass”, and “radius” as columns in the profile) * ‘lambda_from_profile_gravitational_plus_internal’: as above

    but taking into account a factor of common_envelope_alpha_thermal * internal energy too in the binding energy (needing also “energy” as column in the profile)

    • ’lambda_from_profile_gravitational_plus_internal_minus_recombination’

    as above but not taking into account the recombination energy in the internal energy (needing also “y_mass_fraction_He”, “x_mass_fraction_H” “neutral_fraction_H”, “neutral_fraction_He”, and “avg_charge_He” as column in the profile)

  • profile (numpy.array) – Donor’s star profile from MESA

  • tolerance (float) – The tolerance of numerical difference in two floats when comparing and testing results.

Returns:

specific_donor_internal_energy – Value of the specific internal energy per shell of the donor

Return type:

array

posydon.utils.common_functions.get_mass_radius_dm_from_profile(profile, m1_i=0.0, radius1=0.0, tolerance=0.001)[source]

TODO: add summary.

Reads and returns the profile columms of enclosed mass radius and mass per shell of the donor star from a MESA profile.

Parameters:
  • m1_i (float) – m1_i is the value passed from the singlestar object, for testing purposes only

  • radius1 (float) – radius1 is the value passed from the singlestar object, for testing purposes only

  • profile (numpy.array) – Donor’s star profile from MESA

  • tolerance (float) – The tolerance of numerical difference in two floats when comparing and testing results.

Returns:

  • donor_mass (array) – Profile column of enclosed mass of the star.

  • donor_radius (array) – Profile column of the radius the star.

  • donor_dm (array) – Profile mass per shell of the star.

posydon.utils.common_functions.histogram_sampler(x_edges, y, size=1)[source]

Sample from an empirical PDF represented by a histogram.

Parameters:
  • x_edges (array-like) – The edges of the bins of the histrogram.

  • y (array-like) – The counts (or a scaled version of them) of the histogram.

  • size (int) – Number of random values to produce.

Returns:

The random sample.

Return type:

array

posydon.utils.common_functions.infer_mass_transfer_case(rl_relative_overflow, lg_mtransfer_rate, donor_state, verbose=False)[source]

Infer the mass-transfer case of a given star.

Parameters:
  • rl_relative_overflow (float)

  • lg_mtransfer_rate (float)

  • donor_state (str) – Values of star parameters at a specific step.

Returns:

The mass-transfer case integer flag.

Return type:

int

posydon.utils.common_functions.infer_star_state(star_mass=None, surface_h1=None, center_h1=None, center_he4=None, center_c12=None, log_LH=None, log_LHe=None, log_Lnuc=None, star_CO=False)[source]

Infer the star state (corresponding to termination flags 2 and 3).

posydon.utils.common_functions.initialize_empty_array(arr)[source]

Initialize an empty record array with NaNs and empty strings.

posydon.utils.common_functions.inspiral_timescale_from_orbital_period(star1_mass, star2_mass, orbital_period, eccentricity)[source]

Compute the timescale of GW inspiral using the orbital period.

Based on [1]:

https://journals.aps.org/pr/abstract/10.1103/PhysRev.136.B1224

Parameters:
  • star1_mass (float) – Mass of star 1 in Msun.

  • star2_mass (float) – Mass of star 2 in Msun.

  • orbital_separation (type) – Binary separation in Rsun.

  • eccentricity (type) – Eccentricity of the binary orbit. Must be 0 <= ecc <1.

Returns:

The inspiral time scale of the two black holes in Myr.

Return type:

float

References

[1]

Peters 1964 Phys. Rev. 136, B1224

posydon.utils.common_functions.inspiral_timescale_from_separation(star1_mass, star2_mass, separation, eccentricity)[source]

Compute the timescale of GW inspiral using the orbital separation.

Based on [1]:

https://journals.aps.org/pr/abstract/10.1103/PhysRev.136.B1224

Parameters:
  • star1_mass (float) – Mass of star 1 in Msun.

  • star2_mass (float) – Mass of star 2 in Msun.

  • separation (type) – Binary separation in Rsun.

  • eccentricity (type) – Eccentricity of the binary orbit. Must be 0 <= ecc <1.

Returns:

The inspiral time scale of the two black holes.

Return type:

float

References

[1]

Peters 1964 Phys. Rev. 136, B1224

posydon.utils.common_functions.inverse_sampler(x, y, size=1)[source]

Sample from a PDF using the inverse-sampling method.

Parameters:
  • x (array-like) – The x-axis coordinates of the points where the PDF is defined.

  • y (array-like) – The probablity density at x (or a scaled version of it).

  • size (int) – Number of samples to generate.

Returns:

The sample drawn from the PDF.

Return type:

array

posydon.utils.common_functions.is_number(s)[source]

Check if the input can be converted to a float.

posydon.utils.common_functions.linear_interpolation_between_two_cells(array_y, array_x, x_target, top=None, bot=None, verbose=False)[source]

Interpolate quantities between two star profile shells.

posydon.utils.common_functions.orbital_period_from_separation(separation, m1, m2)[source]

Apply the Third Kepler law.

Parameters:
  • separation (float) – Orbital separation (semi-major axis) in Rsun.

  • m1 (float) – Mass of one of the stars in solar units.

  • m2 (type) – Mass of the other star in solar units.

Returns:

The orbital period in days.

Return type:

float

posydon.utils.common_functions.orbital_separation_from_period(period_days, m1_solar, m2_solar)[source]

Apply the Third Kepler law.

Parameters:
  • period_days (float) – Orbital period in days.

  • m1_solar (float) – Mass of the one of the stars, in solar units.

  • m2_solar (float) – Mass of the other star, in solar units.

Returns:

The separation of the binary in solar radii.

Return type:

float

posydon.utils.common_functions.period_change_stabe_MT(period_i, Mdon_i, Mdon_f, Macc_i, alpha=0.0, beta=0.0)[source]

Change the binary period after a semi-detahed stable MT phase.

Calculated in Sorensen, Fragos et al. 2017A&A…597A..12S. Note that MT efficiencies are assumed constant (i.e., not time-dependent) throughout the MT phase.

Parameters:
  • period_i (float) – Initial period

  • Mdon_i (float) – Initial donor mass

  • Mdon_f (float) – Final donor mass (should be in the same unit’s of Mdon_i)

  • Mdon_i – Initial accretor’s mass (should be in the same unit’s of Mdon_i)

  • alpha (float [0-1]) – Fraction of DM_don (= Mdon_i - Mdon_f) from the donor, lost from the donor’s vicinity

  • beta (float [0-1]) – Fraction of Mdot from the L1 point (= (1-alpha)*DM_don), lost from the accretor’s vicinity. The final accreted rate is (1-beta)(1-alpha)*DM_don

Returns:

period_f – final period at the end of stable MT, in the same units as period_i

Return type:

float

posydon.utils.common_functions.period_evol_wind_loss(M_current, M_init, Mcomp, P_init)[source]

Calculate analytically the period widening due to wind mass loss [1].

Parameters:
  • M_current (float) – Current mass of the mass losing star (Msun)

  • M_init (float) – Initial mass of the mass losing star when the calculation starts (Msun)

  • Mcomp (float) – (Constant) mass of the companion star (Msun)

  • P_init (float) – Initial binary period when the calculation starts (days)

Returns:

Current binary period in days

Return type:

float

References

[1]

Tauris, T. M., & van den Heuvel, E. 2006, Compact stellar X-ray sources, 1, 623

posydon.utils.common_functions.profile_recomb_energy(x_mass_fraction_H, y_mass_fraction_He, frac_HII, frac_HeII, frac_HeIII)[source]

Calculate the recombination energy per shell.

Parameters:
  • x_mass_fraction_H (array) – Mass fraction of H per shell

  • y_mass_fraction_He (array) – Mass fraction of He per shell.

  • frac_HII (array) – Fraction of single ionized H per shell.

  • frac_HeII (array) – Fraction of single ionized He per shell.

  • frac_HeIII (array) – Fraction of double ionized He per shell.

Returns:

recomb_energy – recombination energy per shell in ergs (same dimension as x_mass_fraction_H and y_mass_fraction_He)

Return type:

1D numpy.arrays

posydon.utils.common_functions.read_histogram_from_file(path)[source]

Read a histogram from a CSV file.

The expected format is:

# comment line x[0], x[1], …, x[n], x[n+1] y[0], y[1], …, y[n]

where # denotes a comment line (also empty lines are ignored), and n is the number of bins (notice that the first line contains n+1 elements.)

Usage: bin_edges, bin_counts = read_histogram_from_file(“a_histogram.csv”).

Parameters:

path (str) – The path of the CSV file containing the histogram information.

Returns:

The bin edges and bin counts of the histogram.

Return type:

list of arrays

posydon.utils.common_functions.rejection_sampler(x=None, y=None, size=1, x_lim=None, pdf=None)[source]

Generate a sample from a 1d PDF using the acceptance-rejection method.

Parameters:
  • x (array_like) – The x-values of the PDF.

  • y (array_like) – The y-values of the PDF.

  • size (int) – The number of random numbers to generate.

  • x_lim (array float) – The boundary where the pdf function is defined if passed as pdf.

  • pdf (func) – The pdf function

Returns:

An array with size random numbers generated from the PDF.

Return type:

ndarray

posydon.utils.common_functions.roche_lobe_radius(m1, m2, a_orb=1)[source]

Approximate the Roche lobe radius from [1].

Parameters:
  • m1 (float, ndarray of floats) – the mass of the star for which we calculate the Roche lobe

  • m2 (float, ndarray of floats) – the mass of the companion star

  • a_orb (float, ndarray of floats) – Orbital separation. The return value will have the same unit.

Returns:

Roche lobe radius in similar units as a_orb

Return type:

float, ndarray of floats

References

[1]

Eggleton, P. P. 1983, ApJ, 268, 368

posydon.utils.common_functions.rotate(axis, angle)[source]
Generate rotation matrix to rotate a vector about an arbitrary axis

by a given angle

Parameters:
  • axis (array of length 3) – Axis to rotate about

  • angle (float) – Angle, in radians, through which to rotate about axis

Returns:

rotation_matrix – Array such that rotation_matrix.dot(vector) rotates vector about the given axis by the given angle

Return type:

3x3 array

posydon.utils.common_functions.rzams(m, z=0.02, Zsun=0.02)[source]

Evaluate the zero age main sequence radius [1].

Parameters:
  • m (array_like) – The masses of the stars in Msun.

  • z (float) – The metallicity of the star.

Returns:

Array of same size as m containing the ZAMS radii of the stars (Rsun)

Return type:

ndarray

References

[1]

Tout C. A., Pols O. R., Eggleton P. P., Han Z., 1996, MNRAS, 281, 257

posydon.utils.common_functions.separation_evol_wind_loss(M_current, M_init, Mcomp, A_init)[source]

Calculate analytically the separation widening due to wind mass loss [1].

Parameters:
  • M_current (float) – Current mass of the mass losing star (Msun)

  • M_init (float) – Initial mass of the mass losing star when the calculation starts (Msun)

  • Mcomp (float) – (Constant) mass of the companion star (Msun)

  • A_init (float) – Initial binary separation when the calculation starts (Rsun)

Returns:

Current binary separation in Rsun

Return type:

float

References

[1]

Tauris, T. M., & van den Heuvel, E. 2006, Compact stellar X-ray sources, 1, 623.

posydon.utils.common_functions.set_binary_to_failed(binary)[source]

Set the properties of the binary to indicate that it has failed.

Parameters:

binary (BinaryStar) – The binary to set to failed.

posydon.utils.common_functions.spin_stable_mass_transfer(spin_i, star_mass_preMT, star_mass_postMT)[source]

Calculate the spin of an accreting BH under stable mass transfer.

Based on Thorne 1974 eq. 2a.

posydon.utils.common_functions.stefan_boltzmann_law(L, R)[source]

Compute the effective temperature give the luminosity and radius.

posydon.utils.configfile

Module for providing support for configuration files.

The ConfigClass loads, edits and saves configuration files in JSON format. The data are encapsulated in a single dictionary mapping the variable names (keys) to their values.

ConfigFile is an alternative to the configparse module in Python’s standard libray. While configparser can handle only string values and requires using sections (as in .ini files), ConfigFile is simpler and faster to use, while permits keys and values of any type that a Python dictionary permits.

As it relies on the Python json module, an internal function is called when a values is not known to json, e.g. numpy arrays.

Finally, the function parse_inifile is defined to help reading .ini files.

Examples

  1. Saving a dictionary:

    D = {“username”: “konstantinos”,

    “nodes”: [1, 5, 3], “memory”: 1024, “code”: 42, “std.out”: “/data/output/std.out”}

    config_file = ConfigFile(“tmp.cfg”) config_file.update(D) config_file.save()

    OR

    my_config_file = ConfigFile() my_config_file.update(D) my_config_file.save(filename)

  2. Loading and printing configuration:

    config = ConfigFile(filename) print(“Loaded a config file with {} entries.”.format(len(config))) print(“The code is”, config[“code”]) print(config)

  1. Altering entries (and creating if non-existing):

    config[“machine”] = “supercomputer” config[“code”] = 24 config[“H0 and error”] = (67.8, 0.9)

  1. Loading configuration from multiple files:

    config = CongfigFile(“config1.json”) config.load(“config2.json”)

    OR

    config.load(“config1.json”) config.load(“config2.json”)

    If the two loaded configuration files have common keys, then an Exception will occur. To allow updates, e.g. in the case of default configuration and user configuration overriding the former, then:

    config = ConfigFile(“default.cfg”) config.load(“user.cfg”, can_update=True)

  1. Iterating entries:

    config = ConfigFile(“my_conf.json”)

    print(“All configuration items:”) for key in config:

    print(” {}: {}”.format(key, config[key]))

    print(“Ok, I’ll repeat that…:”) for key, value in config.items():

    print(” {}: {}”.format(key, value))

class posydon.utils.configfile.ConfigFile(path=None)[source]

Bases: object

Class handling input, process and output of configurations.

Initialize a ConfigFile with or without a path.

deepcopy()[source]

Make a deep copy of the object.

items()[source]

Return (key, value) tuples of the configuration dictionary.

keys()[source]

Return the keys of the configuration dictionary.

load(path=None, can_update=False)[source]

Load the entries from a JSON file containing a dictionary.

Parameters:
  • path (str or None) – The path of the JSON file. If None it will use the path which which the ConfigFile instance was initialized.

  • can_update (bool) – If True, if a key already exists, it will get the new value. If False, an Exception is thrown.

save(path=None, overwrite=True)[source]

Save the configuration entries into a JSON file.

Parameters:
  • path (str or None) – Where to save. If None, save to the path from the initialization.

  • overwrite (bool) – If True, it will overwrite if the path exists.

update(dictionary)[source]

Create new or update entries from an external dictionary.

values()[source]

Return the values of the configuration dictionary.

class posydon.utils.configfile.VariableKey(item)[source]

Bases: object

A dictionary key which is a variable.

@ivar item: The variable AST object.

Construct the object by giving a name to it.

posydon.utils.configfile.parse_inifile(inifile)[source]

Parse an inifile and return dicts of each section.

posydon.utils.constants

Mathematical and physical constants (in cgs).

Using the 2010 CODATA recommended values of the physical constants:

posydon.utils.data_download

Functions handling the download of data from Zenodo.

class posydon.utils.data_download.ProgressBar[source]

Bases: object

posydon.utils.data_download.data_download(file=file, MD5_check=True, verbose=False)[source]

Download data files from Zenodo if they do not exist.

Parameters:

file (string) –

  • Filename of the data file to be downloaded

MD5_checkboolean
  • Use the MD5 checksum to make sure data is not corrupted

verboseboolean
  • verbose output

posydon.utils.gridutils

Various utility functions used for the manipulating grid data.

posydon.utils.gridutils.T_merger_P(P, m1, m2)[source]

Merger time given initial orbital period and masses of binary.

Parameters:
  • P (float) – Orbital period (days).

  • m1 (float) – Mass of first star (Msun).

  • m2 (float) – Mass of second star (Msun).

Returns:

Merger time (Gyr)

Return type:

float

posydon.utils.gridutils.T_merger_a(a, m1, m2)[source]

Merger time given initial orbital separation and masses of binary.

Parameters:
  • a (float) – Orbital separation (Rsun).

  • m1 (float) – Mass of first star (Msun).

  • m2 (float) – Mass of second star (Msun).

Returns:

Merger time (Gyr) following Peters (1964), eq. (5.10).

Return type:

float

posydon.utils.gridutils.add_field(a, descr)[source]

Return a new array that is like a, but has additional fields.

The contents of a are copied over to the appropriate fields in the new array, whereas the new fields are uninitialized. The arguments are not modified.

Parameters:
  • a (structured numpy array) – The base array.

  • descr (str) – A numpy type description of the new fields.

Returns:

Description of returned object.

Return type:

type

Example

>>> sa = numpy.array([(1, 'Foo'), (2, 'Bar')],
                     dtype=[('id', int), ('name', 'S3')])
>>> sa.dtype.descr == numpy.dtype([('id', int), ('name', 'S3')])
True
>>> sb = add_field(sa, [('score', float)])
>>> sb.dtype.descr == numpy.dtype([('id', int), ('name', 'S3'),
                                   ('score', float)])
True
>>> numpy.all(sa['id'] == sb['id'])
True
>>> numpy.all(sa['name'] == sb['name'])
True
posydon.utils.gridutils.beta_gw(m1, m2)[source]

Evaluate the “beta” (equation 5.9) from Peters (1964).

Parameters:
  • m1 (float) – Mass of the first star.

  • m2 (type) – Mass of the second star.

Returns:

Peters’ beta in cgs units.

Return type:

float

posydon.utils.gridutils.clean_inlist_file(inlist, **kwargs)[source]

Get dictionary of possible parameters/values from the default inlist.

Parameters:
  • inlist (str) – Path to inlist file.

  • **kwargs (dict) – TODO

Returns:

Dictionary of parameters and values from inlist.

Return type:

dict

posydon.utils.gridutils.convert_output_to_table(output_file, binary_history_file=None, star1_history_file=None, star2_history_file=None, column_names=['result', 'CE_flag', 'M_1f(Msun)', 'M_2f(Msun)', 'Porb_f(d)', 'tmerge(Gyr)', 'log_L_1', 'log_T_1', 'He_core_1(Msun)', 'C_core_1(Msun)', 'log_L_2', 'log_T_2', 'He_core_2(Msun)', 'C_core_2(Msun)'])[source]

Convert output of a run, to a pandas dataframe.

Note that this function also works with .gz files.

Parameters:
  • output_file (str) – Path to MESA output file.

  • binary_history_file (str) – Path to binary history data.

  • star1_history_file (str) – Path to history data for star1.

  • star2_history_file (str) – Path to history data for star1.

  • column_names (list of str) – Which columns to return.

Returns:

The table containing the requested columns from the run’s histories.

Return type:

pandas dataframe

posydon.utils.gridutils.find_index_nearest_neighbour(array, value)[source]

Find the index of array closest to the value.

posydon.utils.gridutils.find_nearest(val, array)[source]

Find the element of array closest to the value val.

posydon.utils.gridutils.fix_He_core(history)[source]

Make He core mass/radius at least equal to CO core mass/radius.

posydon.utils.gridutils.get_cell_edges(grid_x, grid_y)[source]

Return the edges of grid cells to be used for plotting with pcolormesh.

Parameters:
  • grid_x (array) – Center values of grid cells for X.

  • grid_y (array) – Center values of grid cells for Y.

Returns:

  • array – X grid values.

  • array – Y grid values.

posydon.utils.gridutils.get_final_proposed_points(proposed_x, grid_x, proposed_y, grid_y)[source]

Map proposed simulation points to the center of a correspoding cell.

Only one mapped value is returned if more than one proposed point falls within one cell.

Parameters:
  • proposed_x (array) – Proposed points for X.

  • grid_x (array) – The values of X at the center of the grid cells.

  • proposed_y (array) – Proposed points for Y.

  • grid_y (type) – The values of Y at the center of the grid cells.

Returns:

  • array – Mapped X values.

  • array – Mapped Y values.

posydon.utils.gridutils.get_new_grid_name(path, compression, create_missing_directories=False)[source]

Get the name of a new grid slice based on the path and the compression.

Parameters:
  • path (str) – Path to grid slice data.

  • compression (str) – Compression value. (Directory to put the new grid slice in.)

  • create_missing_directories (bool) – Flag to create missing directories.

Returns:

File name for the new grid slice.

Return type:

grid_output

posydon.utils.gridutils.join_lists(A, B)[source]

Make a joint list of A and B without repetitions and keeping the order.

Parameters:
  • A (iterable) – The baseline list to be extended.

  • B (iterable) – The second list from which additional elements will be appened.

Returns:

The joint list by merging A and B.

Return type:

list

posydon.utils.gridutils.kepler3_a(P, m1, m2)[source]

Calculate the semimajor axis of a binary from its period and masses.

Parameters:
  • P (float) – Orbital period (days).

  • m1 (float) – Mass of first star.

  • m2 (type) – Mass of second star.

Returns:

Semi-major axis (Rsun) using Kepler’s third law.

Return type:

float

posydon.utils.gridutils.read_EEP_data_file(path, columns)[source]

Read an EEP file (can be .gz) - similar to read_MESA_data_file().

posydon.utils.gridutils.read_MESA_data_file(path, columns)[source]

Read specific columns from a MESA output file to an array.

Note that this function also works with .gz files.

Parameters:
  • path (str) – The path to the file.

  • columns (list of strings) – The list of names of the columns to be returned.

Returns:

The array containing the MESA data, or None if path was None.

Return type:

array or None

posydon.utils.ignorereason

Class for handling ignore reasons when creating new grids.

class posydon.utils.ignorereason.IgnoreReason[source]

Bases: object

Class for handling ignore reasons when creating new grids.

posydon.utils.limits_thresholds

Constant limits and thresholds.

posydon.utils.posydonerror

The POSYDON exception class and subclasses for more specific errors.

exception posydon.utils.posydonerror.FlowError(message='', objects=None)[source]

Bases: POSYDONError

POSYDON error specific for binary evolution flow errors.

General POSYDON exception.

Parameters:
  • message (str) – POSYDONError message.

  • objects (None or list of objects.) – A list of accompanied objects (or None if not set), that will be handled differently when str method is used. This error can only accept BinaryStar, SingleStar, or a list of each.

exception posydon.utils.posydonerror.GridError(message='', objects=None)[source]

Bases: POSYDONError

POSYDON error specific for PSyGrid operations.

General POSYDON exception.

Parameters:
  • message (str) – POSYDONError message.

  • objects (None or list of objects.) – A list of accompanied objects (or None if not set), that will be handled differently when str method is used. This error can only accept BinaryStar, SingleStar, or a list of each.

exception posydon.utils.posydonerror.MatchingError(message='', objects=None)[source]

Bases: POSYDONError

POSYDON error specific for matching stars to single grid during the detached.

General POSYDON exception.

Parameters:
  • message (str) – POSYDONError message.

  • objects (None or list of objects.) – A list of accompanied objects (or None if not set), that will be handled differently when str method is used. This error can only accept BinaryStar, SingleStar, or a list of each.

exception posydon.utils.posydonerror.ModelError(message='', objects=None)[source]

Bases: POSYDONError

POSYDON error specific for when a binary FAILS due to limitations of physics modeling assumptions.

General POSYDON exception.

Parameters:
  • message (str) – POSYDONError message.

  • objects (None or list of objects.) – A list of accompanied objects (or None if not set), that will be handled differently when str method is used. This error can only accept BinaryStar, SingleStar, or a list of each.

exception posydon.utils.posydonerror.NumericalError(message='', objects=None)[source]

Bases: POSYDONError

POSYDON error specific for when a binary FAILS due to limitations of numerical methods.

General POSYDON exception.

Parameters:
  • message (str) – POSYDONError message.

  • objects (None or list of objects.) – A list of accompanied objects (or None if not set), that will be handled differently when str method is used. This error can only accept BinaryStar, SingleStar, or a list of each.

exception posydon.utils.posydonerror.POSYDONError(message='', objects=None)[source]

Bases: Exception

General POSYDON exception class.

General POSYDON exception.

Parameters:
  • message (str) – POSYDONError message.

  • objects (None or list of objects.) – A list of accompanied objects (or None if not set), that will be handled differently when str method is used. This error can only accept BinaryStar, SingleStar, or a list of each.

posydon.utils.posydonerror.initial_condition_message(binary, ini_params=None)[source]

posydon.utils.posydonwarning

The POSYDON warnings class and subclasses for more detailed warning handling.

Mainly the function Pwarn should be called to submit a warning, which behaves like warnings.warn. All the defined POSYDON warnings are collected in _POSYDONWarning_subclasses for those will be checked automatically, when using Pwarn. The functions SetPOSYDONWarnings, AllPOSYDONWarnings, and NoPOSYDONWarnings allow to change the filter settings. It should be noted, that we register POSYDON warnings by category, filename, and lineno. We do not include the warning text in the identifier of a new warning for the default filter, hence it behaves different to python warnings. But we record how often each warning is issued with your identifier. Those records can be requested via get_stats and printed via print_stats. To catch warnings we have the context manager class Catch_POSYDON_Warnings. It will record the warnings and issue them at the end of the context. To not issue the recorded warnings, simply use the reset_cache function of Catch_POSYDON_Warnings before the end of the context. You can get the list of the caught warnings via get_cache. Here an example, where the argument True of get_cache, will empty the list of caught warnings after it is copy to be returned:

with Catch_POSYDON_Warnings() as cpw:

… Pwarn(“Test”, “POSYDONWarning”) … print(cpw.get_cache(True))

posydon.utils.posydonwarning.AllPOSYDONWarnings(category=POSYDONWarning)[source]

Switch the warnings filter to always for POSYDON warnings.

Parameters:

category (str or a warnings category class (default: POSYDONWarning)) – A string, which will be converted into a POSYDONWarning class.

exception posydon.utils.posydonwarning.ApproximationWarning(message='')[source]

Bases: POSYDONWarning

Warning that a physical approximation was used during binary evolution.

exception posydon.utils.posydonwarning.BinaryParsingWarning(message='')[source]

Bases: POSYDONWarning

Warnings related to parsing of binaries.

class posydon.utils.posydonwarning.Catch_POSYDON_Warnings(catch_warnings=True, record=True, filter_first=True, own_registry=False, use_python_catch=False)[source]

Bases: object

Context manager class to catch POSYDON warnings.

Constructor of the object.

Parameters:
  • catch_warnings (bool (default: False)) – Determines, whether warnings are caught.

  • record (bool (default: True)) – Determines, whether warnings are recorded.

  • filter_first (bool (default: True)) – Determines, whether warnings are filtered before recorded or discarded.

  • own_registry (bool (default: False)) – Determines, whether the global POSYDON warnings registry should be used or an own one only valid within the context.

  • use_python_catch (bool (default: False)) – If enabled, it put the python catch_warnings on top of the POSYDON catches. This brings all the drawbacks of the standard catching, hence it is strongly recommended to be not used (properly written code will not contain any use case for this option, hence it is only for backward compatibility.).

exception posydon.utils.posydonwarning.ClassificationWarning(message='')[source]

Bases: POSYDONWarning

Warnings related to classification during binary evolution.

exception posydon.utils.posydonwarning.EvolutionWarning(message='')[source]

Bases: POSYDONWarning

Warning that something unexpeted occurred during the binary evolution, but the evolution is able to continue (binary did not fail).

exception posydon.utils.posydonwarning.InappropriateValueWarning(message='')[source]

Bases: POSYDONWarning

Warnings that a strange value is used.

exception posydon.utils.posydonwarning.IncompletenessWarning(message='')[source]

Bases: POSYDONWarning

Warnings when not all tasks could be done.

exception posydon.utils.posydonwarning.InterpolationWarning(message='')[source]

Bases: POSYDONWarning

Warnings related to interpolation during binary evolution.

exception posydon.utils.posydonwarning.MissingFilesWarning(message='')[source]

Bases: POSYDONWarning

Warnings related to missing files.

posydon.utils.posydonwarning.NoPOSYDONWarnings(category=POSYDONWarning)[source]

Switch the warnings filter to ignore for POSYDON warnings.

Parameters:

category (str or a warnings category class (default: POSYDONWarning)) – A string, which will be converted into a POSYDONWarning class.

exception posydon.utils.posydonwarning.OverwriteWarning(message='')[source]

Bases: POSYDONWarning

Warning that a data will get overwritten.

exception posydon.utils.posydonwarning.POSYDONWarning(message='')[source]

Bases: Warning

General POSYDON warning class.

posydon.utils.posydonwarning.Pwarn(message, category=None, stacklevel=2, **kwargs)[source]

Issueing a warning via warnings.warn.

Parameters:
  • message (str) – The message printed in the warning.

  • category (str or a warnings category class (default: None)) – A string, which will be converted into a POSYDONWarning class.

  • stacklevel (int (default: 2)) – The stack level passed to warnings.warn, defaults to 2.

  • **kwargs (dict (optional)) – Dictionary containing extra options passed to warnings.warn.

exception posydon.utils.posydonwarning.ReplaceValueWarning(message='')[source]

Bases: POSYDONWarning

Warning that a value got replaced.

posydon.utils.posydonwarning.SetPOSYDONWarnings(action='default', category=POSYDONWarning, **kwargs)[source]

Add the warnings filter for POSYDON warnings.

Parameters:
  • action (str (default: "default")) – The behaviour for those warnings. Should be one out of “default”, “error”, “ignore”, “always”, “module”, or “once”

  • category (str or a warnings category class (default: POSYDONWarning)) – A string, which will be converted into a POSYDONWarning class.

  • **kwargs (dict (optional)) – Dictionary containing extra options passed to warnings.filterwarnings.

exception posydon.utils.posydonwarning.UnsupportedModelWarning(message='')[source]

Bases: POSYDONWarning

Warnings related to selecting a model that is not supported.

posydon.utils.posydonwarning.get_stats()[source]

Return the statistics of the POSYDON warnings.

posydon.utils.posydonwarning.print_stats()[source]

Prints the statistics of the POSYDON warnings.