posydon.binary_evol

posydon.binary_evol.binarystar

The binary object describes current and past state of the binary.

The binary object is composed of two star objects and contains the current and past states of the binary. Only parameters in the BINARYPROPERTIES list are stored in the history.

The current parameter value of the star object is accessed as, e.g. binary.orbital_period while its past history with binary.orbital_period_history.

The two stars are accessed as, e.g. binary.star_1.mass while their past history with binary.star_1.mass_history.

class posydon.binary_evol.binarystar.BinaryStar(star_1=None, star_2=None, index=None, properties=None, **binary_kwargs)[source]

Bases: object

A class containing the state and history of a stellar binary.

Initialize a binary star.

Parameters:
  • properties (SimulationProperties) – Instance of the SimulationProperties class (default: None)

  • star_1 (SingleStar) – The first star of the binary.

  • star_2 (Star) – The second star of the binary.

  • **binary_kwargs (dictionary) – List of initialization parameters for a binary

append_state()[source]

Update the history of the binaries’ properties.

check_who_exists()[source]

Check and store which binary components exist (are not

massless remnants). This sets additional class attributes

self.non_existent_companion with the following values:
-1 if neither star exists

0 if both stars exist 1 if Star 2 exists, Star 1 is a massless remnant 2 if Star 1 exists, Star 2 is a massless remnant

and

self.companion_1_exists = True if Star 1 exists (is not

None or a massless remnant)

self.companion_2_exists = True if Star 2 exists (is not

None or a massless remnant)

evolve()[source]

Evolve a binary from start to finish.

classmethod from_df(dataframe, **kwargs)[source]

Convert a binary from a pandas DataFrame to BinaryStar instance.

Parameters:
  • dataframe (Pandas DataFrame) – data to turn into a BinaryStar instance.

  • index (int, optional) – Sets the binary index.

  • extra_columns (dict, optional) – Column names to be added directly to binary not in BINARYPROPERTIES.

Return type:

New instance of BinaryStar

classmethod from_oneline_df(oneline_df, **kwargs)[source]

Convert a oneline DataFrame into a BinaryStar.

The oneline DataFrame is expected to have initial-final values from history and any individual values that don’t have histories.

Parameters:
  • oneline_df (DataFrame) – A oneline DataFrame describing a binary.

  • index (int, None) – Binary index

  • extra_columns (dict) – Names of any extra history columns not inlcuded in BINARYPROPERTIES

Return type:

A new BinaryStar instance.

static from_run(run, history=False, profiles=False)[source]

Create a BinaryStar object from a PSyGrid run.

get_next_step()[source]

Get the next step class object based on the current total state.

get_next_step_name()[source]

Return the name of the next step based on the current total state.

get_total_state()[source]

Return the total state of the binary (star1.state, star2.state, binary.state, binary.event).

initial_condition_message(ini_params=None)[source]

Generate a message with the initial conditions.

Parameters:

ini_params (None or iterable of str) – If None take the initial conditions from the binary, otherwise add each item of it to the message.

Returns:

The message with the binary initial conditions.

Return type:

string

reset(properties=None)[source]

Reset the binary to its ZAMS state.

Parameters:

properties (SimulationProperties) – Instance of the SimulationProperties class (default: None)

restore(i=0)[source]

Restore the BinaryStar() object to its i-th state, keeping the binary history before the i-th state.

Parameters:

i (int) – The index of the binary object history to reset the binary to. By default 0, i.e. the star will be restored to its initial state.

run_step()[source]

Evolve the binary through one evolutionary step.

switch_star()[source]

Switch stars.

to_df(**kwargs)[source]

Return history parameters from the binary in a DataFrame.

Includes star 1 and 2 (S1, S2) data and an extra column ‘binary_index’.

Parameters:
  • extra_columns (dict( 'name':dtype, .... )) – Extra binary parameters to return in DataFrame that are not included in BINARYPROPERTIES. All columns must have an associated pandas data type. Can be used in combination with only_select_columns. Assumes names have no suffix.

  • ignore_columns (list) – Names of binary parameters to ignore. Assumes names have _history suffix.

  • only_select_columns (list) – Names of the only columns to include. Assumes names have _history suffix. Can be used in combination with extra_columns.

  • null_value (float) – Replace all None values with something else (for saving). Default is np.nan.

  • include_S1 (bool) – Choose to include star 1 or 2 data to the DataFrame. The default is to include both.

  • include_S2 (bool) – Choose to include star 1 or 2 data to the DataFrame. The default is to include both.

  • S1_kwargs (dict) – kwargs to pass to each star’s ‘to_df’ method (extra/ignore columns)

  • S2_kwargs (dict) – kwargs to pass to each star’s ‘to_df’ method (extra/ignore columns)

Return type:

pandas DataFrame

to_oneline_df(scalar_names=[], history=True, **kwargs)[source]

Convert binary into a single row DataFrame.

update_star_states()[source]

Update the states of the two stars in the binary.

posydon.binary_evol.binarystar.signal_handler(signum, frame)[source]

React to a maximum time signal.

posydon.binary_evol.flow_chart

Module setting the default evolution flow and allowing alterations.

This file contains the offical POSYDON flow chart binary evolution. To support future development and deal with complexity it is build dynamically.

posydon.binary_evol.flow_chart.flow_chart(FLOW_CHART=None, CHANGE_FLOW_CHART=None)[source]

Generate the flow chart.

Default step nomenclature: - step_SN : StepSN in posydon/bianry_evol/SN/step_SN.py - step_HMS_HMS : MS_MS_step in posydon/binary_evol/mesa_step.py - step_CO_HMS_RLO : CO_HMS_RLO_step in posydon/binary_evol/mesa_step.py - step_CO_HeMS : CO_HeMS_step in posydon/binary_evol/mesa_step.py - step_detached : detached_step in posydon/binary_evol/detached_step.py - step_CE : StepCEE in posydon/binary_evol/CE/step_CEE.py - step_dco : DoubleCO in posydon/binary_evol/double_CO.py - step_end

Parameters:
  • FLOW_CHART (dict) – Flow chart that maps the tuple (star_1_state, star_1_state, binary_state, binary_event) to a step.

  • CHANGE_FLOW_CHART (dict) –

    Flow chart to change the default FLOW_CHART. E.g. CHANGE_FLOW_CHART = {(‘NS’, ‘NS’, ‘detached’, None) : ‘step_end’,

    (‘NS’, ‘HeMS’, ‘RLO1’, ‘pRLO1’) : ‘step_my_RLO1’}

Returns:

Flow chart.

Return type:

dict

posydon.binary_evol.flow_chart.initial_eccentricity_flow_chart(FLOW_CHART=None, CHANGE_FLOW_CHART=None)[source]
Modify POSYDON’s default flow to:

ZAMS binaries -> detached oRLO1/oRLO2 -> HMS-HMS RLO grid

Parameters:
  • FLOW_CHART (dict or None)

  • CHANGE_FLOW_CHART (dict or None)

Returns:

Modified flow chart.

Return type:

dict

posydon.binary_evol.simulationproperties

Simulation properties for the population class.

This class contains the simulation properties, e.g. flow, steps and max_time.

class posydon.binary_evol.simulationproperties.EvolveHooks[source]

Bases: object

Base class for hooking into binary evolution.

Add any new output columns to the hooks constructor. Example for extra binary columns:

self.extra_binary_col_names = [“column_name_1”, “column_name_2”]

Example for extra star columns:

self.extra_star_col_names = [“column_name_1”, “column_name_2”]

post_evolve(binary)[source]

Perform actions after a binary exits the evolution loop.

post_step(binary, step_name)[source]

Perform acctions after every evolution step.

pre_evolve(binary)[source]

Perform actions before a binary evolves.

pre_step(binary, step_name)[source]

Perform actions before every evolution step.

class posydon.binary_evol.simulationproperties.NullStep[source]

Bases: object

An evolution step that does nothing but is used to initialize.

class posydon.binary_evol.simulationproperties.PrintStepInfoHooks[source]

Bases: EvolveHooks

Simple example for adding extra print info.

Add any new output columns to the hooks constructor. Example for extra binary columns:

self.extra_binary_col_names = [“column_name_1”, “column_name_2”]

Example for extra star columns:

self.extra_star_col_names = [“column_name_1”, “column_name_2”]

post_evolve(binary)[source]

Report at the end of the evolution of each binary.

pre_step(binary, step_name)[source]

Print the step name for each binary, before taking it.

class posydon.binary_evol.simulationproperties.SimulationProperties(flow=({}, {}), step_HMS_HMS=(NullStep(), {}), step_CO_HeMS=(NullStep(), {}), step_CO_HMS_RLO=(NullStep(), {}), step_CO_HeMS_RLO=(NullStep(), {}), step_detached=(NullStep(), {}), step_disrupted=(NullStep(), {}), step_merged=(NullStep(), {}), step_initially_single=(NullStep(), {}), step_dco=(NullStep(), {}), step_SN=(NullStep(), {}), step_CE=(NullStep(), {}), step_end=(NullStep(), {}), extra_hooks=[], **kwargs)[source]

Bases: object

Class describing the properties of a population synthesis simulation.

Construct the simulation properties object.

Parameters:
  • flow_chart (dict) – A POSYDON flow_chart dictionary.

  • step_HMS_HMS (tuple) – A tuple whose first element is a MesaGridStep class handling HMS-HMS evolution, like MS_MS_step. The second element is a dictionary of kwargs for that step.

  • step_CO_HeMS (tuple) – A tuple whose first element is a MesaGridStep class handling CO-HeMS evolution, like CO_HeMS_step. The second element is a dictionary of kwargs for that step.

  • step_CO_HMS_RLO (tuple) – A tuple whose first element is a MesaGridStep class handling CO-HMS-RLO evolution, like CO_HMS_RLO_step. The second element is a dictionary of kwargs for that step.

  • step_CO_HeMS_RLO (tuple) – A tuple whose first element is a MesaGridStep class handling CO-HeMS-RLO evolution, like CO_HeMS_RLO_step. The second element is a dictionary of kwargs for that step.

  • step_detached (tuple) – A tuple whose first element is a detached_step class handling detached evolution. The second element is a dictionary of kwargs for that step.

  • step_disrupted (tuple) – A tuple whose first element is a DisruptedStep class handling disrupted evolution. The second element is a dictionary of kwargs for that step.

  • step_merged (tuple) – A tuple whose first element is a MergedStep class handling merged evolution. The second element is a dictionary of kwargs for that step.

  • step_initially_single (tuple) – A tuple whose first element is a InitiallySingleStep class handling initially single evolution. The second element is a dictionary of kwargs for that step.

  • step_dco (tuple) – A tuple whose first element is a DoubleCO class handling double CO evolution. The second element is a dictionary of kwargs for that step.

  • step_SN (tuple) – A tuple whose first element is a StepSN class handling supernova evolution. The second element is a dictionary of kwargs for that step.

  • step_CE (tuple) – A tuple whose first element is a StepCEE class handling common envelope evolution. The second element is a dictionary of kwargs for that step.

  • step_end (tuple) – A tuple whose first element is a step_end class handling the end of evolution. The second element is a dictionary of kwargs for that step.

  • extra_hooks (list of tuples) – Each tuple contains a hooks class and kwargs or the extra step name (e.g., ‘extra_pre_evolve’, ‘extra_pre_step’, ‘extra_post_step’, ‘extra_post_evolve’) and the corresponding function.

check_step(metallicity, RNG, step_name, step_tup, verbose=False)[source]

Validate and update configuration for an evolution step.

This method ensures that a valid metallicity is assigned to the step (unless the step is excluded from metallicity handling) and that a corresponding TrackMatcher exists if the step requires track matching. If a TrackMatcher for the (metallicity, step_name) combination does not yet exist, it is created and stored.

Parameters:
  • metallicity (float or None) – Default metallicity value to use for the step if not explicitly provided in step_kwargs.

  • step_name (str) – Name of the pipeline step being checked.

  • step_kwargs (dict) – Keyword arguments for the step. This dictionary may be modified in-place to include validated metallicity and/or a TrackMatcher instance.

  • verbose (bool, optional) – If True, print the keyword arguments used to construct the TrackMatcher.

Returns:

The step tuple containing the step function and the updated step_kwargs dictionary. This new step_kwargs contains a validated metallicity entry and potentially a track_matcher object.

Return type:

tuple

Notes

  • If metallicity is not provided for a step that requires it, a warning

is issued and a default value of Z = 1.0 (solar metallicity) is used. - TrackMatcher objects are stored in self.track_matchers and reused for repeated (metallicity, step_name) combinations.

close()[source]

Close hdf5 files before exiting.

create_track_matcher(metallicity, step_name, matcher_kwargs)[source]

Create and store a TrackMatcher for a given metallicity and step.

This method ensures that the required stellar evolution grids (H-rich and stripped-He) are loaded for the specified metallicity. If the corresponding GRIDInterpolator objects do not yet exist, they are created and cached. The interpolators are then passed to a TrackMatcher instance, which is stored internally.

Parameters:
  • metallicity (float) – Stellar metallicity used to select the appropriate grid files.

  • step_name (str) – Identifier for the evolutionary step associated with this TrackMatcher.

  • matcher_kwargs (dict) – Keyword arguments used to initialize the TrackMatcher. This dictionary will be updated in-place with the following keys: ‘grid_Hrich’ and ‘grid_strippedHe’.

Notes

  • GRIDInterpolator objects are created only once per metallicity

and reused for subsequent TrackMatcher creations. - The created TrackMatcher is stored in self.track_matchers using the key (metallicity, step_name).

default_grid_paths = {'CO_HMS_RLO_path': './POSYDON_data/CO-HMS_RLO', 'CO_HeMS_RLO_path': './POSYDON_data/CO-HeMS_RLO', 'CO_HeMS_path': './POSYDON_data/CO-HeMS', 'HMS_HMS_path': './POSYDON_data/HMS-HMS', 'single_HMS_path': './POSYDON_data/single_HMS', 'single_HeMS_path': './POSYDON_data/single_HeMS'}
classmethod from_ini(path, metallicity=None, load_steps=False, RNG=np.random.default_rng(), verbose=False, **override_sim_kwargs)[source]

Create a SimulationProperties instance from an inifile.

Parameters:
  • path (str) – Path to an inifile to load in.

  • metallicity (float) – A metallicity (Z) may be provided to automatically assign to steps as they are loaded. Should be one of e.g., 2.0, 1.0, 4.5e-1, 2e-1, 1e-1, 1e-2, 1e-3, 1e-4, corresponding to metallicities available in your POSYDON_DATA grids.

  • load_steps (bool) – Whether or not evolution steps should be automatically loaded.

  • RNG (numpy.random.Generator, optional) – Random number generator used for any stochastic components of the simulation. Defaults to a new NumPy Generator instance created via np.random.default_rng().

  • verbose (bool) – Print useful info.

  • **override_sim_kwargs – Additional keyword arguments that override values specified in the .ini file when constructing the SimulationProperties instance.

Returns:

A new instance of SimulationProperties.

Return type:

SimulationProperties

load_a_step(step_name, step_tup=(NullStep, {}), metallicity=None, RNG=np.random.default_rng(), from_ini='', verbose=False)[source]

Instantiate and attach a simulation step to this object.

This method creates an instance of a step class and assigns it as an attribute of SimulationProperties using step_name as the attribute name. Step keyword arguments may be provided directly via step_tup or loaded from an .ini configuration file. Before instantiation, step arguments are validated and augmented (e.g., assigning metallicity and creating a TrackMatcher if required).

Parameters:
  • step_name (str) – Name of the evolution step. The created step instance will be attached to the object as self.<step_name>. See SimulationProperties.__init__ for the standard set of steps.

  • step_tup (tuple, optional) –

    Tuple of the form (step_class, kwargs_dict) where:

    • step_class is the class representing the step.

    • kwargs_dict is a dictionary of keyword arguments used to

    initialize the step.

    Default is (NullStep, {}).

  • metallicity (float, optional) – Metallicity (Z) to assign to the step if required and not already specified in the step keyword arguments. Default supported values are: 2.0, 1.0, 4.5e-1, 2e-1, 1e-1, 1e-2, 1e-3, 1e-4.

  • from_ini (str, optional) – Path to an .ini file containing step configuration. If provided and the file exists, the step class and keyword arguments for step_name are loaded from this file and override step_tup.

  • verbose (bool, optional) – If True, print detailed information about step loading and the keyword arguments used to instantiate the step.

Return type:

None

Notes

  • Step keyword arguments are processed by self.check_step before

instantiation. This may assign a metallicity and/or attach a TrackMatcher if required for the step. - The instantiated step is stored as an attribute of SimulationProperties. - After loading, self.steps_loaded is updated to indicate whether all configured steps have been successfully attached.

load_steps(metallicity=None, RNG=np.random.default_rng(), verbose=False)[source]

Instantiate all step classes and set as instance attributes.

Parameters:
  • metallicity (float) – A metallicity (Z) may be provided to automatically assign to steps as they are loaded. Should be one of e.g., 2.0, 1.0, 4.5e-1, 2e-1, 1e-1, 1e-2, 1e-3, 1e-4, corresponding to metallicities available in your POSYDON_DATA grids.

  • verbose (bool) – Print extra information.

Return type:

None

post_evolve(binary)[source]

Finalize the evolution of the binary.

The method is called after a binary exits the evolution loop. Uses all extra hooks classes or extra functions.

Parameters:

binary (instance of <class, BinaryStar>) – The binary after evolution is ended.

Returns:

binary

Return type:

instance of <class, BinaryStar>

post_step(binary, step_name)[source]

Finalize step.

The method is called after every evolution step; uses all extra hooks classes or extra functions (except for undefined next step errors).

Parameters:
  • binary (instance of <class, BinaryStar>) – The binary before evolution starts.

  • step_name (str) – The name of the step about to be called (as defined in the flow).

Returns:

binary

Return type:

instance of <class, BinaryStar>

pre_evolve(binary)[source]

Functions called before a binary evolves.

Uses all extra hooks classes or extra functions.

Parameters:

binary (instance of <class, BinaryStar>) – The binary before evolution starts.

Returns:

binary

Return type:

instance of <class, BinaryStar>

pre_step(binary, step_name)[source]

Prepare for step.

The method is called before every evolution step; uses all extra hooks classes or extra functions (except for undefined next step errors).

Parameters:
  • binary (instance of <class, BinaryStar>) – The binary before evolution starts.

  • step_name (str) – The name of the step about to be called (as defined in the flow).

Returns:

binary

Return type:

instance of <class, BinaryStar>

preload_imports()[source]

Preload the imports of detached_step and MesaGridStep to avoid

importing them when they are needed when close() is called. In particular, detached_step imports sklearn, which in turn utilizes loky, which invokes its own register.at_exit call. If this happens during the close() call, which is invoked at shutdown, a failure occurs, hence the need for something like this.

set_path(path_name, path_str)[source]

Set and normalize a grid path attribute that points to one of the MESA grids needed for binary evolution. By default, these are the grids inside of the directory name held in $PATH_TO_POSYDON_DATA.

For example, for the step_HMS_HMS, the grid would be

$PATH_TO_POSYDON_DATA/HMS-HMS/<metallicity>_Zsun.h5

by default. The grid HDF5 file names themselves are expected to follow formats like so: 1e+00_Zsun.h5, 1e-04_Zsun.h5, etc.

If path_str is None, a default path is assigned based on path_name using self.default_grid_paths. If path_name is not recognized, a GridError is raised listing the valid options.

The resulting path is converted to an absolute path before being stored as an attribute of the instance.

Parameters:
  • path_name (str) – Name of the grid path attribute to set. Must be a key in self.default_grid_paths if path_str is None.

  • path_str (str or None) – Path to assign. If None, a default path corresponding to path_name is used.

Raises:

GridError – If path_name is not recognized and no default path can be assigned.

Notes

The path is not validated for existence here; only normalization to an absolute path is performed.

class posydon.binary_evol.simulationproperties.StepNamesHooks[source]

Bases: EvolveHooks

Add history column ‘step_name’ to each binary.

Name of evolutionary step as defined in SimulationProperties.

>>> pop.to_df(extra_columns={'step_names': str})

Add any new output columns to the hooks constructor. Example for extra binary columns:

self.extra_binary_col_names = [“column_name_1”, “column_name_2”]

Example for extra star columns:

self.extra_star_col_names = [“column_name_1”, “column_name_2”]

post_evolve(binary)[source]

Ensure None’s are append to step_names to match rows in history.

post_step(binary, step_name)[source]

Record the step name.

pre_evolve(binary)[source]

Initialize the step name to match history.

pre_step(binary, step_name)[source]

Do not do anything before the step.

class posydon.binary_evol.simulationproperties.TimingHooks[source]

Bases: EvolveHooks

Add history column ‘step_times’ (time taken by step) to each binary.

Example

>>> pop.to_df(extra_columns={'step_times': float})

Add any new output columns to the hooks constructor. Example for extra binary columns:

self.extra_binary_col_names = [“column_name_1”, “column_name_2”]

Example for extra star columns:

self.extra_star_col_names = [“column_name_1”, “column_name_2”]

post_evolve(binary)[source]

Add None’s to step_times to match history rows.

post_step(binary, step_name)[source]

Record the duration of the step.

pre_evolve(binary)[source]

Initialize the step time to match history.

pre_step(binary, step_name)[source]

Record the wall time before taking the step.

posydon.binary_evol.singlestar

The star object describe the star current and past state.

The star object contains the current and past states of the star. Only parameters in the STARPROPERTIES list are stored in the history. The current parameter value of the star object is accessed as, e.g. star.mass, while his past history with star.mass_history.

class posydon.binary_evol.singlestar.SingleStar(**kwargs)[source]

Bases: object

Class describing a single star.

Initialize the star.

Parameters:

**kwargs (dict) – List of initialization parameters for a star.

append_state()[source]

Append the new version of the star to the end of the star state.

static from_run(run, history=False, profile=False, which_star=None)[source]

Create a SingleStar object from a single-star grid run.

restore(i=0, hooks=None)[source]

Restore the SingleStar() object to its i-th state, keeping the star history before the i-th state.

Parameters:
  • i (int) – Index of the star object history to reset the star to. By default i == 0, i.e. the star will be restored to its initial state.

  • hooks (list) – List of extra hooks associated with the SimulationProperties() of the BinaryStar() object containing this SingleStar(), if applicable. This parameter is automatically set when restoring a BinaryStar() object.

to_df(**kwargs)[source]

Return history parameters from the star in a DataFrame.

By default all parameters in STARPROPERTIES are included.

Parameters:
  • extra_columns (dict( 'name':dtype, .... )) – Extra star history parameters to return in DataFrame that are not included in STARPROPERTIES. All columns must have an associated pandas data type. Can be used in combination with only_select_columns. Assumes names have no suffix.

  • ignore_columns (list) – Names of STARPROPERTIES parameters to ignore. Assumes names have _history suffix.

  • only_select_columns (list) – Names of the only columns to include. Can be used in combination with extra_columns. Assumes names have _history suffix.

  • include_profile (bool) – Include the star’s profile in the dataframe (NOT RECOMMENDED)

  • null_value (float, optional) – Replace all None values with something else (for saving). Default is np.nan.

  • prefix (str, optional) – Prefix to all column names. (e.g. ‘star_1’, ‘S1’) Default has no prefix.

Return type:

pandas DataFrame

to_oneline_df(history=True, prefix='', **kwargs)[source]

Convert SingleStar into a single row DataFrame.

By default, initial final values of history are used with the to_df method. Any scalar values can also be added.

Parameters:
  • scalar_names (list of str) – Names of any values to be added to the oneline DataFrame.

  • history (bool) – Include the history initial-final values from to_df method.

  • prefix (str) – Any prefix to go at the beginning of all columns names.

  • **kwargs – All options for the to_df method.

Return type:

oneline_df

posydon.binary_evol.singlestar.convert_star_to_massless_remnant(star)[source]
posydon.binary_evol.singlestar.properties_massless_remnant()[source]

posydon.binary_evol.step_end

Class defining the default step at the end of evolution of a binary.

class posydon.binary_evol.step_end.step_end[source]

Bases: object

Default end step.

DEFAULT_KWARGS = {}

posydon.binary_evol.track_match

class posydon.binary_evol.track_match.TrackMatcher(**kwargs)[source]

Bases: object

This class contains the functionality to match binary star components

to single star models for detached evolution. Typically, this is so that the binary star can continue evolving in a detached (non-interacting) state.

Several matching methods may be used, and metrics (physical

quantities) that are used to determine the quality of the match may be customized. By default, the metrics are as follows:

DEFAULT_KWARGS = {'grid_Hrich': None, 'grid_strippedHe': None, 'list_for_matching_HMS': None, 'list_for_matching_HeStar': None, 'list_for_matching_postHeMS': None, 'list_for_matching_postMS': None, 'matching_method': 'minimize', 'matching_tolerance': 0.01, 'matching_tolerance_hard': 0.1, 'metallicity': None, 'path': './POSYDON_data', 'record_matching': False, 'verbose_matching': False}
TRAINING_TRIGGERS = ['grid_Hrich', 'grid_strippedHe', 'path', 'metallicity', 'list_for_matching_HMS', 'list_for_matching_HeStar', 'list_for_matching_postMS', 'list_for_matching_postHeMS']
calc_omega(star)[source]

Calculate the spin of a star from its (pre-match) moment

of inertia and angular momentum (or rotation rates). This is required because we match a rotating model (from the binary grids) to a non-rotating model (from the single star grids).

Parameters:

star (SingleStar object) – Star object containing the star properties.

Returns:

omega_in_rad_per_year – The rotation rate of the star in radians per year, calculated from the star’s (pre-match) angular momentum and moment of inertia.

Return type:

float

Warns:

InappropriateValueWarning – If the pre-match rotation quantities are NaN or None and can not calculate a the post-match rotation rate, we setting the post-match rotation rate to zero.

create_root0_h()[source]
create_root0_he()[source]
determine_star_states(binary)[source]

Determines which star is primary (further evolved) and which is

secondary (less evolved). Determines whether stars should be matched to the H- or He-rich grid, whether they exist, or if they are compact objects/massless remnants. This is used to determine how to match the stars.

Parameters:

binary (BinaryStar object) – A binary star object, containing the binary system’s properties.

Returns:

  • primary (SingleStar object) – A single star object, representing the primary (more evolved) star in the binary and containing its properties.

  • secondary (SingleStar object) – A single star object, representing the secondary (less evolved) star in the binary and containing its properties.

  • only_CO (bool) – A boolean indicating whether the binary system contains only a single compact object (True) or not (False). As in the detached step, it may be desirable to use this flag to exit an evolution step, as a single compact obejct (point mass) can not be evolved further.

Raises:
  • POSYDONError – If there is no star to evolve (both are massless remnants), then evolution can no continue and detached step should not have been called.

  • ValueError – If the State of star 1 or 2 is not recognized.

  • POSYDONError – If the non_existent_companion of the binary is determined to be not equal to 0 (both stars exist), 1 (only star 2 exists), or 2 (only star 1 exists), something has gone wrong.

do_matching(binary, step_name='step_match', match_secondary=True, match_primary=True)[source]

Perform binary to single star grid matching. This is currently

used when transitioning to detached star evolution from binary but may be used in other steps. This performs several actions:

  1. Determines which star is primary/secondary in the evolution and their evolutionary states. If evolvable, matching will proceed.

  2. Match either one or both stars to a (non-rotating) single star evolution track.

  3. Calculate the matched star’s rotation using the pre-match step’s angular momentum-related properties.

  4. Returns the primary/secondary stars with interpolator objects that may be used to calculate quantities along the time series of each star for further evolution.

Parameters:
  • binary (BinaryStar object) – A binary star object, containing the binary system’s properties.

  • step_name (str) – If self.record_matching is True, then the matched quantities of the star will be appended to the history. This is a string that can be used as a custom label in the BinaryStar object’s history, meant to indicate the relevant evolution step’s name. This should normally match the name of the step in which the matching was made, e.g., “step_detached”.

  • match_secondary (bool) – A boolean that indicates whether to perform matching on star 1.

  • match_primary (bool) – A boolean that indicates whether to perform matching on star 2.

Returns:

  • primary_out (tuple(SingleStar, PchipInterpolator, float)) – The first element is the SingleStar object of the primary (more evolved) star. The second element is the primary’s PchipInterpolator object, used to interpolate values along this star’s time series. The third is the primary’s calculated (post-match) rotation rate, using angular momentum-related quantites from the pre-match step.

  • secondary_out (tuple(SingleStar, PchipInterpolator, float)) – The first element is the SingleStar object of the secondary (less evolved) star. The second element is the secondary’s PchipInterpolator object, used to interpolate values along this star’s time series. The third is the secondary’s calculated (post-match) rotation rate, using angular momentum-related quantites from the pre-match step.

  • only_CO (bool) – A boolean indicating whether the binary system contains only a single compact object (True) or not (False). As in the detached step, it may be desirable to use this flag to exit an evolution step, as a single compact obejct (point mass) can not be evolved further.

Raises:
  • ValueError – If the primary_normal and primary_not_normal flags are both determined to be False. One or the other should be True.

  • MatchingError – If the stellar matching to a single star model fails, or the PchipInterpolator object returned from matching is None.

get_root0(attr_names, attr_vals, htrack, rescale_facs=None)[source]

Get the stellar evolution track in the single star grid with values

closest to the requested ones. This calculates the difference in stellar properties between a given track and those in the single star grids. It then returns the mass of and age along the track where the minimum difference occurs.

Parameters:
  • attr_names (list[str]) – Contains the keys of the requested specific quantities that will be matched in the single star track.

  • attr_vals (list[float]) – Contains the latest values (from a previous POSYDON step) of the quantities of “keys” in the POSYDON SingleStar object. This should be the same length as “keys”.

  • htrack (bool) – Set True to search the single star H-rich grids, or False to search the He-rich grids.

  • rescale_facs (list[float]) – Contains normalization factors to be divided for rescaling attribute values. This should be the same length as attr_names.

Returns:

  • m0 (float) – Initial mass (in solar units) of the minimum diff model for initial guess.

  • t0 (float) – Age (in years) of the minimum diff model for initial guess.

get_star_final_values(star)[source]

This updates the final values of a SingleStar object,

given an initial stellar mass m0, typically found from matching to a single star track.

Parameters:
  • star (SingleStar object) – A single star object that contains the star’s properties.

  • htrack (bool) – A boolean that specifies whether the star would be found in the hydrogen rich single star grid or not (in which case it is matched to the helium rich single star grid).

  • m0 (float) – Initial stellar mass (in solar units) of the single star track that we will grab values from and update star with.

get_star_match_data(binary, star, copy_prev_m0=None, copy_prev_t0=None)[source]

Match a given component of a binary (i.e., a star) to a

single star model. This then creates and returns interpolator objects that may be used to calculate properties of the star as a function of time.

In the case of a compact object, radius, mdot, and Idot are

set to zero. One may use another star, e.g., the companion of the compact object to provide a mass and age.

Parameters:
  • binary (BinaryStar object) – A binary star object, containing the binary system’s properties.

  • star (SingleStar object) – A single star object that contains the star’s properties.

  • copy_prev_m0 (float) – A mass value that may be copied from another star in the case where the target star is a compact object

  • copy_prev_t0 (float) – An age value that may be copied from another star in the case where the target star is a compact object

Returns:

  • match_m0 (float) – Initial mass (in solar units) of the matched model.

  • match_t0 (float) – Age (in years) of the matched model.

get_star_profile(star)[source]

This updates the stellar profile of a SingleStar object,

given an initial stellar mass m0, typically found from matching to a single star track. The profile of the SingleStar object is updated to become the profile of the (matched) single star track.

Parameters:
  • star (SingleStar object) – A single star object that contains the star’s properties.

  • htrack (bool) – A boolean that specifies whether the star would be found in the hydrogen rich single star grid or not (in which case it is matched to the helium rich single star grid).

  • m0 (float) – Initial stellar mass (in solar units) of the single star track that we will grab values from and update star with.

get_track_val(key, htrack, m0, t)[source]

Return a single value of a stellar property from the

interpolated time-series along a requested stellar track of mass m0 at an age of t.

Parameters:
  • key (str) – Keyword of the desired quantity.

  • m0 (float) – The initial mass of the desired stellar track.

  • t (float) – The desired age along the stellar track.

Returns:

val – The value of the desired quantity from a stellar track of initial mass m0 at the time t.

Return type:

float

match_through_minimize(star, get_root0, get_track_val)[source]

Match the star through a minimization method. An initial

match is found using the get_root0() function. Then, those initial values are used in SciPy’s minimize method to find the closest matching point in evolution, based on several physical matching metrics.

Parameters:
  • star (SingleStar object) – This is a SingleStar object, typically representing a member of a binary star system that we are trying to match to a single star track.

  • get_root0 (function) – Function that is used to get an initial guess for a closely matching stellar track.

  • get_track_val (function) – Function that returns a single value of a stellar property from the interpolated time-series along a requested stellar track of mass m0 at an age of t.

Returns:

  • match_vals (array) – Mass and age of the star found through matching. These serve as starting points for subsequent (post-match) evolution.

  • best_sol (OptimizeResult object) – The OptimizeResult object that contains attributes of the closest matching stellar track. Produced by SciPy’s minimize().

match_through_root(star, get_root0, get_track_val)[source]

Match the star through a root method.

Parameters:
  • star (SingleStar object) – This is a SingleStar object, typically representing a member of a binary star system that we are trying to match to a single star track.

  • get_root0 (function) – Function that is used to get an initial guess for a closely matching stellar track.

  • get_track_val (function) – Function that returns a single value of a stellar property from the interpolated time-series along a requested stellar track of mass m0 at an age of t.

Returns:

  • match_vals (array) – Mass and age of the star found through matching. These serve as starting points for subsequent (post-match) evolution.

  • best_sol (OptimizeResult object) – The OptimizeResult object that contains attributes of the closest matching stellar track. Produced by SciPy’s root().

match_to_single_star(star)[source]

Get the track in the grid that matches the time and mass of a star,

that has typically undergone prior binary star evolution. A match is made according to a given algorithm that minimizes the difference amongst several physical properties, e.g., mass, central hydrogen abundance, radius, and core helium mass, depending on the type of star being matched. However, these properties may also be customized by the user.

Parameters:

star (SingleStar object) – A single star object that contains the star’s properties.

Returns:

  • match_m0 (float) – Initial mass (in solar units) of the matched model.

  • match_t0 (float) – Age (in years) of the matched model.

Warns:

EvolutionWarning – If attempting to match an He-star with an H-rich grid or post-MS star with a stripped-He grid. This can happen if an initial matching attempt fails; alternative grids are checked for a match in such cases.

Raises:
  • AttributeError – If a matching parameter does not exist in the single star grid options

  • NumericalError – If SciPy numerical differentiation occured outside boundary while matching to single star track.

  • MatchingError – If the initial mass to be matched is out of the single star grid range, thereby preventing a possible match.

scale(attr_name, htrack, scaler_method)[source]

Normalize quantities in the single star grids to (0,1).

Parameters:
  • attr_name (str) – Keyword of the requested quantity.

  • htrack (bool) – A boolean that specifies whether the star would be found in the hydrogen rich single star grid or not (in which case it is matched to the helium rich single star grid).

  • scaler_method (str) – Scaling method in the DataScaler class. See posydon.interpolation.data_scaling.DataScaler().fit() for more details.

Returns:

scaler – This is a DataScaler object, trained to rescale the requested attribute to the range (0, 1).

Return type:

DataScaler object

classmethod separate_kwargs(step_kwargs)[source]
train_scalers()[source]
update_rotation_info(primary, secondary)[source]

Once we have matched to a non-rotating single star, we need to

calculate what the single star’s spin should be, based the star’s rotation before matching. This calculates a new rotation rate for the matched star from the previous moment of inertia and angular momentum (or rotation rate in lieu of those). This also updates the stars in the binary with the newly calculated values to reflect this.

Parameters:
  • primary (SingleStar object) – A single star object, representing the primary (more evolved) star in the binary and containing its properties.

  • secondary (SingleStar object) – A single star object, representing the secondary (less evolved) star in the binary and containing its properties.

Returns:

  • omega0_pri (float) – The rotation rate of the primary star in radians per year, calculated from the star’s (pre-match) angular momentum and moment of inertia.

  • omega0_sec (float) – The rotation rate of the secondary star in radians per year, calculated from the star’s (pre-match) angular momentum and moment of inertia.

update_star_properties(star, htrack)[source]

This updates a SingleStar object (star) with the

values from a single star track that has initial mass m0 and age t0. This can be used after matching finds the closest m0, t0 to update the SingleStar object with the values of the best matching single star track. This will not update the log_total_angular_momentum or surf_avg_omega because the single star track is non-rotating and those quantities are poorly defined.

Parameters:
  • star (SingleStar object) – A single star object that contains the star’s properties.

  • htrack (bool) – A boolean that specifies whether the star would be found in the hydrogen rich single star grid or not (in which case it is matched to the helium rich single star grid).