Package and Function Info

popsycle.binary_utils module

popsycle.binary_utils.add_magnitudes(mags)

Adds a list of magnitudes

Parameters:
mags: array-like

List or array of magnitudes

Returns:
m_sumfloat

Sum of input magnitudes

popsycle.binary_utils.add_observable_peaks_column(t_prim, t_comp_rb, t_comp_rb_mp, t_lightcurves, delta_m_cutoff=0.1, delta_m_cutoff_secondary=0.02, match_by_field=True)

Adds new column to event table with the number of observable peaks

Parameters:
t_primAstropy table

Events table from refine_binary_events.

t_comp_rbAstropy table

Companion table from refine_binary_events.

t_comp_rb_mpAstropy table

Multi peak table from refine binary events (each row corresponds to a peak in a lightcurve).

t_lightcurvesAstropy table

Lightcurve table from refine_binary_events (each row corresponds to a generated lightcurve).

delta_m_cutofffloat, optional

Bump magnitude cutoff for primary peak (if primary peak < delta_m_cutoff, the number of observable peaks is 0). Default is 0.1.

delta_m_cutoff_secondaryfloat, optional

Bump magnitude cutoff for secondary peaks. Default is 0.02.

match_by_fieldbool, optional

If there are multiple fields, looks for a column called “field_id” and requires the companions and primaries to be in the same field. Default is True.

Returns:
t_primAstropy table

Events table with additional column with the number of observable peaks.

popsycle.binary_utils.cut_Mruns(t_prim, t_comp_rb, t_comp_rb_mp, min_mag, delta_m_cut, u0_cut, ubv_filter, S_LSN)

Make observational cuts on PopSyCLE runs with multiple systems

Parameters:
t_primAstropy table

Events table from refine_binary_events. Must contain ‘observable_n_peaks’ column.

t_comp_rbAstropy table

Companion table from refine_binary_events.

t_comp_rb_mpAstropy table

Multi peak table from refine binary events (each row corresponds to a peak in a lightcurve).

min_magfloat

Minimum baseline or source magnitude (specified by S_LSN).

delta_m_cutfloat or None.

Minimum bump magnitude.

u0_cutfloat

Maximum u0.

ubv_filterstr

Filter name used when cutting on min_mag and delta_m_cut.

S_LSNstr

‘S’ for source mag cut or ‘LSN’ for baseline magnitude cut.

Returns:
t_both_mcutAstropy table

Table with specified observational cuts.

t_both_mcut_one_peakAstropy table

Table with specified observational cuts and only single peaked events.

t_multiples_mcut_multi_peakAstropy table

Table with specified observational cuts and only multipeaked events containing a multiple system.

popsycle.binary_utils.event_table_companion_idxs_to_lists(events)

The event table from refine_binary_events() is saved with ‘companion_idx_list’ as strs so it can be saved as a .fits file. This function switches that column to lists. (Note this changes in place, so input table is changed).

Parameters:
eventsAstropy Table

Event table from refine_binary_events with ‘companion_idx_list’ as strs

Returns:
eventsAstropy Table

Event table with ‘companion_idx_list’ as lists

popsycle.binary_utils.primary_mag_from_system_mag(system_mag, companion_mag)
popsycle.binary_utils.subtract_magnitudes(m1, m2)

Subtracts two magnitudes Expects m1 to be brighter than m2. Will return nan if the opposite is the case or if m1 is nan.

Parameters:
m1float or array-like

Brighter magnitude

m2float or array-like

Dimmer magnitude

Returns:
m_difffloat or array-like

Difference in the corresponding flux of m1 - m2

popsycle.conftest module

Configure Test Suite.

This file is used to configure the behavior of pytest when using the Astropy test infrastructure. It needs to live inside the package in order for it to get picked up when running the tests inside an interpreter using {{ cookiecutter.module_name }}.test().

popsycle.conftest.pytest_configure(config)

Configure Pytest with Astropy.

Parameters:
configpytest configuration

popsycle.converter module

converter.py Functions for converting PopSyCLE data formats.

popsycle.converter.convert_h5_array_dtype_to_compound_dtype(hdf5_file)

Converts h5 files with the array datatype into the compound datatype

Parameters:
hdf5_filestr

Name of the HDF5 file with the array datatype.

Returns:
<hdf5_file>.compound_dtype.fits

Name of the resulting HDF5 file with the compound datatype.

popsycle.ebf module

A module to read and write data in ebf format.

EBF is a binary format for storing data. It is designed to read and write data, easily and efficiently.

  • Store multiple data items in one file, each having a unique tag name

    • tagnames follow the convention of unix style pathname e.g. /x or /mydata/x

    • this allows hierarchical storage of data

  • Automatic type and endian conversion

  • Support for mutiple programming languages

    • data can easily read in C, C++, Fortran, Java, IDL and Matlab

    • facilitates easy distribution of data

  • Comprehensive numpy support

    • data is read back as numpy arrays

    • almost any numpy array can be written

    • Nested numpy structures are also supported

  • Read and write directly a recursive dictionary of numpy arrays

To install

$pip install ebfpy           OR
$pip install ebfpy --user    OR

Alternatively

$tar -zxvf ebfpy_x.x.x.tar.gz
$cd ebfpy_x.x.x
$python setup.py install --user                            OR 
$python setup.py install --user --install-scripts=mypath   OR
$python setup.py install  --install-scripts=mypath 

The –install_scripts option if specified determines the installation location of the command line script ebftkpy, the ebf module is always installed in a standard location. It is better to set this manually (to something like ‘/usr/local/bin’ or somewhere in home) because the standard script installation location might not be in your search path. With –user option generally the scripts are installed in ~/.local/bin/.

To run the test suite just do (from within folder ebfpy_x.x.x)

$./ebf.py 

Example:

Write specific numpy arrays.

>>> import ebf
>>> import numpy
>>> x = numpy.random.rand(2,5)
>>> y = numpy.random.rand(2,5)
>>> ebf.write('check.ebf', '/x', x, "w")
>>> ebf.write('check.ebf', '/y', y, "a")

Write in a different path within an ebf file .

>>> ebf.write('check.ebf', '/mypath/x', x, "a")
>>> ebf.write('check.ebf', '/mypath/y', y, "a")

Read back the written arrays

>>> x1 = ebf.read('check.ebf', '/x')
>>> y1 = ebf.read('check.ebf', '/mypath/y')

Read all items in an ebf path as a dictionary such that data[“x”] is same as x1 such that data[“y”] is same as y1

>>> data = ebf.read('check.ebf', '/mypath/')

Check the contents of the file.

>>> ebf.info('check.ebf')
check.ebf 2460 bytes
------------------------------------------------------------------
name                           dtype    endian  unit       dim       
------------------------------------------------------------------
/.ebf/info                     int64    little             [5]       
/.ebf/htable                   int8     little             [1256]    
/x                             float64  little             [2 5]     
/y                             float64  little             [2 5]     
/mypath/x                      float64  little             [2 5]     
/mypath/y                      float64  little             [2 5]     

Split a structure and write individual data items in path “/mypath/” in an ebf file.

>>> dth = numpy.dtype([('data_u1', 'u1', (2, 5)), ('data_u2', 'u2', (2, 5))])
>>> data = numpy.zeros(1, dtype = dth)
>>> ebf.write('check.ebf', '/mypath/', data, "w")
>>> data1 = ebf.read('check.ebf', '/mypath/')
>>> ebf.info('check.ebf') 
check.ebf 1906 bytes
------------------------------------------------------------------
name                           dtype    endian  unit       dim       
------------------------------------------------------------------
/.ebf/info                     int64    little             [5]       
/.ebf/htable                   int8     little             [1256]    
/mypath/data_u1                uint8    little             [2 5]     
/mypath/data_u2                uint16   little             [2 5] 

Write a nested structure and read it back.

>>> dth = numpy.dtype([('data_u1', 'u1', (2, 5)), ('data_u2', 'u2', (2, 5))])
>>> dth1 = numpy.dtype([('data_u1', 'u1', (2, 5)), ('point1', dth, (1, ))])
>>> data = numpy.zeros(10, dtype = dth1)
>>> ebf.write("check.ebf", "/data", data, "w")
>>> data1 = ebf.read("check.ebf", "/data")
>>> ebf.info("check.ebf")
check.ebf 2247 bytes
------------------------------------------------------------------
name                           dtype    endian  unit       dim       
------------------------------------------------------------------
/.ebf/info                     int64    little             [5]       
/.ebf/htable                   int8     little             [1256]    
/data                          struct   little             [10]      
structure definition:
ver-1 
struct {
uint8 data_u1 2  2  5  ;
struct {
uint8 data_u1 2  2  5  ;
uint16 data_u2 2  2  5  ;
} point1 1 1   ; 
} anonymous 1 1   ; 

Write a string and read it back as string. Note, return type is numpy.ndarray, hence have to use tostring() method to convert it back to string.

>>> x = "abcdefghijkl"
>>> ebf.write("check.ebf", "/mystr", numpy.array(x), "w")
>>> y = ebf.read("check.ebf", "/mystr").tostring()

Write a list of string and read it back as numpy.ndarray of type numpy.string

>>> x = ["abc", "abcdef"]
>>> ebf.write("check.ebf", "/mystr", numpy.array(x), "w")
>>> y = ebf.read("check.ebf", "/mystr")
>>> print y[0] == "abc",y[1] == "abcdef"
True True

Write with units and read it back.

>>> data = numpy.zeros(1, dtype = "int32")
>>> ebf.write('check.ebf', '/data', data, "w",dataunit="100 m/s")
>>> print, ebf.unit('check.ebf', '/data')

Check if a data item is present.

>>> ebf.containsKey('check.ebf', '/data')
class popsycle.ebf.EbfFile(filename, path, mode, dataunit='', cache=100)

Bases: object

Methods

read_ind:

Read indicies.

close()
read(i, nsize=1)
read_ind(ind)

This method looks for groups of contiguous indices in ‘ind’ and loads those blocks of memory with a single copy command. This method is ~50% faster than looping over each index and running: data[i] = self.read(ind[i])

Parameters:
indstr

List or array of indices to be read.

write(data)
popsycle.ebf.cat(filename, tagname, delimiter=' ', tableon=0)

Print data items in ascii format.

Parameters:
filenamestr
tagnamestr
delimiterstr, optional.

‘ ‘ or ‘, ‘ for csv. Default is ‘ ‘.

tableonint, optional

Default is 0.

Examples

>>> ebf.cat('check.ebf','/x /y',', ')
>>> ebf.cat('check.ebf','/x+',', ')
>>> ebf.cat('check.ebf','/x+',', ',1)
popsycle.ebf.check(filename)

Check if the file is not corrupted.

Parameters:
filenamestr
Returns:
ecodeint

Error code.

Examples

>>> ebf.check('check.ebf')
popsycle.ebf.clearEbfMap()

Clears cached information about all files. This could be used to conserve memory after a lot of different files have been read.

>>> ebf.clearEbfMap()
popsycle.ebf.containsKey(filename, dataname)

Check if a data item is present in an ebf file.

Parameters:
filenamestr

a string specifying filename

datanamestr

name of data item

Returns:
1 if an item is present else 0

Examples

>>> ebf.containsKey('check.ebf','/x')
popsycle.ebf.copy(filename1, filename2, mode='a', tagnames='', outpath=None)

Copy data items from one file to another.

Parameters:
filename1str
filename2str
modestr, optional

‘w’ or ‘a’. Default is ‘a’.

tagnamesstr, optional

If blank then copies all items or else one can supply space separated list of data items as a single string. Default is ‘’.

outpathstr or None, optional

Path ending with ‘/’ into which to copy items. Default is None.

Examples

>>> ebf.copy("check1.ebf",'check2.ebf','/x /y','w')
>>> ebf.copy("check1.ebf",'check2.ebf','/x')
>>> ebf.copy("check1.ebf",'check2.ebf')
popsycle.ebf.descr2sdef(descr, units='')
popsycle.ebf.dict2npstruct(data, basekey=None, keylist=None)

Convert a python dict containing numpy arrays to numpy struct

Parameters:
datadict of numpy.arrays
basekeystr or None, optional

Only those items in dict whose size match that of data[bsekey] will be used. Default is None.

keyliststr or None, optional

list of keys to beused when constructing npstruct. Default is None.

Returns:
data1numpy struct
popsycle.ebf.diff(filename1, filename2)

Perform diff operation on two files. Ignores data items starting with “/.” which are for internal use. If file contents are same it does not print anything.

Parameters:
filename1str
filename2str

Examples

>>> ebf.diff("check1.ebf","check2.ebf")
popsycle.ebf.getHeader(filename, dataname)

Get header of the data item

Parameters:
filenamestr
datanamestr
Returns:
headerstr

Examples

>>> ebf.getHeader("check.ebf","/x")
popsycle.ebf.info(filename, option=0)

Get summary of the contents of a file.

Parameters:
filenamestr
optionint, optional

Default is 0.

Examples

>>> ebf.info('check.ebf')
popsycle.ebf.initialize(filename)

Initialize a file for writing with mode=’w’. After this one can use mode=’a’ to write rest of the items.

Parameters:
filenamestr

Examples

>>> ebf.initialize('check.ebf')
>>> ebf.write('check.ebf','/x',[0,1,2],'a')
>>> ebf.write('check.ebf','/y',[0,1,2],'a')
is same as
>>> ebf.write('check.ebf','/x',[0,1,2],'w')
>>> ebf.write('check.ebf','/y',[0,1,2],'a')
popsycle.ebf.iterate(filename, tagname, cache)

An iterator to read in data, part by part of a given size. Useful for reading big arrays which are difficult to fit in RAM.

Parameters:
filenamestr
tagnamestr

The name of data to be read. Multiple items of same size can be read by appending a + sign.

cacheint

No of data items to read at a time

Examples

>>> temp=0.0
>>> for x in ebf.iterate('check.ebf','/x',1000):
>>>     temp=temp+np.sum(x)   

To read all items whose size match with size of “/x”

>>> temp=0.0
>>> for data in ebf.iterate('check.ebf','/x+',1000):
>>>     temp=temp+np.sum(data['/x'])   
popsycle.ebf.join(files, path, outfile, outpath, mode)
popsycle.ebf.keys(filename, dataname)
popsycle.ebf.npstruct2dict(data)

Convert an array of numpy struct to a python dict of numpy arrays

Parameters:
datanumpy struct
Returns:
data1dict of numpy arrays
popsycle.ebf.read(filename, path='/', recon=0, ckon=1, begin=0, end=None)

Read data from an ebf file

Parameters:
filenamestr
pathstr, optional

tagname of data to be read from the ebf file or a path to the data items within the file. If ending with + then all arrays in the same path having same size as the specfied array are read. Useful to load tables where individual columns are written separately.

reconint, optional

Should be 1 if one wants to load data objects recursively. Should be 0 if one wants to load data objects only under current path.Defualt is 0.

ckonint, optional

option that determines if checksum is to be compared with checksum on file. Default is to compare, but if there is little possibility of file being externally modified then it can be set to 0.

Returns:
numpy.ndarray or a dictionary of numpy.ndarray. If multiple data items are to be read as a dictionary, the path must end with ‘/’ in the later case.
popsycle.ebf.read_ind(filename, tagname, ind)

Read data from specified locations in a file

Parameters:
filenamestr
tagnamestr

The name of data to be read.

indstr

List or array of indices to be read.

Returns:
data
popsycle.ebf.rename(filename, oldkey, newkey)

Rename a data item in an ebf file

Parameters:
filename: str
oldkey: str

The name of key to rename.

newkey: str

The new name. If new key is blank ‘’, then a name of the form ‘/.tr’+oldkey+’.X’ is created. Here X is a an integer greater than equal to zero, which is incremented each time the item with same name is deleted.

Examples

>>> ebf.rename('check.ebf','/x1','/x2')
>>> ebf.rename('check.ebf','/x1','')    
popsycle.ebf.sdef2descr(sdef)
popsycle.ebf.stat(filename, tagname, recon=0)

Get statistics of a data item.

Parameters:
filenamestr
tagnamestr
reconint

Default is 0.

Examples

>>> ebf.stat('check.ebf','/x /y ')
popsycle.ebf.swapEndian(filename)

Swaps the endianess of the file. Little to Big or Big to Little.

Parameters:
filenamestr

Examples

>>> ebf.swapEndian("check.ebf")
popsycle.ebf.unit(filename, dataname)

Get physical units of the data type if supplied in file or else empty string

Parameters:
filenamestr
datanamestr
Returns:
unitstr

Examples

>>> ebf.unit("check.ebf","/x")
popsycle.ebf.update_ind(filename, dataname, data, ind=None)

Update existing data array in a file at user given index positions.

Parameters:
filenamestr
datanamestr

The name of data to be upated.

dataarray

Data to be updated.

indarray or None, optional

indices of the array on file that needs to be updated. Default is None.

popsycle.ebf.write(filename, tagname, data, mode, dataunit='')

Write data to a file

Parameters:
filenamestr
tagnamestr

the name of data to be written to the ebf file or a path ending with ‘/’ if multiple items are to be written

datanumpy.ndarray

data to be to be written

modestr

writing mode, “w” to write a fresh file or “a” to append an existing file

dataunitstr, optional

units of data default is a blank string

popsycle.filters module

filters.py Functions (and their associated functions) for additional photometric systems.

popsycle.filters.generate_ubv_to_ztf_grid(iso_dir, filter_name)

Creates the 2D transformational matrix ubv_to_ztf-r_grid.npz and ubv_to_ztf-g_grid.npz necessary for generating ztf-g and ztf-r magnitudes from the UBV filters.

2D transformational matrix is valid for values of:

0 < ubv_V - ubv_R < 6 0 < ubv_B - ubv_V < 6

ubv-to-ztf-g

x-axis : ubv_V - ubv_R y-axis : ubv_B - ubv_V z-axis : ztf_g - ubv_V

ubv-to-ztf-r

x-axis : ubv_V - ubv_R y-axis : ubv_B - ubv_V z-axis : ztf_r - ubv_R

ubv-to-ztf-i

x-axis : ubv_V - ubv_R y-axis : ubv_B - ubv_V z-axis : ztf_i - ubv_I

Parameters:
iso_dirfilepath

Where are the isochrones stored (for SPISEA)

filter_namestr

The name of the filter in which to calculate all the microlensing events. Must be either ‘g’ or ‘r’.

popsycle.filters.load_ubv_to_ztf_grid(filter_name)

Loads the 2D transformational matrix ubv_to_ztf-r_grid.npz and ubv_to_ztf-g_grid.npz necessary for generating ztf-g and ztf-r magnitudes from the UBV filters, as well as the kdtree of those values.

2D transformational matrix is valid for values of:

0 < ubv_V - ubv_R < 6 0 < ubv_B - ubv_V < 6

ubv-to-ztf-g

x-axis : ubv_V - ubv_R y-axis : ubv_B - ubv_V z-axis : ztf_g - ubv_V

ubv-to-ztf-r

x-axis : ubv_V - ubv_R y-axis : ubv_B - ubv_V z-axis : ztf_r - ubv_R

ubv-to-ztf-i

x-axis : ubv_V - ubv_R y-axis : ubv_B - ubv_V z-axis : ztf_i - ubv_I

Parameters:
filter_namestr

The name of the filter in which to calculate all the microlensing events. Must be either ‘g’ or ‘r’ or ‘i’.

Returns:
ubv_to_ztf_grid2D numpy array

2D grid array of UBV colors with each cell containing the difference between a ztf filter and a ubv filter

kdtreecKDTree

kdtree containing the grid of colors on the x-axis and y-axis

popsycle.filters.transform_ubv_to_ztf(filter_name, ubv_B, ubv_V, ubv_R, ubv_I=None)

Converts ubv filters into ztf filters.

Function is valid for values of:

0 < ubv_V - ubv_R < 6 0 < ubv_B - ubv_V < 6

Parameters:
filter_namestr

ZTF filter name of converted photometry Can be ‘g’, ‘r’, or ‘i’ If converting to ztf_i, then ubv_I must be provided

ubv_Barray of floats

ubv_B photometry of galaxia / SPISEA sources

ubv_Varray of floats

ubv_V photometry of galaxia / SPISEA sources

ubv_Rarray of floats

ubv_R photometry of galaxia / SPISEA sources

ubv_Iarray of floats, optional

ubv_I photometry of galaxia / SPISEA sources, required for converting to ztf_i

Returns:
ztf_magarray of floats

ztf photometry of galaxia / SPISEA sources in filter_name

popsycle.filters.ztf_mag_AB_to_vega(ztf_mag_AB, filter_name)

Converts AB magnitudes into vega magnitudes for ztf filters. Extrapolated from http://astroweb.case.edu/ssm/ASTR620/alternateabsmag.html using the effective wavelengths from http://svo2.cab.inta-csic.es/svo/theory/fps3/

Parameters:
ztf_mag_ABfloat, array of floats

ztf photometry of galaxia / SPISEA sources in AB system

filter_namestr

The name of the filter in which to calculate all the microlensing events. Must be either ‘g’ or ‘r’ or ‘i’.

Returns:
ztf_mag_vegafloat, array of floats

ztf photometry of galaxia / SPISEA sources in vega system

popsycle.filters.ztf_mag_vega_to_AB(ztf_mag_vega, filter_name)

Converts vega magnitudes into AB magnitudes for ztf filters. Extrapolated from http://astroweb.case.edu/ssm/ASTR620/alternateabsmag.html using the effective wavelengths from http://svo2.cab.inta-csic.es/svo/theory/fps3/

Parameters:
ztf_mag_vegafloat, array of floats

ztf photometry of galaxia / SPISEA sources in vega system

filter_namestr

The name of the filter in which to calculate all the microlensing events. Must be either ‘g’ or ‘r’ or ‘i’.

Returns:
ztf_mag_ABfloat, array of floats

ztf photometry of galaxia / SPISEA sources in AB system

popsycle.orbits module

exception popsycle.orbits.EccAnomalyError(message)

Bases: Exception

class popsycle.orbits.Orbit

Bases: object

Exerpted from orbits.py from gcworks

Methods

kep2xyz:

Generates (r, v, a) in AU, AU/yr, and AU/yr^2 respectively from keplarian parameters.

eccen_anomaly:

Calculates the eccentricity anomaly.

eccen_anomaly(m, ecc, thresh=1e-10)

Calculates the eccentricity anomaly

Parameters:
m: numpy array

Mean anomalies

ecc: float between 0-1

The eccentricity of the orbit

kep2xyz(epochs)

Generates (r, v, a) in AU, AU/yr, and AU/yr^2 respectively from keplarian parameters.

epoch: numpy array

Array of times (in years) that you would like to compute the parameters for

mass: float or array-like

Mass of primary object

An example call is:

>>> orb = orbits.Orbit()
>>> orb.w = omega # [degrees]
>>> orb.o = bigOm # [degrees]
>>> orb.i = incl # [degrees]
>>> orb.e = e_mag # float between 0 and 1
>>> orb.p = p # [years]
>>> orb.t0 = t0 # [years] This is initial
>>> orb.mass = mass # [Msun]

(r, v, a) = orb.kep2xyz(array([refTime]))

popsycle.orbits.a_to_P(mass, a)

Goes from semimajor axis in AU to period in years

Parameters:
mass: float or array-like

Primary object mass in Msun.

a: float or array-like

Semimajor axis in AU.

Returns:
period: float or array-like

Orbital period in years.

popsycle.orbits.add_mult_positions(companions, ss_pos, logAge, add_velocities=False)

Adds x and y positions of multiple companions by transforming keplerian parameters to xyz in AU using code origially from gcworks and random initial times. Then adding them to the random posiiton of the primary object.

Parameters:
ss_pos: astropy table

Star system table with positions added with add_positions()

companion: astropy table

Companion table without positions

logAge: float or int

Log of age of cluster with age in years

Returns:
companion_temp: astropy table

Companion table with positions added

popsycle.orbits.add_positions(ss)

Adds x and y positions randomly in a box of length and width 40000 AU for each system.

Parameters:
ss: astropy table

Star system table without positions

Returns:
ss_temp: astropy table

Star system table with positions added

popsycle.orbits.distance_to_center_of_mass(ss_pos, companions_pos)

Adds extra column to star system and companions table with x and y distance to the center of mass in AU. Assumes hierarchical triples (two closest stars orbit their center of mass and triple orbits them) and no quads+.

Parameters:
ss_pos: astropy table

Star system table with positions added with add_positions()

companion_pos: astropy table

Companion table with positions added with add_mult_positions()

Returns:
ss_pos_temp: astropy table

Star system table with distance to center of mass in AU added

companion_pos_temp: astropy table

Companion table with distance to center of mass in AU added

popsycle.orbits.plot_companion_orbit(ss, companions_pos, logAge, t0=None, system=None)

Plots the orbit of one system assuming the primary object is at (0,0). By default random companion and initial time.

Parameters:
ss: astropy table

Star system table (does not matter if it has positions or not)

companion_pos: astropy table

Companion table with positions added with add_mult_positions()

logAge: float or int

Log of age of cluster with age in years

t0: float or int, optional

Initial time of creation of the system in years. Default random.

system: int, optional

Index of desired companion in companion_pos table. Default random.

popsycle.orbits.plot_projected_cluster(ss_pos, companions_pos)

Plots projected cluster with lines between companions and primary stars

Parameters:
ss_pos: astropy table

Star system table with positions added with add_positions()

companion_pos: astropy table

Companion table with positions added with add_mult_positions()

popsycle.run module

run.py Executable to run the PopSyCLE pipeline.

popsycle.run.generate_config_file(config_filename, config)

Save configuration parameters from a dictionary into a yaml file

Parameters:
config_filenamestr

Name of the configuration file

configdict

Dictionary containing the configuration parameters

popsycle.run.generate_field_config_file(longitude, latitude, area, config_filename='field_config.yaml')

Save field configuration parameters from a dictionary into a yaml file

Parameters:
longitudefloat

Galactic longitude, ranging from -180 degrees to 180 degrees

latitudefloat

Galactic latitude, ranging from -90 degrees to 90 degrees

areafloat

Area of the sky that will be generated, in square degrees

config_filenamestr, optional

Name of the configuration file Default: field_config.yaml

popsycle.run.generate_popsycle_config_file(radius_cut=2, obs_time=1000, n_obs=101, theta_frac=2, blend_rad=0.75, isochrones_dir='/Users/myself/popsycle_isochrones', IFMR='Raithel18', galaxia_galaxy_model_filename='/Users/myself/galaxia_galaxy_model_filename', bin_edges_number=None, BH_kick_speed_mean=50, NS_kick_speed_mean=400, photometric_system='ubv', filter_name='R', red_law='Damineli16', multiplicity=None, binning=True, config_filename='popsycle_config.yaml')

Save popsycle configuration parameters from a dictionary into a yaml file

Parameters:
radius_cutfloat

Initial radius cut, in ARCSECONDS.

obs_timefloat

Survey duration, in DAYS.

n_obsint

Number of observations.

theta_fracfloat

Another cut, in multiples of Einstein radii.

blend_radfloat

Stars within this distance of the lens are said to be blended. Units are in ARCSECONDS.

isochrones_dirstr

Directory for SPISEA isochrones

IFMRstring

The name of the IFMR object from SPISEA. For more information on these objects see ifmr.py in SPISEA. ‘Raithel18’ = IFMR_Raithel18 ‘Spera15’ = IFMR_Spera15 ‘SukhboldN20’ = IFMR_N20_Sukhbold

galaxia_galaxy_model_filenamestr

Name of the galaxia galaxy model, as outlined at https://github.com/jluastro/galaxia

bin_edges_numberint
Number of edges for the bins

bins = bin_edges_number - 1

Total number of bins is

N_bins = (bin_edges_number - 1)**2

If None (default), then number of bins is

bin_edges_number = int(60 * 2 * radius) + 1

BH_kick_speed_meanfloat

Mean of the birth kick speed of BH (in km/s) maxwellian distrubution. Defaults to 50 km/s.

NS_kick_speed_meanfloat

Mean of the birth kick speed of NS (in km/s) maxwellian distrubution. Defaults to 400 km/s based on distributions found by Hobbs et al 2005 ‘A statistical study of 233 pulsar proper motions’. https://ui.adsabs.harvard.edu/abs/2005MNRAS.360..974H/abstract

photometric_systemstr

The name of the photometric system in which the filter exists.

filter_namestr

The name of the filter in which to calculate all the microlensing events. The filter name convention is set in the global filt_dict parameter at the top of this module.

red_lawstr

The name of the reddening law to use from SPISEA.

multiplicity: str

If a resovled multiplicity object is specified, the table will be generated with resolved multiples. Default is None.

binningbool

If set to True, bins files as specified by bin_edges_numbers or default. If set to False, no bins (SET TO FALSE IF DOING FULL SKY DOWNSAMPLED). Default is True.

config_filenamestr, optional

Name of the configuration file Default: popsycle_config.yaml

popsycle.run.generate_slurm_config_file(path_python='python', account='ulens', queue='regular', resource='cpu', memory=512, n_cores_per_node=64, n_nodes_max=3072, memory_max=512, walltime_max='24:00:00', additional_lines=['module load cray-hdf5/1.10.5.2', 'export HDF5_USE_FILE_LOCKING=FALSE'], config_filename='slurm_config.yaml')

Save slurm configuration parameters from a dictionary into a yaml file

Parameters:
path_pythonstr

Path to the python executable

accountstr

Project account name to charge

queuestr

Scheduler queue type

resourcestr

Computing resource name

memoryint

Amount of memory allocated for the job, in units of GB

n_cores_per_nodeint

Number of cores in each node of the compute resource

n_nodes_maxint

Total number of nodes in the compute resource

memory_maxint

Memory per node in the computer resource, in units of GB

walltime_maxint

Maximum number of hours for single job on the compute resource Format: hh:mm:ss

additional_lineslist of strings

Additional lines to be run before executing run.py

config_filenamestr, optional

Name of the configuration file Default: slurm_config.yaml

popsycle.run.generate_slurm_script(slurm_config_filename, popsycle_config_filename, path_run, output_root, longitude, latitude, area, walltime, n_cores_perform_pop_syn=1, n_cores_calc_events=1, n_cores_refine_binary_events=1, multi_proc_refine_binary_events=True, jobname='default', seed=None, overwrite=False, submitFlag=True, returnJobID=True, dependencyJobID=None, skip_galaxia=False, skip_perform_pop_syn=False, skip_calc_events=False, skip_refine_events=False, skip_refine_binary_events=False, verbose=0)

Generates (and possibly submits) the slurm script that executes the PopSyCLE pipeline

Parameters:
slurm_config_filenamestr

Name of slurm_config.yaml file containing the slurm parameters that will be used the generate the slurm script header.

popsycle_config_filenamestr

Name of popsycle_config.yaml file containing the PopSyCLE parameters that will be passed along to the run_on_slurm.py command in the slurm script.

path_runstr

Directory containing the parameter file and PopSyCLE output files

output_rootstr

Base filename of the output files Examples:

  • ‘{output_root}.h5’

  • ‘{output_root}.ebf’

  • ‘{output_root}_events.h5’

longitudefloat

Galactic longitude, ranging from -180 degrees to 180 degrees

latitudefloat

Galactic latitude, ranging from -90 degrees to 90 degrees

areafloat

Area of the sky that will be generated, in square degrees

walltimestr

Amount of walltime that the script will request from slurm. Format: hh:mm:ss

jobnamestr, optional

The name of the slurm job and run_popsycle execution file. If ‘default’, the format will be: <longitude>_<latitude>_<output_root>

seedint, optional

If non-None, all random sampling will be seeded with the specified seed, forcing identical output for SPISEA and PopSyCLE. Default None.

overwritebool, optional

If True, overwrites output files. If False, exists the function if output files are already on disk. Default is False.

submitFlagbool, optional

If True, script will be submitted to the slurm scheduler after being written to disk. If False, it will not be submitted. Default is True

returnJobIDbool, optional

If True and submitFlag is True, function will return the SLURM job id after script submission. If False or submitFlag is False, function will return None. Default is True

dependencyJobIDint, optional

If non-None and submitFlag is True, submitted job will only run after dependencyJobID is completed with no errors. Default is None

n_cores_perform_pop_synint, optional

Number of cores for executing synthetic.perform_pop_syn Default is 1.

n_cores_calc_eventsint, optional

Number of cores for executing synthetic.calc_events Default is 1.

n_cores_refine_binary_eventsint, optional

Number of cores for executing synthetic.refine_binary_events Default is 1.

multi_proc_refine_binary_eventsbool, optional

Even if n_proc = 1, a pool is still created. If multi_proc = False, instead there is just a for-loop to generate and analyze the lightcurves. If multi_proc == False, n_proc must = 1. Default is True.

skip_galaxiabool, optional

If True, pipeline will not run Galaxia and assume that the resulting ebf file is already present. Default is False

skip_perform_pop_synbool, optional

If True, pipeline will not run perform_pop_syn and assume that the resulting h5 file is already present. Default is False

skip_calc_eventsbool, optional

If True, pipeline will not run calc_events and assume that the resulting events and blends files are already present. Default is False

skip_refine_eventsbool, optional

If True, pipeline will not run refine_events. Default is False

skip_refine_binary_eventsbool, optional

If True, pipeline will not run refine_binary_events. If specified multiplicity is None, will be True. Default is False

verboseint, optional

Level of debugging information to print to stderr. Set to 0 for minimal information. Coarse timing at 2 and fine timing at 4. Default is 0.

Returns:
<output_root>.h5hdf5 file

NOTE: This is what _bin_lb_hdf5 returns. An hdf5 file with datasets that correspond to the longitude bin edges, latitude bin edges, and the compact objects and stars sorted into those bins.

<path_run>/<output_root>_field_config.yamlyaml file

Field config file containing the galactic parameters needed to run pipeline

<path_run>/run_popsycle_<jobname>.shyaml file

SLURM batch script for submitting job with pipeline run

None or slurm_jobidstr

If submitFlag is True and returnJobID is True, function returns the SLURM job ID after script submission. Otherwise, function returns None

popsycle.run.load_config_file(config_filename)

Load configuration parameters from a yaml file into a dictionary

Parameters:
config_filenamestr

Name of the configuration file

Returns:
configdict

Dictionary containing the configuration parameters

popsycle.run.main()
popsycle.run.run(output_root='root0', field_config_filename='field_config.yaml', popsycle_config_filename='popsycle_config.yaml', n_cores_perform_pop_syn=1, n_cores_calc_events=1, n_cores_refine_binary_events=1, multi_proc_refine_binary_events=True, verbose=0, seed=None, overwrite=False, skip_galaxia=False, skip_perform_pop_syn=False, skip_calc_events=False, skip_refine_events=False, skip_refine_binary_events=False)
popsycle.run.tar_run_results(extension_list=['ebf', 'fits', 'h5', 'log', 'out', 'sh', 'txt', 'yaml'], include_bin_phot=True, output_prefix=None)

Creates a tarball of all results from executing run.py. This script assumes that all instances of generat_slurm_script were run with path_run set to subfolders to a common folder, and that this script is being run in that common folder. Failure to do so will create some funky tarball with files you don’t want in it.

Parameters:
extension_listlist

List of extensions to include in tarball. Defaults to all possible extensions.

include_bin_photbool

If True and running with multiplicity, include lightcurves generated by refine_binary_events. Default True.

output_prefixstr
If not None, add output_prefix before name of tarball:

{output_prefix}_runs.tar

Returns:
<output_prefix>_runs.tartarball file

popsycle.synthetic module

synthetic.py Functions (and their associated functions) for running the PopSyCLE pipeline. Including: - write_galaxia_params - perform_pop_syn - calc_events - refine_events - refine_binary_events

popsycle.synthetic.bsbl_model_gen(bsbl_parameter_dict)

Generate bsbl_photastrom_par_param1 model from parameter dict

Parameters:
bspl_parameter_dictdict

Dictionary of the BSBL_PhotAstrom_Par_Param1 parameters

Returns:
bsbl model
popsycle.synthetic.bspl_model_gen(bspl_parameter_dict)

Generate bspl_photastrom_par_param1 model from parameter dict

Parameters:
bspl_parameter_dictdict

Dictionary of the BSPL_PhotAstrom_Par_Param1 parameters

Returns:
bspl model
popsycle.synthetic.calc_DM(r, M)

Calculate the distance modulus: m = M + 5log10(100*r/kpc)

Parameters:
Mfloat or array

Absolute magnitude of star

rfloat or array

Distance of star from sun (in kpc)

Returns:
mfloat or array

Apparent magnitude of star

popsycle.synthetic.calc_app_mag(r, M, E, f)

Calculate the apparent magnitude (i.e. distance modulus plus extinction)

Parameters:
Mfloat or array

Absolute magnitude of star

rfloat or array

Distance of star from sun (in kpc)

Efloat or array

Extinction law

ffloat or array

Coefficient for that particular band or whatever

Returns:
mfloat or array

Apparent magnitude of star

popsycle.synthetic.calc_blend_and_centroid(filter_name, red_law, blend_tab, photometric_system='ubv')

Given the absolute magnitudes of a bunch of things, calculate their blended apparent magnitude and flux. Also calculate the centroid of these things. Assumes all binaries are blended.

Filter name is ‘j’, ‘i’, etc. red_law is Damineli16, Schlegel99, etc.

popsycle.synthetic.calc_bump_amp(u0, f_S, f_L, f_N)

Calculate the “bump” amplitude, given the minimum separation and the fluxes of the (unmagnified) source, lens, and neighbors. The bump amplitude (mags) is: abs(m_peak - m_base) = -2.5 log10 ((A(u0) * f_S + f_L + f_N)/(f_S + f_L + f_N))

Parameters:
u0float or array

Dimensionless source-lens angular separation, closest approach

f_Sfloat or array

Flux from source (arbitrary units)

f_Lfloat or array

Flux from lens (arbitrary units)

f_Nfloat or array

Flux from neighbors (arbitrary units)

Returns:
m_bumpfloat or array

Bump magnitude

popsycle.synthetic.calc_closest_approach(event_tab, survey_duration)

Calculate the point of closest approach, during a given interval. Return the position and time of closest approach. This algorithm comes from a little writeup called “Point of Closest Approach for the Linear Motion of Two Particles in 2-D”

Parameters:
event_tabastropy table

This should take the astropy table that comes from the output of calc_events.

survey_durationint or float

Survey duration, in days

Returns:
u0array (same length as event_tab)

Minimum separation (normalized to Einstein radius)

t0array (same length as event_tab)

Time at minimum separation (days)

popsycle.synthetic.calc_delta_c(u, thetaE)

Calculate the maximum centroid shift for a dark lens, no neighbors

Parameters:
ufloat or array

Dimensionless lens-source separation, normalized in Einstein radius units.

thetaEfloat

Einstein radius of lens.

Returns:
delta_cfloat or array

Maximum centroid shift

popsycle.synthetic.calc_diff_limit_blend(event_fits_file, blend_fits_file, blend_rad)

Given a table of events and blends, calculate what the blending would be for a smaller blending radius (e.g. table is for seeing limited, and you want what the diffraction limit blend is.)

popsycle.synthetic.calc_distance(event_tab, time)

Calculate the separation of two different objects at some given time. With sign convention from Gould 2004: u0 > 0 then the source is to the east of the lens u0 < 0 then the source is to the west of the lens

Parameters:
event_tabastropy table
timeint/float
Returns:
uarray (same length as astropy table)
popsycle.synthetic.calc_events(hdf5_file, output_root2, radius_cut=2, obs_time=1000, n_obs=101, theta_frac=2, blend_rad=0.65, n_proc=1, overwrite=False, hdf5_file_comp=None)

Calculate microlensing events

Parameters:
hdf5_filestr

Name of the HDF5 file.

output_root2str

The name for the h5 file

radius_cutfloat

Initial radius cut, in ARCSECONDS.

obs_timefloat

Survey duration, in DAYS.

n_obsint

Number of observations.

theta_fracfloat

Another cut, in multiples of Einstein radii.

blend_radfloat

Stars within this distance of the lens are said to be blended. Units are in ARCSECONDS.

n_procint, optional

Number of processors to use. Should not exceed the number of cores. Default is one processor (no parallelization).

overwritebool, optional

If set to True, overwrites output files. If set to False, exists the function if output files are already on disk. Default is False.

hdf5_file_comp: str

String of hdf5 file of companion events created in perform_pop_syn(). Default is None.

Returns:
<output_root2>_events.fitsAstropy .fits table

Table of candidate microlensing events. The number of rows corresponds to the number of candidate events.

popsycle.synthetic.calc_ext(E, f)

Calculate the magnitude of extinction.

Parameters:
Efloat or array

Extinction law

ffloat or array

Coefficient for that particular band or whatever

Returns:
m_Efloat or array

Magnitude of extinction

popsycle.synthetic.calc_magnification(u)

Calculate the magnification factor A(u)

Parameters:
ufloat or array

Dimensionless lens-source separation, normalized in Einstein radius units

Returns:
Magnification factorfloat or array
popsycle.synthetic.calc_sph_motion(vx, vy, vz, r, b, l)

Calculate velocities in the r directions and proper motions in l, b directions.

Parameters:
vx, vy, vzfloat or array

Heliocentric velocities vx, vy, and vz (in km/s)

r, b, lfloat or array

Galactic coordinates r, b, and l (in kpc and degrees)

Returns:
vr, mu_b, mu_lcosbfloat or array (in km/s and mas/yr)

Radial velocity and proper motions

popsycle.synthetic.calculate_binary_angles(joined_table)
  • Calculates the following angles to the companion array:

    • alpha: angle between North and binary axis (East of North)

    • phi_pi_E: angle between North and proper motion vector (East of North)

    • phi: angle between the proper motion and the binary axis

  • Each set of angles is for the source if the companion is assocaited with the source or the lens if the companion is associated with the lens.

  • Binary parameters established in a galactic spherical coordinate systems.

  • Big Omega measured from galactic north increasing in the direction of galactic east (positive l).

Parameters:
joined_tablepandas table

Joined companion and event table on obj_id_L and obj_id_S

Returns:
alphaslist

Angle between North and binary axis (East of North)

phi_pi_Eslist

Angle between North and proper motion vector (East of North)

phislist

Angle between the proper motion and the binary axis (phi_pi_E - alpha)

popsycle.synthetic.einstein_radius(M, d_L, d_S)

Calculates the einstein radius, in mas

Parameters:
Mfloat

Lens current mass, in solar masses

d_Lfloat

Distance to lens, in kpc

d_Sfloat

Distance to source, in kpc

Returns:
Einstein radius, in mas
popsycle.synthetic.galactic_to_heliocentric(r, b, l)

Converts from galactic coordinates to heliocentric coordinates.

Parameters:
r, b, lfloat or array

Galactic coordinates r, b and l (in kpc and degrees)

Returns:
x, y, zfloat or array

Heliocentric coordinates x, y, and z (in kpc)

popsycle.synthetic.get_Alambda_AKs(red_law_name, lambda_eff)

Get Alambda/AKs. NOTE: this doesn’t work for every law in SPISEA! Naming convention is not consistent. Change SPISEA or add if statements?

Parameters:
red_law_namestr

The name of the reddening law

lambda_efffloat

Wavelength in microns

Returns:
Alambda_AKsfloat

Alambda/AKs

popsycle.synthetic.get_bsbl_lightcurve_parameters(event_table, comp_table, comp_idx_L, comp_idx_S, photometric_system, filter_name, red_law, event_id=None)

Find the parameters for BSPL_PhotAstrom_Par_Param2 from event_table and comp_table.

Parameters:
event_tableAstropy table

Table containing the events calculated from refine_events.

comp_tableAstropy table

Table containing the companions calculated from refine_events.

comp_idx_Lint

Index into the comp_table of the lens companion for which the model is being calculated.

comp_idx_Sint

Index into the comp_table of the source companion for which the model is being calculated.

photometric_systemstr

The name of the photometric system in which the filter exists.

filter_namestr

The name of the filter in which to calculate all the microlensing events. The filter name convention is set in the global filt_dict parameter at the top of this module.

red_lawstr

Redenning law

event_idfloat or None, optional

Corresponding event_id in event_table to companion id. Default is None.

Returns:
bsbl_parameter_dictdict

Dictionary of the BSBL_PhotAstrom_Par_Param2 parameters

obj_id_Lint

Object id of the lens associated with event

obj_id_Sint

Object id of the source associated with event

popsycle.synthetic.get_bspl_lightcurve_parameters(event_table, comp_table, comp_idx, photometric_system, filter_name, red_law, event_id=None)

Find the parameters for BSPL_PhotAstrom_Par_Param1 from event_table and comp_table.

Parameters:
event_tableAstropy table

Table containing the events calculated from refine_events.

comp_tableAstropy table

Table containing the companions calculated from refine_events.

comp_idxint

Index into the comp_table of the companion for which the psbl is being calculated.

photometric_systemstr

The name of the photometric system in which the filter exists.

filter_namestr

The name of the filter in which to calculate all the microlensing events. The filter name convention is set in the global filt_dict parameter at the top of this module.

red_lawstr

Redenning law

event_idfloat or None, optional

Corresponding event_id in event_table to companion id

Returns:
bspl_parameter_dictdict

Dictionary of the BSPL_PhotAstrom_Par_Param1 parameters

obj_id_Lint

Object id of the lens associated with event

obj_id_Sint

Object id of the source associated with event

popsycle.synthetic.get_psbl_lightcurve_parameters(event_table, comp_table, comp_idx, photometric_system, filter_name, event_id=None)

Find the parameters for PSBL_PhotAstrom_Par_Param7 from event_table and comp_table.

Parameters:
event_tableAstropy table

Table containing the events calculated from refine_events.

comp_tableAstropy table

Table containing the companions calculated from refine_events.

comp_idxint

Index into the comp_table of the companion for which the psbl is being calculated.

photometric_systemstr

The name of the photometric system in which the filter exists.

filter_namestr

The name of the filter in which to calculate all the microlensing events. The filter name convention is set in the global filt_dict parameter at the top of this module.

event_idfloat or None, optional

Corresponding event_id in event_table to companion id. Default is None.

Returns:
psbl_parameter_dictdict

Dictionary of the PSBL_PhotAstrom_Par_Param7 parameters

obj_id_Lint

Object id of the lens associated with event

obj_id_Sint

Object id of the source associated with event

popsycle.synthetic.heliocentric_to_galactic(x, y, z)

Converts from heliocentric coordinates to galactic coordinates.

Parameters:
x, y, zfloat or array

Heliocentric coordinates x, y, and z (in kpc)

Returns:
r, b, lfloat or array

Galactic coordinates r, b, and l (in kpc and degrees)

popsycle.synthetic.lightcurve_parameter_gen(model, model_parameter_dict, comp_idxs, obj_id_L, obj_id_S, name=None, save_phot=False, phot_dir=None, overwrite=False)

Find the parameters

Parameters:
modelfunction

Function associated with generating the microlensing model (must be same as parameter_dict)

model_parameter_dictdict

Dictionary of the bagel model parameters

comp_idxlist

List of indices into the comp_table of the companion(s) for which the binary event is being calculated.

obj_id_Lint

Object id of the lens associated with event

obj_id_Sint

Object id of the source associated with event

namestr or None, optional

Name of fits file to be saved. Default is None.

save_photbool, optional

If set to True, saves the photometry generated instead of just parameters. Default is False.

phot_dirstr or None, optional

Name of the directory photometry is saved if save_phot = True. This parameters is NOT optional if save_phot = True. Default is None.

overwritebool

If set to True, overwrites output files. If set to False, exists the function if output files are already on disk. Default is False.

Returns:
param_dictdict

Dictionary of additional parameters added to companion table and one called ‘mp_rows’ which are the rows to be added to the multi peak table.

popsycle.synthetic.make_ebf_log(ebf_table)

Converts log from Galaxia ebf output into dictionary

Parameters:
ebf_tableprocessed ebf file

The ebf file that galaxia outputs, AFTER it’s been read

Returns:
ebf_logdictionary

The ebf file log, in dictionary form

popsycle.synthetic.make_label_file(h5file_name, overwrite=False)

Given an output root for an .h5 file, creates a table of dataset name, l, b, and number of objects. Writes out the Astropy table as a .fits file.

Parameters:
h5file_namestring

The path and name of the input h5file containing the population synthesis results. We will read this in and make a new output file entitled: <h5file_name>_label.fits (after removing the *.h5).

Returns:
label_fileAstropy table

Table containing the dataset name, and corresponding l, b, and number of objects.

popsycle.synthetic.make_label_file_no_bins(h5file_name, overwrite=False)

Given an output root for an .h5 file, creates a table of dataset name and number of objects. Writes out the Astropy table as a .fits file. Used when binning = False (when simulating full sky)

Parameters:
h5file_namestring

The path and name of the input h5file containing the population synthesis results. We will read this in and make a new output file entitled: <h5file_name>_label.fits (after removing the *.h5).

Returns:
label_fileAstropy table

Table containing the dataset name, and corresponding l, b, and number of objects.

popsycle.synthetic.match_companions(star_zams_masses, SPISEA_primary_zams_masses, verbose=0)

Matches galaxia stars and SPISEA stellar primaries by closest match. Note this is after all SPISEA stars with mass greater than the largest galaxia mass have been dropped.

Parameters:
star_zams_masseslist

Galaxia star zams mass column form the star_dict.

SPISEA_primary_zams_massesobject

Astropy column ‘zams_mass’ from the cluster.star_systems cut down to stellar primaries with companions less massive than the most massive galaxia star.

Returns:
closest_index_arrarray

Cloest index in the galaxia mz_galaxia (used to index into mz_galaxia) with the length of mz_spisea. Note that an index of -1 indicates this star cannot be matched within 20% of the desired mass.

mass_diffarray

The difference between the galaxia star mass and the spisea primary mass (m_galaxia - m_spisea) for every input spisea star. Note that a value of np.nan is used for unmatched stars.

popsycle.synthetic.model_param_dict2fits_header(model_parameter_dict, phot_dir, name)

If photometry is being saved, saves the parameters of the model to generate the lightcurve in the first header

Parameters:
model_parameter_dictdictionary

Dictionary of the bagel model parameters

phot_dirstr

Name of the directory photometry

namestr

Base name of fits file of photometry without the _phot (i.e. L_{obj_id_L}_S_{obj_id_S}).

popsycle.synthetic.one_lightcurve_analysis(event_table_row, comp_table_rows, obj_id_L, obj_id_S, photometric_system, filter_name, red_law, save_phot=False, phot_dir=None, overwrite=False)

Generate BAGLE model, photometry, and generate binary lightcurve parameters.

Parameters:
event_table_rowAstropy table

Astropy table row from event table with event parameters.

comp_table_rows: Astropy table

Astropy table with row(s) associated with event row. I.e. if it’s a binary source, binary lens, there should be two rows.

obj_id_Lint

Object id of the lens associated with event.

obj_id_Sint

Object id of the source associated with event.

photometric_systemstr

Name of the photometric system, i.e. ‘ubv’.

filter_namestr

Name of filter associated with photometric system, i.e. ‘I’.

red_lawstr

Name of reddening law in filt_dict list above, i.e. ‘Damineli16’.

save_photbool, optional

If set to True, saves the photometry generated instead of just parameters. Default is False.

phot_dirstr or None, optional

Name of the directory photometry is saved if save_phot = True. This parameters is NOT optional if save_phot = True. Default is None.

overwritebool, optional

If set to True, overwrites output files. If set to False, exists the function if output files are already on disk. Default is False.

Returns:
lightcurve_parameterslist
List of two dictionaries:
  • Dictionary of additional parameters added to the event table and one called ‘mp_rows’ which are the rows to be added to the multi peak table.

  • Dictonary of lightcurve parameters which include both lightcurves whose parameters are saved in the event table and those that are not. i.e. in a triple system only the one with the highest delta_m’s p arameters are used for the lightcurve table. These will all be saved in a separate lightcurve_table.

popsycle.synthetic.perform_pop_syn(ebf_file, output_root, iso_dir, IFMR, bin_edges_number=None, BH_kick_speed_mean=50, NS_kick_speed_mean=400, additional_photometric_systems=None, multiplicity=None, binning=True, overwrite=False, seed=None, n_proc=1, verbose=0)

Given some galaxia output, creates compact objects. Sorts the stars and compact objects into latitude/longitude bins, and saves them in an HDF5 file.

Parameters:
ebf_filestr or ebf file

str : name of the ebf file from Galaxia ebf file : actually the ebf file from Galaxia

output_rootstr

The thing you want the output files to be named Examples include myout, /some/path/to/myout ../back/to/some/path/myout.

iso_dirfilepath

Where are the isochrones stored (for SPISEA)

IFMRstring

The name of the IFMR object from SPISEA. For additional information on these objects see ifmr.py in SPISEA. ‘Raithel18’ = IFMR_Raithel18 ‘Spera15’ = IFMR_Spera15 ‘SukhboldN20’ = IFMR_N20_Sukhbold

bin_edges_numberint, optional

Number of edges for the bins such that bins = bin_edges_number - 1. The Total number of bins is N_bins = (bin_edges_number - 1)**2. If set to None (default), then number of bins is bin_edges_number = int(60 * 2 * radius) + 1

BH_kick_speed_meanfloat, optional

Mean of the birth kick speed of BH (in km/s) maxwellian distrubution. Defaults to 50 km/s.

NS_kick_speed_meanfloat, optional

Mean of the birth kick speed of NS (in km/s) maxwellian distrubution. Defaults to 400 km/s based on distributions found by Hobbs et al 2005 ‘A statistical study of 233 pulsar proper motions’. https://ui.adsabs.harvard.edu/abs/2005MNRAS.360..974H/abstract

additional_photometric_systemslist of strs, optional

The name of the photometric systems which should be calculated from Galaxia / SPISEA’s ubv photometry and appended to the output files.

multiplicity: object

If a resovled multiplicity object is specified, the table will be generated with resolved multiples. Default is None.

binningbool

If set to True, bins files as specified by bin_edges_numbers or default. If set to False, no bins (SET TO FALSE IF DOING FULL SKY DOWNSAMPLED). Default is True.

overwritebool, optional

If set to True, overwrites output files. If set to False, exits the function if output files are already on disk. Default is False.

seedint, optional

If set to non-None, all random sampling will be seeded with the specified seed, forcing identical output for SPISEA and PopSyCLE. Default None.

n_procint

Number of processors to use in the parallel processing. Note that calculations are memory intensive and n_proc > few should likely not be used to avoid memory overruns that may result in data corruption. Default is 1.

verboseint

Level of debugging information to print to stderr. Set to 0 for minimal information. Coarse timing at 2 and fine timing at 4. Default is 0.

Returns:
<output_root>.h5hdf5 file

NOTE: This is what _bin_lb_hdf5 returns. A compund type hdf5 file with datasets that correspond to the longitude bin edges, latitude bin edges, and the compact objects and stars sorted into those bins.

<output_root>_label.fitsfits file

NOTE: This is what make_label_file returns. A fits file that shows the correspondence between dataset name, latitude, longitude, and number of objects in that bin.

popsycle.synthetic.psbl_model_gen(psbl_parameter_dict)

Generate psbl_photastrom_par_param1 model from parameter dict

Parameters:
psbl_parameter_dictdict

Dictionary of the PSBL_PhotAstrom_Par_Param7 parameters

Returns:
psbl model
popsycle.synthetic.reduce_blend_rad(blend_tab, new_blend_rad, output_root, input_root='default', overwrite=False)

Creates a new blend table for some blending radius r_new that is smaller than the original blend radius r_orig, i.e. r_new < r_orig. Also makes a corresponding log and events.

Parameters:
blend_tabstr

The name of the blend table.

new_blend_radfloat or int

The new (smaller) blend radius. Units are in ARCSECONDS.

output_rootstr

The name for the new blend table (and corresponding event table)

input_rootstr, optional

The input root of the old blend table. If ‘default’, takes root of blend_tab.

overwritebool, optional

If set to True, overwrites output files. If set to False, exits the function if output files are already on disk. Default is False.

Returns:
new_blend.fits table

New table with smaller blend radius.

popsycle.synthetic.refine_binary_events(events, companions, photometric_system, filter_name, red_law='Damineli16', overwrite=False, output_file='default', save_phot=False, phot_dir=None, n_proc=1, multi_proc=True)

Takes the output Astropy table from refine_events (both primaries and companions) and from that calculates the binary light curves.

Parameters:
eventsstr

fits file containing the events calculated from refine_events

companionsstr

fits file containing the companions calculated from refine_events

photometric_systemstr

The name of the photometric system in which the filter exists.

filter_namestr

The name of the filter in which to calculate all the microlensing events. The filter name convention is set in the global filt_dict parameter at the top of this module.

red_lawstr, optional

Reddening law. Default is Damineli16

overwritebool, optional

If set to True, overwrites output files. If set to False, exists the function if output files are already on disk. Default is False.

output_filestr, optional

The name of the final refined_events file. If set to ‘default’, the format will be: <input_root>_refined_events_<photometric_system>_<filt>_<red_law>.fits

save_photbool, optional

If set to True, saves the photometry generated instead of just parameters. Default is False.

phot_dirstr or None, optional

Name of the directory photometry is saved if save_phot = True. This parameters is NOT optional if save_phot = True. Default is None.

n_procint, optional

Number of processors to use. Should not exceed the number of cores. Default is one processor (no parallelization).

multi_procbool, optional

Even if n_proc = 1, a pool is still created. If multi_proc = False, instead there is just a for-loop to generate and analyze the lightcurves. If multi_proc == False, n_proc must = 1. Default is True.

Returns:
<input_root>_refined_events_<photometric_system>_<filt>_<red_law>_companions_rb.fitsfits file

A file that contains all the same objects, only now with lots of extra columns of data. (rb stands for refine binaries).

<input_root>_refined_events_<photometric_system>_<filt>_<red_law>_companions_rb_mp.fitsfits file

A file will be created named that contains the data for each individual peak for events with multiple peaks. (mp stands for multiple peaks).

popsycle.synthetic.refine_events(input_root, filter_name, photometric_system, red_law, overwrite=False, output_file='default', hdf5_file_comp=None, legacy=False, seed=None)

Takes the output Astropy table from calc_events, and from that calculates the time of closest approach. Will also return source-lens separation at this time.

Parameters:
input_rootstr

The root path and name of the *_events.fits and *_blends.fits. Don’t include those suffixes yet.

filter_namestr

The name of the filter in which to calculate all the microlensing events. The filter name convention is set in the global filt_dict parameter at the top of this module.

photometric_systemstr

The name of the photometric system in which the filter exists.

red_lawstr

The name of the reddening law to use from SPISEA.

overwritebool, optional

If set to True, overwrites output files. If set to False, exists the function if output files are already on disk. Default is False.

output_filestr, optional

The name of the final refined_events file. If set to ‘default’, the format will be: <input_root>_refined_events_<photometric_system>_<filt>_<red_law>.fits

hdf5_file_comp: str or None, optional

String of hdf5 file of companion events created in perform_pop_syn(). Default is None.

legacybool, optional

For running on files created before ~2020 when the filter system was changed to uppercase (i.e. from ubv_r to ubv_R) and before seeds were introduced. Default is False.

seedint or None, optional

If not None, this forces the random orbit time for binaries to be fixed every time. If seed is added but there are no binaries, the seed will have no consequence. Default is None.

Returns:
<input_root>_refined_events_<photometric_system>_<filt>_<red_law>.fitsfits file

A file will be created that contains all the same objects, only now with lots of extra columns of data.

<input_root>_refined_events_<photometric_system>_<filt>_<red_law>_companions.fitsfits file

If hdf5_file_comp is not None then a file will be created that contains the same objects as a the companion file with extra columns of data.

popsycle.synthetic.run_galaxia(output_root, longitude, latitude, area, galaxia_galaxy_model_filename, seed=None, output_dir='./', photo_sys='UBV', mag_color_names='V,B-V', app_mag_limits=[-1000, 1000], abs_mag_limits=[-1000, 1000], color_limits=[-1000, 1000], geometry_option=1, f_sample=1, pop_ID=-1, warp_flare_on=1, r_max=30)

Given an object root, sky location and area, creates the parameter file that Galaxia requires for running and executes Galaxia. User can also specify a seed for Galaxia to use in its object generation.

Parameters:
output_rootstr

The thing you want the output files to be named Examples include myout, /some/path/to/myout, ../back/to/some/path/myout.

longitudefloat

Galactic longitude, ranging from -180 degrees to 180 degrees

latitudefloat

Galactic latitude, ranging from -90 degrees to 90 degrees

areafloat

Area of the sky that will be generated, in square degrees

galaxia_galaxy_model_filenamestr

Name of the galaxia galaxy model parameter file, as outlined at https://github.com/jluastro/galaxia

seedint, optional

Seed Galaxia will use to generate objects. If not set, script will generate a seed from the current time. Setting this seed guarantees identical results.

popsycle.synthetic.unique_blends(blend_table)

Given a blends table, there might be a single lens-source-neighbor triple multiple times (it might have been observed at different timesteps.) This function will eliminate duplicates, only keeping an event once. It is picked to be the first occurence.

Parameters:
blend_tableblend array

A table with all the events. There is 1 column with the unique source ID, 1 with the unique lens ID lens, 1 with the lens-neighbor separation, and the remaining columns contain info about the neighbors.

Returns:
new_blend_tablenumpy array

Same as blend_table, but all duplicate events have been trimmed out, such that each event only is listed once (at the observed time where the source-lens separation is smallest.)

popsycle.synthetic.unique_events(event_table)

Given an event table, there might be a single microlensing event listed multiple times (it might have been observed at different timesteps, or the nearest neighbor pair might have been symmetric for source and lens.) This function will eliminate duplicates, only keeping an event once. It is picked to be the particular observed event with the smallest source- lens separation.

Parameters:
event_tablenumpy array

A table with all the events. There are equal numbers of columns containing info about the source and the lens, and four additional columns with theta_E, u0, mu_rel, and t0. The number of rows corresponds to the number of events.

Returns:
new_event_tablenumpy array

Same as event_table, but all duplicate events have been trimmed out, such that each event only is listed once (at the observed time where the source-lens separation is smallest.)

popsycle.synthetic.write_galaxia_params(output_root, longitude, latitude, area, seed=None, output_dir='./', photo_sys='UBV', mag_color_names='V,B-V', app_mag_limits=[-1000, 1000], abs_mag_limits=[-1000, 1000], color_limits=[-1000, 1000], geometry_option=1, f_sample=1, pop_ID=-1, warp_flare_on=1, r_max=30)

Given an object root, sky location and area, creates the parameter file that Galaxia requires for running. User can also specify a seed for Galaxia to use in its object generation.

Parameters:
output_rootstr

The thing you want the output files to be named Examples include myout, /some/path/to/myout, ../back/to/some/path/myout.

longitudefloat

Galactic longitude, ranging from -180 degrees to 180 degrees

latitudefloat

Galactic latitude, ranging from -90 degrees to 90 degrees

areafloat

Area of the sky that will be generated, in square degrees

seedint, optional

Seed Galaxia will use to generate objects. If not set, script will generate a seed from the current time. Setting this seed guarantees identical results.

Returns:
<output_root>_galaxia_params.txtstr

A text file with the parameters that Galaxia requires to run.

popsycle.utils module

utils.py Functions (and their associated functions) for utilities.

popsycle.utils.add_precision64(input_array, power)

Need more precision for kdtree to run properly. Convert inputs from float32 to float64, and add a random perturbation beginning in the nths decimal place.

Parameters:
input_arrayfloat or array (float32)

Thing that needs more precision.

powerfloat

To what place you want the perturbation.

Returns:
output_arrayfloat or array (float64)

Thing that has more precision.

popsycle.utils.calc_centroid_shift(glat_S, glon_S, glat_N, glon_N, f_L, f_S, f_N, u)

Calculate the centroid (astrometric) shift for a luminous lens and neighbors

Parameters:
glat_xfloat or array

Longitude of x (L = lens, S = source, N = neighbor centroid)

glon_xfloat or array

Latitude of x (L = lens, S = source, N = neighbor centroid)

f_xfloat or array

Flux of x (L = lens, S = source, N = all neighbors)

ufloat or array

Dimensionless separation

Returns:
delta_c_obsfloat or array

Magnitude of observed astrometric shift, in mas

popsycle.utils.calc_delta_c_LL(fratio, u0, thetaE)

Calculate the maximum-ish centroid shift for a luminous lens, no neighbors

Parameters:
fratioflux ratio of the lens to source, i.e. f_L/f_S
u0impact parameter
thetaEEinstein radius
popsycle.utils.calc_f(lambda_eff)

Calculate that coefficient f that multiples E(B-V) to get the extinction in magnitudes

popsycle.utils.calc_new_position(l0, b0, mu_lcosb, mu_b, t)

Given an initial position and proper motions in l and b, calculate the new position at some later time.

Parameters:
l0float or array

Initial longitude, in DEGREES

b0float or array

Initial latitude, in DEGREES

mu_lcosbfloat or array

Longitudinal proper motion l * cos(b), in MAS/YEAR

mu_bfloat or array

Latitudinal roper motion, in MAS/YEAR

tfloat or array

Time, in DAYS

Returns:
lfloat or array

Latitude, in DEGREES

bfloat or array

Longitude, in DEGREES

popsycle.utils.calc_normalized_counts(mag)
Parameters:
mag: float
Returns:
counts: int
CHANGE THIS CODE IN THE FUTURE TO TAKE IN DIFFERENT ZERO POINTS! NEEDS ADDITIONAL DOCUMENTATION
Right now this is only applicable for OGLE I band
See confluence wiki for where these values come from…
popsycle.utils.combine_refined_events(refined_events_filenames, overwrite=False, output_file='default')

Creates a combined refined_events out of multiple refined_events files

Parameters:
refined_events_filenameslist of strs

Filenames of refined_events tables to be combined

overwritebool, optional

If set to True, overwrites output files. If set to False, exits the function if output files are already on disk. Default is False.

output_filestr, optional

The name of the final refined_events file. If set to ‘default’, the format will be generated from the first filename in refined_events_filenames following: combined_refined_events_<photometric_system>_<filt>_<red_law>.fits

popsycle.utils.execute(cmd, shell=False)

Executes a command line instruction, captures the stdout and stderr

Parameters:
cmdstr

Command line instruction, including any executables and parameters

shellbool, optional

Determines if the command is run through the shell. Default is False.

Returns:
stdoutstr

Contains the standard output of the executed process

stderrstr

Contains the standard error of the executed process

popsycle.utils.generate_isochrones(iso_dir, logAge_min=5.01, logAge_max=10.291, logAge_delta=0.01, metallicity=0.0, include_ztf=True)

Generates isochrones needed for PopSyCLE simulations

Parameters:
iso_dirfilepath

Where are the isochrones stored (for SPISEA)

logAge_minfloat

Minimum log10(age) of generated isochrones

logAge_maxfloat

Maximum log10(age) of generated isochrones

logAge_deltafloat

Resolution in log10(age) of generated isochrones

metallicityfloat

The metallicity in [M/H]

include_ztfbool, optional

Determines if ztf filters should be included in the generated isochrones. Default is True.

popsycle.utils.get_t_from_u(u0, t0, tE, u)

Given the time and separation at closest approach of lens and source and the Einstein radius, calculate the time as a function of separation.

NOTE 1: You need to be consistent with your units for t0, tE, and t, i.e. pick whatever you want (days, years, etc.) but be self consistent.

NOTE 2: There is a positive and negative solution for t. We return the positive solution.

Parameters:
u0float or array

Minimum separation of lens and source (normalized to Einstein radius)

t0float or array

Time of minimum separation of lens and source

tEfloat or array

Einstein crossing time of microlensing event

ufloat or array

Separation of lens and source (normalized to Einstein radius)

Returns:
tfloat or array

Time corresponding to the separation u

popsycle.utils.get_u_from_t(u0, t0, tE, t)

Given the time and separation at closest approach of lens and source and the Einstein radius, calculate the separation as a function of time.

NOTE 1: You need to be consistent with your units for t0, tE, and t, i.e. pick whatever you want (days, years, etc.) but be self consistent.

NOTE 2: There is a positive and negative solution for u. We return the positive solution.

Parameters:
u0float or array

Minimum separation of lens and source (normalized to Einstein radius)

t0float or array

Time of minimum separation of lens and source

tEfloat or array

Einstein crossing time of microlensing event

tfloat or array

Time at which you want to calculate the separation

Returns:
ufloat or array

Separation of lens and source (normalized to Einstein radius)

Makes symlinks for galaxia_params.txt and perform_pop_syn.log files which are required for refine_events()

Parameters:
input_rootstr

Input root of galaxia_params.txt and perform_pop_syn.log. (Assumes they have the same input root).

output_rootstr

Output root of galaxia_params.txt and perform_pop_syn.log.

popsycle.utils.max_delta_c(u0, thetaE)
popsycle.utils.remove_nan_companions(event_table_loc, comp_table_loc, event_output_loc=None, comp_output_loc=None, overwrite=False, rewrite_old_loc=None)

utility to remove companions that were not assigned a final mass or other parameters. This functionality will be implemented in perform_pop_syn, but this modifies those that were run with the nan companions included.

If a SPISEA zams_mass of a companion is too small, the isochrone interpolator may not be able to assign a mass and other parameters so they’ll be nan. This is especially a problem for old (>~ 9 Gyr) and high metallicity (Fe/H>0.4) objects.

Parameters:
event_table_locstring

Location of a companion table to modify

comp_table_locstring

Location of a companion table to modify

event_output_locstring or None, optional

String of output location of companion table without nan companions formated as ‘/path/to/file.fits’. If none, gets saved in the input location with ‘_no_nan’ suffix Default is None.

comp_output_locstring or None, optional

String of output location of companion table without nan companions formated as ‘/path/to/file.fits’. If none, gets saved in the input location with ‘_no_nan’ suffix Default is None.

overwritebool, optional

Whether file at output_loc should be overwritten. Default is False.

rewrite_old_locstring or None, optional

String of output location of companion table without nan companions. If None, does not get saved. Default is None.

popsycle.utils.return_nearest_gridpoint(grid, x_grid_arr, y_grid_arr, x_data, y_data)

Algorithm for finding the nearest grid cell on a 2D array given a datapoint that falls within the bounds of the 2D array.

Parameters:
grid2D numpy array

2D array with size (len(y_grid_arr), len(x_grid_array))

x_grid_arrnumpy array

2D grid indices in the x-dimension

y_grid_arrnumpy array

2D grid indices in the y-dimension

x_datanumpy array

x-coordinate for data that will be located onto the grid

y_datanumpy array

y-coordinate for data that will be located onto the grid

Returns:
gridpoint_arrnumpy array

list of nearest cell values on the grid at the location of (x_data, y_data)

popsycle.utils.sample_spherical(npoints, speed, ndim=3)

Randomly sample points on a sphere. I found this code on stackexchange.

Parameters:
npointsfloat

The number of points you want to generate.

speedfloat

The radius of the sphere (aka the magnitude of the vectors.)

dimfloat

The dimension of the space in which the sphere is embedded (ndim = 3 samples points on a 2-sphere, aka a “normal” sphere)

Returns:
An array of the vectors.