utils

class cosmic.utils.ConfigParser(defaults=None, dict_type=<class 'dict'>, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section='DEFAULT', interpolation=<object object>, converters=<object object>)

Bases: RawConfigParser

ConfigParser implementing interpolation.

_DEFAULT_INTERPOLATION = <configparser.BasicInterpolation object>
__abstractmethods__ = frozenset({})
__doc__ = 'ConfigParser implementing interpolation.'
__module__ = 'configparser'
_abc_impl = <_abc._abc_data object>
_read_defaults(defaults)

Reads the defaults passed in the initializer, implicitly converting values to strings like the rest of the API.

Does not perform interpolation for backwards compatibility.

add_section(section)

Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.

set(section, option, value=None)

Set an option. Extends RawConfigParser.set by validating type and interpolation syntax on the value.

class cosmic.utils.Path(*args, **kwargs)

Bases: PurePath

PurePath subclass that can make system calls.

Path represents a filesystem path but unlike PurePath, also offers methods to do system calls on path objects. Depending on your system, instantiating a Path will return either a PosixPath or a WindowsPath object. You can also instantiate a PosixPath or WindowsPath directly, but cannot instantiate a WindowsPath on a POSIX system or vice versa.

__annotations__ = {}
__doc__ = 'PurePath subclass that can make system calls.\n\n    Path represents a filesystem path but unlike PurePath, also offers\n    methods to do system calls on path objects. Depending on your system,\n    instantiating a Path will return either a PosixPath or a WindowsPath\n    object. You can also instantiate a PosixPath or WindowsPath directly,\n    but cannot instantiate a WindowsPath on a POSIX system or vice versa.\n    '
__enter__()
__exit__(t, v, tb)
__module__ = 'pathlib'
static __new__(cls, *args, **kwargs)

Construct a PurePath from one or several strings and or existing PurePath objects. The strings and path objects are combined so as to yield a canonicalized path, which is incorporated into the new PurePath object.

__slots__ = ()
_accessor = <pathlib._NormalAccessor object>
_make_child_relpath(part)
absolute()

Return an absolute version of this path. This function works even if the path doesn’t point to anything.

No normalization is done, i.e. all ‘.’ and ‘..’ will be kept along. Use resolve() to get the canonical path to a file.

chmod(mode, *, follow_symlinks=True)

Change the permissions of the path, like os.chmod().

classmethod cwd()

Return a new path pointing to the current working directory (as returned by os.getcwd()).

exists()

Whether this path exists.

expanduser()

Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser)

glob(pattern)

Iterate over this subtree and yield all existing files (of any kind, including directories) matching the given relative pattern.

group()

Return the group name of the file gid.

Make this path a hard link pointing to the same file as target.

Note the order of arguments (self, target) is the reverse of os.link’s.

classmethod home()

Return a new path pointing to the user’s home directory (as returned by os.path.expanduser(‘~’)).

is_block_device()

Whether this path is a block device.

is_char_device()

Whether this path is a character device.

is_dir()

Whether this path is a directory.

is_fifo()

Whether this path is a FIFO.

is_file()

Whether this path is a regular file (also True for symlinks pointing to regular files).

is_mount()

Check if this path is a POSIX mount point

is_socket()

Whether this path is a socket.

Whether this path is a symbolic link.

iterdir()

Iterate over the files in this directory. Does not yield any result for the special paths ‘.’ and ‘..’.

lchmod(mode)

Like chmod(), except if the path points to a symlink, the symlink’s permissions are changed, rather than its target’s.

Make the target path a hard link pointing to this path.

Note this function does not make this path a hard link to target, despite the implication of the function and argument names. The order of arguments (target, link) is the reverse of Path.symlink_to, but matches that of os.link.

Deprecated since Python 3.10 and scheduled for removal in Python 3.12. Use hardlink_to() instead.

lstat()

Like stat(), except if the path points to a symlink, the symlink’s status information is returned, rather than its target’s.

mkdir(mode=511, parents=False, exist_ok=False)

Create a new directory at this given path.

open(mode='r', buffering=-1, encoding=None, errors=None, newline=None)

Open the file pointed by this path and return a file object, as the built-in open() function does.

owner()

Return the login name of the file owner.

read_bytes()

Open the file in bytes mode, read it, and close the file.

read_text(encoding=None, errors=None)

Open the file in text mode, read it, and close the file.

Return the path to which the symbolic link points.

rename(target)

Rename this path to the target path.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

replace(target)

Rename this path to the target path, overwriting if that path exists.

The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.

Returns the new Path instance pointing to the target path.

resolve(strict=False)

Make the path absolute, resolving all symlinks on the way and also normalizing it (for example turning slashes into backslashes under Windows).

rglob(pattern)

Recursively yield all existing files (of any kind, including directories) matching the given relative pattern, anywhere in this subtree.

rmdir()

Remove this directory. The directory must be empty.

samefile(other_path)

Return whether other_path is the same or not as this file (as returned by os.path.samefile()).

stat(*, follow_symlinks=True)

Return the result of the stat() system call on this path, like os.stat() does.

Make this path a symlink pointing to the target path. Note the order of arguments (link, target) is the reverse of os.symlink.

touch(mode=438, exist_ok=True)

Create this file with the given access mode, if it doesn’t exist.

Remove this file or link. If the path is a directory, use rmdir() instead.

write_bytes(data)

Open the file in bytes mode, write to it, and close the file.

write_text(data, encoding=None, errors=None, newline=None)

Open the file in text mode, write to it, and close the file.

class cosmic.utils.VariableKey(item)

Bases: object

A dictionary key which is a variable. @ivar item: The variable AST object.

__dict__ = mappingproxy({'__module__': 'cosmic.utils', '__doc__': '\n    A dictionary key which is a variable.\n    @ivar item: The variable AST object.\n    ', '__init__': <function VariableKey.__init__>, '__eq__': <function VariableKey.__eq__>, '__hash__': <function VariableKey.__hash__>, '__dict__': <attribute '__dict__' of 'VariableKey' objects>, '__weakref__': <attribute '__weakref__' of 'VariableKey' objects>, '__annotations__': {}})
__doc__ = '\n    A dictionary key which is a variable.\n    @ivar item: The variable AST object.\n    '
__eq__(compare)

Return self==value.

__hash__()

Return hash(self).

__init__(item)
__module__ = 'cosmic.utils'
__weakref__

list of weak references to the object (if defined)

cosmic.utils.a_from_p(p, m1, m2)

Computes the separation from orbital period with KEPLER III

Parameters:
pfloat/array

orbital period [day]

m1float/array

primary mass [msun]

m2float/array

secondary mass [msun]

Returns:
sepfloat/array

separation [rsun]

cosmic.utils.calc_Roche_radius(M1, M2, A)

Get Roche lobe radius (Eggleton 1983)

Parameters:
M1float

Primary mass [any unit]

M2float

Secondary mass [any unit]

Afloat

Orbital separation [any unit]

Returns:
Roche radiusfloat

in units of input ‘A’

cosmic.utils.check_initial_conditions(full_initial_binary_table)

Checks initial conditions and reports warnings

Only warning provided right now is if star begins in Roche lobe overflow

cosmic.utils.conv_select(bcm_save, bpp_save, final_kstar_1, final_kstar_2, method, conv_lims)

Select bcm data for special convergence cases

Parameters:
bcm_savepandas.DataFrame

bcm dataframe containing all saved bcm data

bpp_savepandas.DataFrame

bpp dataframe containing all saved bpp data

final_kstar_1list

contains list of final primary kstars specified by user

final_kstar_2list

contains list of final primary kstars specified by user

methodstr

stage in binary evolution to check convergence for only one method may be supplied and they are specified in the inifile

conv_limsdict

dictionary where keys are convergence params and the values are lists containing a [lo, hi] value to filter the convergence param between any non-specified convergence params will not be filtered

Returns:
conv_savepandas.DataFrame

filtered dataframe containing binaries that fulfill user-specified convergence criteria

cosmic.utils.conv_select_singles(bcm_save, bpp_save, final_kstar_1)

Select singles

cosmic.utils.convert_kstar_evol_type(bpp)

Provides way to convert integer values to their string counterpart

The underlying fortran code relies on integers to indicate things like the evoltuionary stage of the star as well as key moments in its evolutionary track. If you pass the data frame returned from running

`Evolve.evolve`

you can convert the columns with these integer proxies to their true astrophysical meaning.

cosmic.utils.dat_transform(dat, dat_list)

Transform a data set to have limits between zero and one using param_transform, then transform to log space

Parameters:
dat “ DataFrame

Data to transform to eventually perform KDE

dat_listlist

List of DataFrame columns to include in transformation

Returns:
dat_transarray

Transformed data for columns in dat_list

cosmic.utils.dat_un_transform(dat_sample, dat_set, dat_list)

Un-transform data that was transformed in dat_transform

Parameters:
dat_samplearray

Data sampled from kde generated with transformed data

dat_setDataFrame

Un-transformed data (same as dat in dat_transform)

dat_listlist

List of DataFrame columns to include in transformation

Returns:
datarray

Array of data sampled from kde that is transformed back to bounds of the un-transformed data set the kde is generated from

cosmic.utils.error_check(BSEDict, SSEDict, filters=None, convergence=None, sampling=None)

Checks that values in BSEDict, SSEDict,filters, and convergence are viable

cosmic.utils.explain_setting(setting)

Provides explanation for a BSE setting from the cosmic-settings.json file

Parameters:
settingstr

Name of BSE setting to explain

cosmic.utils.filter_bin_state(bcm, bpp, method, kstar1_range, kstar2_range)

Filter the output of bpp and bcm, where the kstar ranges have already been selected by the conv_select module

Parameters:
bcmpandas.DataFrame

bcm dataframe

bpppandas.DataFrame

bpp dataframe

methoddict,

one or more methods by which to filter the bpp or bcm table, e.g. {'binary_state' : [0,1]}; This means you do not want to select the final state of the binaries in the bcm array

kstar1_rangelist

list containing all kstar1 values to retain

kstar2_rangelist

list containing all kstar2 values to retain

Returns:
bcmpandas.DataFrame

filtered bcm dataframe

cosmic.utils.get_FeH_from_Z(Z, Z_sun=0.02)

Converts from Z to FeH under the assumption that all stars have the same abundance as the sun

Parameters:
Zarray

metallicities to convert to Fe/H

Z_sunfloat

solar metallicity

Returns:
FeHarray

Fe/H corresponding to metallicities

cosmic.utils.get_METISSE_metallicity_files(path_to_tracks)

Returns the path to the METISSE files

Parameters:
path_to_tracksstr

Path to the directory containing the METISSE metallicity file(s) for hydrogen/helium tracks

Returns:
met_fileslist

List of paths to the METISSE metallicity files for hydrogen/helium tracks

cosmic.utils.get_Z_from_FeH(FeH, Z_sun=0.02)

Converts from FeH to Z under the assumption that all stars have the same abundance as the sun

Parameters:
FeHarray

Fe/H values to convert

Z_sunfloat

solar metallicity

Returns:
Zarray

metallicities corresponding to Fe/H

cosmic.utils.get_binfrac_of_Z(Z)

Calculates the theoretical binary fraction as a function of metallicity. Following Moe+2019

Parameters:
Zarray

metallicity Z values

Returns:
binfracarray

binary fraction values

cosmic.utils.get_met_dep_binfrac(met)

Returns a population-wide binary fraction consistent with Moe+19 based on the supplied metallicity

Parameters:
metfloat

metallicity of the population

Returns:
binfracfloat

binary fraction of the population based on metallicity

cosmic.utils.get_porb_norm(Z, close_logP=4.0, wide_logP=6.0, binfrac_tot_solar=0.66, Z_sun=0.02)

Returns normalization constants to produce log normals consistent with Fig 19 of Moe+19 for the orbital period distribution

Parameters:
Zarray

metallicity values

close_logPfloat

divding line beween close and intermediate orbits

wide_logPfloat

dividing line between intermediate and wide orbits

binfrac_totfloat

integrated total binary fraction at solar metallicity

Returns:
norm_widefloat

normalization factor for kde for wide binaries

norm_closefloat

normalization factor for kde for wide binaries

cosmic.utils.idl_tabulate(x, f, p=5)

Function that replicates the IDL int_tabulated function which performs a p-point integration on a tabulated set of data

Parameters:
xarray

tabulated x-value data

farray

tabulated f-value data, same size as x

pint

number of chunks to divide tabulated data into Default: 5

Returns:
retfloat

Integration result

cosmic.utils.io_files(package: ModuleType | str) Traversable

Get a Traversable resource from a package

cosmic.utils.knuth_bw_selector(dat_list)

Selects the kde bandwidth using Knuth’s rule implemented in Astropy If Knuth’s rule raises error, Scott’s rule is used

Parameters:
dat_listlist

List of data arrays that will be used to generate a kde

Returns:
bw_minfloat

Minimum of bandwidths for all of the data arrays in dat_list

cosmic.utils.mass_min_max_select(kstar_1, kstar_2, **kwargs)

Select a minimum and maximum mass to filter out binaries in the initial parameter sample to reduce the number of unneccessary binaries evolved in BSE

Parameters:
kstar_1int, list

BSE stellar type for the primary or minimum and maximum stellar types for the primary

kstar_2int, list

BSE stellar type for the secondary or minimum and maximum stellar types for the secondary

Returns:
min_mass[0]float

minimum primary mass for initial sample

max_mass[0]float

maximum primary mass for initial sample

min_mass[1]float

minimum secondary mass for initial sample

max_mass[1]float

maximum secondary mass for initial sample

cosmic.utils.p_from_a(sep, m1, m2)

Computes separation from orbital period with kepler III

Parameters:
sepfloat/array

separation [rsun]

m1float/array

primary mass [msun]

m2float/array

secondary mass [msun]

Returns:
pfloat/array

orbital period [day]

cosmic.utils.param_transform(dat)

Transforms a data set to limits between zero and one Leaves some wiggle room on the edges of the data set

Parameters:
datarray

array of data to transform between 0 and 1

Returns:
datTransformedarray

array of data with limits between 0 and 1

cosmic.utils.parse_inifile(inifile)

Provides a method for parsing the inifile and returning dicts of each section

cosmic.utils.pop_write(dat_store, log_file, mass_list, number_list, bcm, bpp, initC, conv, kick_info, bin_state_nums, match, idx, **kwargs)
Writes all the good stuff that you want to save from runFixedPop in a

single function

Parameters:
dat_storepandas HDFStore

H5 file to write to

log_filefile write

log file to write to

mass_listlist

list containing the mass of the singles, mass of the binaries, and mass of the stars

n_listlist

list containing the number of singles, number of binaries, and number of stars

bcmpandas.DataFrame

bcm array to write

bpppandas.DataFrame

bpp array to write

initCondpandas.DataFrame

initCond array to write

convpandas.DataFrame

conv array to write

kick_infopandas.DataFrame

kick_info array to write

bin_state_numslist

contains the count of binstates 0,1,2

matchpandas.DataFrame

contains the match values for each conv_param

idxint

contains the index of the bcm so we can pick up where we left off if runFixedPop hits a wall time

conv_singlespandas.DataFrame

kwargs conv_singles array to write

bcm_singlespandas.DataFrame

kwargs bcm_singles array to write

bpp_singlespandas.DataFrame

kwargs bpp_singles array to write

initC_singlespandas.DataFrame

kwargs initC_singles array to write

kick_info_singlespandas.DataFrame

kwargs kick_info_singles array to write

Returns:
Nothing!
cosmic.utils.read_MIST_track(eep_path)
cosmic.utils.read_eep_directory(eep_dir, fmt_dict)

Read all EEP files in a directory matching the given pattern

Parameters:
eep_dirstr or Path

Directory containing the EEP files.

fmt_dictdict

Dictionary containing format file options, e.g., column names, EEP stages, flags.

Returns:
trackslist of dict

List of track dictionaries, each as returned by read_eep_file

cosmic.utils.read_format_file(format_file_path)

Read the format file associated with the metallicity namelist

Parameters:
format_file_pathstr or Path

Path to the format file.

Returns:
fmt_dictdict

Dictionary containing format file options, e.g., column names, EEP stages, flags.

Notes

  • Booleans (.true./.false.) are converted to Python True/False.

  • Fortran-style scientific notation with ‘d’ (e.g., 1.23d-04) is converted to float.

  • Strings in quotes are stripped of the quotes.

  • Stops parsing at the Fortran namelist terminator ‘/’.

cosmic.utils.read_metallicity_file(met_file_path)

Read a metallicity namelist

Parameters:
met_file_pathstr or Path

Path to the metallicity file (*.in).

Returns:
met_dictdict

Dictionary containing metallicity options, e.g., ‘eep_tracks_dir’, ‘Z_files’, ‘format_file’, etc. Paths are converted to Path objects.

Notes

  • Booleans (.true./.false.) are converted to Python True/False.

  • Fortran-style scientific notation with ‘d’ (e.g., 1.23d-04) is converted to float.

  • Strings in quotes are stripped of the quotes.

  • Stops parsing at the Fortran namelist terminator ‘/’.

cosmic.utils.read_other_track(eep_path, fmt)
cosmic.utils.rndm(a, b, g, size)

Power-law generator for pdf(x)propto x^{g} for a<=x<=b

Parameters:
afloat

Minimum of range for power law

bfloat

Maximum of range for power law

gfloat

Index for power law

sizeint

Number of data points to draw

Returns:
powerarray

Array of data sampled from power law distribution with params fixed by inputs

cosmic.utils.to_f2py_str_array(pylist, maxlen=256)

Convert Python list of strings to NumPy array of fixed-length strings for F2PY.

Parameters:
pylistlist of str

Strings to convert.

maxlenint

Max length for Fortran strings.

Returns:
np.ndarray

Array of dtype S{maxlen}

cosmic.utils.zcnsts(z)

Calculate constants based on the metallicty * zpars: 1; M below which hook doesn’t appear on MS, Mhook. * 2; M above which He ignition occurs non-degenerately, Mhef. * 3; M above which He ignition occurs on the HG, Mfgb. * 4; M below which C/O ignition doesn’t occur, Mup. * 5; M above which C ignites in the centre, Mec. * 6; value of log D for M<= zpars[2] * 7; value of x for Rgb propto M^(-x) * 8; value of x for tMS = numpy.maximum(tHOOK,x*tBGB) * 9; constant for McHeIf when computing Mc,BGB, mchefl. * 10; constant for McHeIf when computing Mc,HeI, mchefl. * 11; hydrogen abundance. * 12; helium abundance. * 13; constant x in rnumpy.minimum = rgb*x**y used by LM CHeB. * 14; z**0.4 to be used for WD L formula.