API Reference

This section provides detailed API documentation for all public modules and classes in the zdm package.

Core Modules

These modules form the backbone of the zdm package, providing parameter management, survey handling, and z-DM grid computation.

parameters

Central configuration system for FRB z-DM analysis. All model parameters are organized into dataclasses grouped by category (cosmology, FRB demographics, host galaxy, IGM, etc.). The State class aggregates all parameter groups.

zdm.parameters Module

Parameter dataclasses for the zdm package.

This module defines the central configuration system for FRB z-DM analysis. All model parameters are organized into dataclasses grouped by category:

Parameter Classes

AnalysisParams

Analysis-level settings (grid generation, FRB cuts).

CosmoParams

Cosmological parameters (H0, Omega_m, Omega_b, etc.).

FRBDemoParams

FRB population demographics (source evolution, rates).

RepeatParams

Repeating FRB parameters (rate distribution).

MWParams

Milky Way DM contributions (ISM, halo).

HostParams

Host galaxy DM distribution parameters.

IGMParams

Intergalactic medium parameters (cosmic DM variance).

WidthParams

Intrinsic FRB width distribution parameters.

ScatParams

Scattering timescale distribution parameters.

EnergeticsParams

FRB energy/luminosity function parameters.

State Class

The State class aggregates all parameter dataclasses into a single object that can be passed to grid and survey calculations. It provides methods for updating individual parameters and importing astropy cosmologies.

Example

>>> from zdm.parameters import State
>>> state = State()
>>> state.cosmo.H0  # Access Hubble constant
67.66
>>> state.update_param('gamma', -1.5)  # Update energy distribution slope

Notes

All dataclasses inherit from data_class.myDataClass which provides serialization and parameter metadata handling.

class zdm.parameters.AnalysisParams(NewGrids: bool = True, sprefix: str = 'Std', min_lat: float = -1.0, DMG_cut: float = None)[source]

Analysis-level configuration parameters.

NewGrids: bool = True
sprefix: str = 'Std'
min_lat: float = -1.0
DMG_cut: float = None
__init__(NewGrids: bool = True, sprefix: str = 'Std', min_lat: float = -1.0, DMG_cut: float = None) None
class zdm.parameters.CosmoParams(H0: float = np.float64(67.66), Omega_k: float = 0.0, Omega_lambda: float = np.float64(0.6888463055445441), Omega_m: float = 0.30966, Omega_b: float = 0.04897, Omega_b_h2: float = np.float64(0.0224178568132), fix_Omega_b_h2: bool = True)[source]

Cosmological parameters for Lambda CDM universe.

H0: float = np.float64(67.66)
Omega_k: float = 0.0
Omega_lambda: float = np.float64(0.6888463055445441)
Omega_m: float = 0.30966
Omega_b: float = 0.04897
Omega_b_h2: float = np.float64(0.0224178568132)
fix_Omega_b_h2: bool = True
__init__(H0: float = np.float64(67.66), Omega_k: float = 0.0, Omega_lambda: float = np.float64(0.6888463055445441), Omega_m: float = 0.30966, Omega_b: float = 0.04897, Omega_b_h2: float = np.float64(0.0224178568132), fix_Omega_b_h2: bool = True) None
class zdm.parameters.FRBDemoParams(source_evolution: int = 0, alpha_method: int = 1, sfr_n: float = 1.77, lC: float = 3.3249)[source]

FRB population demographics parameters.

source_evolution: int = 0
alpha_method: int = 1
sfr_n: float = 1.77
lC: float = 3.3249
__init__(source_evolution: int = 0, alpha_method: int = 1, sfr_n: float = 1.77, lC: float = 3.3249) None
class zdm.parameters.RepeatParams(lRmin: float = -3.0, lRmax: float = 1.0, Rgamma: float = -2.375, RC: float = 0.01, RE0: float = 1e+39)[source]

Parameters for repeating FRB population modeling.

lRmin: float = -3.0
lRmax: float = 1.0
Rgamma: float = -2.375
RC: float = 0.01
RE0: float = 1e+39
__init__(lRmin: float = -3.0, lRmax: float = 1.0, Rgamma: float = -2.375, RC: float = 0.01, RE0: float = 1e+39) None
class zdm.parameters.MWParams(ISM: float = 35.0, logu: bool = False, sigmaDMG: float = 0.0, sigmaHalo: float = 15.0, halo_method: int = 0, DMhalo: float = 50.0)[source]

Milky Way DM contribution parameters (ISM and halo).

ISM: float = 35.0
logu: bool = False
sigmaDMG: float = 0.0
sigmaHalo: float = 15.0
halo_method: int = 0
DMhalo: float = 50.0
__init__(ISM: float = 35.0, logu: bool = False, sigmaDMG: float = 0.0, sigmaHalo: float = 15.0, halo_method: int = 0, DMhalo: float = 50.0) None
class zdm.parameters.HostParams(lmean: float = 2.16, lsigma: float = 0.51)[source]

Host galaxy DM contribution distribution parameters.

lmean: float = 2.16
lsigma: float = 0.51
__init__(lmean: float = 2.16, lsigma: float = 0.51) None
class zdm.parameters.IGMParams(logF: float = np.float64(-0.494850021680094))[source]

Intergalactic medium parameters for cosmic DM distribution.

logF: float = np.float64(-0.494850021680094)
__init__(logF: float = np.float64(-0.494850021680094)) None
class zdm.parameters.WidthParams(WidthFunction: int = 2, Wmethod: int = 2, Wlogmean: float = -0.29, Wlogsigma: float = 0.65, Wthresh: int = 0.5, WNbins: int = 12, WNInternalBins: int = 1000, WMin: int = 0.01, WMax: int = 100)[source]

FRB intrinsic width distribution parameters.

WidthFunction: int = 2
Wmethod: int = 2
Wlogmean: float = -0.29
Wlogsigma: float = 0.65
Wthresh: int = 0.5
WNbins: int = 12
WNInternalBins: int = 1000
WMin: int = 0.01
WMax: int = 100
__init__(WidthFunction: int = 2, Wmethod: int = 2, Wlogmean: float = -0.29, Wlogsigma: float = 0.65, Wthresh: int = 0.5, WNbins: int = 12, WNInternalBins: int = 1000, WMin: int = 0.01, WMax: int = 100) None
class zdm.parameters.ScatParams(ScatFunction: int = 2, Slogmean: float = -1.3, Slogsigma: float = 0.2, Smaxsigma: float = 3.0, Sfnorm: float = 1000, Sfpower: float = -4.0, ScatDist: int = 2, Sbackproject: bool = False)[source]

Scattering timescale distribution parameters.

ScatFunction: int = 2
Slogmean: float = -1.3
Slogsigma: float = 0.2
Smaxsigma: float = 3.0
Sfnorm: float = 1000
Sfpower: float = -4.0
ScatDist: int = 2
Sbackproject: bool = False
__init__(ScatFunction: int = 2, Slogmean: float = -1.3, Slogsigma: float = 0.2, Smaxsigma: float = 3.0, Sfnorm: float = 1000, Sfpower: float = -4.0, ScatDist: int = 2, Sbackproject: bool = False) None
class zdm.parameters.EnergeticsParams(lEmin: float = 30.0, lEmax: float = 41.84, alpha: float = 1.54, gamma: float = -1.16, luminosity_function: int = 2)[source]

FRB energy/luminosity function parameters.

lEmin: float = 30.0
lEmax: float = 41.84
alpha: float = 1.54
gamma: float = -1.16
luminosity_function: int = 2
__init__(lEmin: float = 30.0, lEmax: float = 41.84, alpha: float = 1.54, gamma: float = -1.16, luminosity_function: int = 2) None
class zdm.parameters.State[source]

Central configuration object containing all model parameters.

The State class aggregates all parameter dataclasses into a single object that is passed to Grid, Survey, and other components. It provides dictionary-like access to parameter groups and methods for updating parameters.

analysis

Analysis-level settings.

Type:

AnalysisParams

cosmo

Cosmological parameters.

Type:

CosmoParams

FRBdemo

FRB population parameters.

Type:

FRBDemoParams

rep

Repeater parameters.

Type:

RepeatParams

MW

Milky Way parameters.

Type:

MWParams

host

Host galaxy parameters.

Type:

HostParams

IGM

IGM parameters.

Type:

IGMParams

width

Width distribution parameters.

Type:

WidthParams

scat

Scattering parameters.

Type:

ScatParams

energy

Energy function parameters.

Type:

EnergeticsParams

Example

>>> state = State()
>>> state.cosmo.H0
67.66
>>> state['cosmo'].H0  # Dictionary-style access
67.66
>>> state.update_param('gamma', -1.5)
__init__()[source]
set_dataclasses()[source]

Initialize all parameter dataclass instances with defaults.

update_param(param: str, value)[source]

Update a single parameter by name.

Automatically finds which dataclass contains the parameter and updates it. Handles special cases like H0 updating Omega_b.

Parameters:
  • param (str) – Parameter name (e.g., ‘H0’, ‘gamma’, ‘lEmax’).

  • value (any) – New value for the parameter.

set_astropy_cosmo(cosmo)[source]

Import cosmological parameters from an astropy Cosmology object.

Parameters:

cosmo (astropy.cosmology.Cosmology) – Astropy cosmology object (e.g., Planck18, WMAP9).

Classes

AnalysisParams([NewGrids, sprefix, min_lat, ...])

Analysis-level configuration parameters.

CosmoParams([H0, Omega_k, Omega_lambda, ...])

Cosmological parameters for Lambda CDM universe.

EnergeticsParams([lEmin, lEmax, alpha, ...])

FRB energy/luminosity function parameters.

FRBDemoParams([source_evolution, ...])

FRB population demographics parameters.

HostParams([lmean, lsigma])

Host galaxy DM contribution distribution parameters.

IGMParams([logF])

Intergalactic medium parameters for cosmic DM distribution.

IO()

Generic base class for TextIO and BinaryIO.

MWParams([ISM, logu, sigmaDMG, sigmaHalo, ...])

Milky Way DM contribution parameters (ISM and halo).

RepeatParams([lRmin, lRmax, Rgamma, RC, RE0])

Parameters for repeating FRB population modeling.

ScatParams([ScatFunction, Slogmean, ...])

Scattering timescale distribution parameters.

State()

Central configuration object containing all model parameters.

WidthParams([WidthFunction, Wmethod, ...])

FRB intrinsic width distribution parameters.

survey

FRB Survey class for modeling telescope observations. Encapsulates instrument characteristics, beam patterns, detection efficiencies, and detected FRB data. Survey files are loaded from ECSV format with header metadata and FRB tables.

zdm.survey Module

FRB Survey class for modeling telescope observations.

This module provides the Survey class, which encapsulates all properties of an FRB survey including instrument characteristics, beam patterns, detection efficiencies, and detected FRB data.

The Survey class handles: - Loading survey definition files (ECSV format) with FRB metadata - Beam pattern modeling and solid angle calculations - Detection efficiency as a function of DM and width - DM budget calculations (Galactic, halo, host contributions) - Threshold calculations for FRB detection

Survey Definition Files

Survey files are stored in zdm/data/Surveys/ and contain: - Header metadata: telescope parameters, beam settings, frequency, etc. - FRB table: TNS name, DM, position, width, fluence for each detection

Example

>>> from zdm import survey
>>> from zdm.parameters import State
>>> state = State()
>>> dmvals = np.linspace(0, 3000, 1000)
>>> s = survey.Survey(state, 'CRAFT/ICS', 'CRAFT_ICS.ecsv', dmvals)
>>> s.NFRB  # Number of FRBs
10
>>> s.DMEGs  # Extragalactic DM values
array([...])

Author: C.W. James

class zdm.survey.Survey(state, survey_name: str, filename: str, dmvals: ndarray, zvals: ndarray = None, NFRB: int = None, iFRB: int = 0, edir=None, rand_DMG=False, survey_dict=None)[source]

Represents an FRB survey with instrument properties and detected FRBs.

The Survey class is the primary interface for defining telescope characteristics and loading FRB detections. It computes detection efficiencies across the DM-width-fluence parameter space.

name

Survey identifier (e.g., ‘CRAFT/ICS’, ‘Parkes/Mb’).

Type:

str

NFRB

Number of FRBs in the survey.

Type:

int

DMEGs

Extragalactic DM values for detected FRBs.

Type:

ndarray

Zs

Redshifts for localized FRBs (None if unknown).

Type:

ndarray or None

meta

Survey metadata from file header.

Type:

dict

efficiencies

Detection efficiency grid as function of DM and width.

Type:

ndarray

__init__(state, survey_name: str, filename: str, dmvals: ndarray, zvals: ndarray = None, NFRB: int = None, iFRB: int = 0, edir=None, rand_DMG=False, survey_dict=None)[source]

Initialize an FRB Survey.

Parameters:
  • state (parameters.State) – State object containing model parameters.

  • survey_name (str) – Identifier for the survey (e.g., ‘CRAFT/ICS’).

  • filename (str) – Path to survey definition file (ECSV format).

  • dmvals (ndarray) – Extragalactic DM grid values for efficiency calculations.

  • zvals (ndarray, optional) – Redshift grid values. Required for some width methods.

  • NFRB (int, optional) – Limit number of FRBs loaded from file.

  • iFRB (int, optional) – Starting index for FRB selection. Default is 0.

  • edir (str, optional) – Directory containing pre-computed efficiency files.

  • rand_DMG (bool, optional) – If True, randomize Galactic DM within uncertainty. Default False.

  • survey_dict (dict, optional) – Override survey metadata parameters.

init_widths(state=None)[source]

Performs initialisation of width and scattering distributions

Parameters:

state (parameters.state object., optional) – if set, assume this state contains new scattering/width parameters

process_dm_mask(edir=None)[source]

Processes a DM mask into units of local DM

do_efficiencies()[source]

Function to handle calculation of efficiencies. Allows this to be called externally, e.g. if DM halo model changes

make_widths(iz=None)[source]

This routine calculates width distributions of FRBs, which is required to estimate detection efficiency, and (potentially) calculate p(w,tau).

The functionality depends on self.width_method, which is set via

WMETHOD [int: 0-4]:

0: No distribution - calculations performed at total width = 1ms 1: FRB widths are a simple lognormal of self.wlogmean, self.wlogsigma

histogrammed into self.wbins. Describes widths as “total width”, i.e. intrinsic plus scattering.

2: FRB widths convolved with frequency-dependent scattering distribution.

Calculates lognormal intrinsic width distribution, and convolves this with a lognormal scattering distribution. NOTE: if wmethod=2, iz must be called with iz=None.

3: As above, but allows for redshift dependence of both intrinsic

width and scattering. Distributions both scale width redshift: width with 1+z, scattering with (1+z)^-3

4: Use a specific width of a particular FRB. Used for detailed calcs

for individual FRB-by-FRB analyses.

init_repeaters()[source]

Checks to see if this is a repeater survey and if so ensures all the relevant information is present.

get_internal_coeffs(wlist)[source]

Returns indices and coefficients for linear interpolation between intrinsic width values

wlist: np.ndarray of observed intrinsic widths or taus

Returns:

index of lower value iws2 (int): index of upper value dkws1 (float): coefficient for iws1 dkws2 (float): coefficient for iws2

Return type:

iws1 (int)

init_frb_bvals()[source]

Initialise frb-by-frb weights for each value of the beam histogram, based on the value of the beam that the FRB was detected in.

Simply does this by linear interpolation

init_frb_wvals()[source]

Initialises frb width coefficients for linear interpolation

This is for a slightly different purpose than the init widths routine

get_w_coeffs(wlist)[source]

Returns indices and coefficients for linear interpolation between width values Bin edges run from [small~1e-10, self.WMin, self.WMin + self.dlowg, …, self.Wmax] We should use bin centres to determine which linear interpolations we sit between

wlist: np.ndarray of observed widths

Returns:

index of lower value iws2 (int): index of upper value dkws1 (float): coefficient for iws1 dkws2 (float): coefficient for iws2

Return type:

iws1 (int)

randomise_DMG(uDMG=0.5)[source]

Change the DMG_ISM values to a random value within uDMG Gaussian uncertainty

init_DMEG(DMhalo, halo_method=0)[source]

Calculates extragalactic DMs assuming halo DM

process_dmhalo(halo_method)[source]

Calculates directionally dependent DMhalo from Yamasaki and Totani 2020 and rescaling to an average of self.DMhalo

self.c, self.Gls and self.Gbs should be loaded in process_survey_file

init_halo_coeffs()[source]

Initialise coefficients for Yamasaki and Totani 2020 implementation of directionally dependent DMhalo

init_zs()[source]

Gets zlist and nozlist and determines which z values to use

init_zs_reps()[source]

Gets zlist and nozlist for repeaters and singles. Basically the same as init_zs but for repeaters.

process_survey_file(filename: str, NFRB: int = None, iFRB: int = 0, min_lat=None, dmg_cut=None, survey_dict=None)[source]

Loads a survey file, then creates dictionaries of the loaded variables

Parameters:
  • filename (str) – Survey filename

  • NFRB (int, optional) – Use only a subset of the FRBs in the Survey file. Mainly used for Monte Carlo analysis

  • iFRB (int, optional) – Start grabbing FRBs at this index Mainly used for Monte Carlo analysis Requires that NFRB be set

  • surveydict – overrides value in file

fix_coordinates(verbose=False)[source]

Takes and FRB, and fills out missing coordinate values Note that now, RA, DEC, Gl, and Gb will be present But their default values are None

process_dmg()[source]

Estimates galactic DM according to Galactic lat and lon only if not otherwise provided

init_beam(plot=False, method=1, thresh=0.001)[source]

Initialises the beam

calc_max_dm()[source]

Calculates the maximum searched DM.

Calculates bandwidth using

get_efficiency_from_wlist(wlist, plist, model='Quadrature', addGalacticDM=True, edir=None, iz=None)[source]

Gets efficiency to FRBs Returns a list of relative efficiencies as a function of dispersion measure for each width given in wlist

wlist:

list of intrinsic FRB widths

plist:

list of relative probabilities for FRBs to have widths of wlist

model: method of estimating efficiency as function of width, DM, and time resolution
Takes values of “Quadrature”, “Sammons” (from Mawson Sammons summer project),

“CHIME” or a file name

addGalacticDM:
  • True: this routine adds in contributions from the MW Halo and ISM, i.e.

    it acts like DMlist is an extragalactic DM

  • False: just use the supplied DMlist

edir:
  • Directory where efficiency files are contained. Only relevant if specific FRB responses are used

iz:
  • izth z-bin where these efficiencies are being calculated

__repr__()[source]

Over-ride print representation

Returns:

Items of the FURBY

Return type:

str

zdm.survey.calc_relative_sensitivity(DM_frb, DM, w, fbar, t_res, nu_res, Nchan=336, max_idt=None, max_dm=None, model='Quadrature', dsmear=True, edir=None, max_iw=None, max_meth=0)[source]

Calculates DM-dependent sensitivity

This function adjusts sensitivity to a given burst as a function of DM.

It includes DM smearing between channels, burst intrinsic width, the observation frequency time- and frequency-resolutions etc.

NOTE: DM_frb only used if dsmear = True: combine these to default to None?

Parameters:
  • [float] (w) – measured DM of a particular FRB. Used only if dsmear=True.

  • pc/cm3 (DMs [np.ndarray] DMs at which to calculate the DM bias effect.)

  • [float] – FRB width [ms]

  • fbar – mean frequency of the observation [Mhz]

  • t_res – time resolution of the observation [ms]

  • nu_res – frequency resolution of the observation [Mhz]

  • model

    Quadrature,Sammons, or CHIME: method to calculate bias. NOTE: Quadrature_s and Sammons_s should be input to this function as

    just Quadrature and Sammons respectively

  • dsmear – subtract DM smearing from measured width to calculate intrinsic

  • [string (edir) – directory containing efficiency files to be loaded

  • optional] – directory containing efficiency files to be loaded

  • [int (maxmeth) – maximum integer width of the search

  • optional] – maximum integer width of the search

  • [int – 0: ignore maximum width 1: truncate sensitivity at maximum width 2: scale sensitivity as 1/w at maximum width

  • optional] – 0: ignore maximum width 1: truncate sensitivity at maximum width 2: scale sensitivity as 1/w at maximum width

zdm.survey.load_survey(survey_name: str, state: State, dmvals: ndarray, zvals: ndarray = None, sdir: str = None, NFRB: int = None, nbins=None, iFRB: int = 0, dummy=False, edir=None, rand_DMG=False, survey_dict=None, verbose=False)[source]

Load a survey

Parameters:
  • survey_name (str) – Name of the survey e.g. CRAFT/FE

  • state (parameters.State) – Parameters for the state

  • dmvals (np.ndarray) – DM values

  • zvals (np.ndarray,optional) – z values

  • sdir (str, optional) – Path to survey files. Defaults to None.

  • nbins (int, optional) – Sets number of bins for Beam analysis [was NBeams]

  • NFRB (int, optional) – Cut the total survey down to a random subset [useful for testing]

  • iFRB (int, optional) – Start grabbing FRBs at this index Mainly used for Monte Carlo analysis Requires that NFRB be set

  • dummy (bool,optional) – Skip many initialisation steps: used only when loading survey parameters for conversion to the new survey format

  • survey_dict (dict, optional) – dictionary of survey metadata to over-ride values in file

  • verbose (bool) – print output

Raises:

IOError – [description]

Returns:

instance of the class

Return type:

Survey

zdm.survey.vet_frb_table(frb_tbl: DataFrame, mandatory: bool = False, fill: bool = False)[source]

This should not be necessary anymore, since all required FRB data should be populated with default values. However, it’s great as a check. If this complains, it means we have a bug in the replacement with default value procedure.

zdm.survey.quadrature_convolution(width_function, width_args, scat_function, scat_args, internal_logvals, bins, backproject=False)[source]

Numerically evaluates the resulting distribution of y=sqrt{x1^2+x2^2}, where x1 is the width distribution, and x2 is the scattering distribution.

Parameters:
  • width_function (float function(float,args)) – function to call giving p(logw) dlogw

  • width_args (*list) – arguments to pass to width function

  • scat_function (float function(float,args)) – function to call giving p(logtau) dlogtau

  • scat_args (*list) – arguments to pass to scattering function

  • internal_vals (np.ndarray) – numpy array of length NIbins giving internal values of log dw to use for internal calculation purposes.

  • bins (np.ndarray([NBINS+1],dtype='float')) – bin edges for final width distribution

  • backproject (bool, optional) – if True, calculates p(tau|totalw) and p(w|totalw) for this redshift, and returns additional values.

Returns:

histogram of probability within bins wfracs (np.ndarray,only if backproject): p(tau|tw) taufracs (np.ndarray,only if backproject): p(w|tw)

Return type:

hist (np.ndarray)

zdm.survey.lognormal(log10w, *args)[source]

Lognormal probability distribution. Note that the x values and args could theoretically be in natural log (or other) space, including linear.

Parameters:
  • log10w – log base 10 of widths

  • args – vector of [logmean,logsigma] mean and std dev

Returns:

p(logw) d logw

Return type:

result

zdm.survey.halflognormal(log10w, *args)[source]

Generates a parameterised half-lognormal distribution. This acts as a lognormal in the lower half, but keeps a constant per-log-bin width in the upper half There is nor formal way to normalise this function.

It can also be verified that changing the normalisation of these functions only changes the P(N) calculation, which should in any case be separately optimised. Note however that this changes the interpretation of the log-constant, which may be incorrect to within such a normalisation factor.

Parameters:
  • log10w – log base 10 of widths

  • args – vector of [logmean,logsigma] mean and std dev and max value

Returns:

p(log10w) d log10w

Return type:

result

zdm.survey.constant(log10w, *args)[source]

Dummy function that returns a constant of unity, down to a certain minimum, below which it is zero. NOTE: to include 1+z scaling here, one will need to reduce the minimum width argument with z. Feature to be added. Maybe have args also contain min and max values?

Parameters:
  • log10w – log base 10 of widths

  • args – vector of [logmean,logsigma] mean and std dev and max width

Returns:

p(logw) d logw

Return type:

result

Functions

calc_relative_sensitivity(DM_frb, DM, w, ...)

Calculates DM-dependent sensitivity

constant(log10w, *args)

Dummy function that returns a constant of unity, down to a certain minimum, below which it is zero.

dataclass([cls, init, repr, eq, order, ...])

Add dunder methods based on the fields defined in the class.

embed(*[, header, compile_flags])

Call this to embed IPython at the current point in your program.

fields(class_or_instance)

Return a tuple describing the fields of this dataclass.

halflognormal(log10w, *args)

Generates a parameterised half-lognormal distribution.

load_survey(survey_name, state, dmvals[, ...])

Load a survey

lognormal(log10w, *args)

Lognormal probability distribution.

quad(func, a, b[, args, full_output, ...])

Compute a definite integral.

quadrature_convolution(width_function, ...)

Numerically evaluates the resulting distribution of y=sqrt{x1^2+x2^2}, where x1 is the width distribution, and x2 is the scattering distribution.

vet_frb_table(frb_tbl[, mandatory, fill])

This should not be necessary anymore, since all required FRB data should be populated with default values.

Classes

SkyCoord(*args[, copy])

High-level object providing a flexible interface for celestial coordinate representation, manipulation, and transformation between systems.

Survey(state, survey_name, filename, dmvals)

Represents an FRB survey with instrument properties and detected FRBs.

Table([data, masked, names, dtype, meta, ...])

A class to represent tables of heterogeneous data.

grid

Core z-DM grid class for FRB population modeling. Computes 2D probability distributions of FRB detection rates as a function of redshift and DM by combining cosmological volumes, p(DM|z), telescope efficiency, and luminosity functions.

zdm.grid Module

Core z-DM grid class for FRB population modeling.

This module provides the Grid class, which computes 2D probability distributions of FRB detection rates as a function of redshift (z) and dispersion measure (DM).

The Grid combines: - Cosmological volume elements and source evolution - p(DM|z) from the Macquart relation (cosmic + host) - Telescope detection efficiency (fluence threshold, beam pattern) - FRB luminosity/energy function

Key Features

  • Builds normalized 2D probability grids for expected FRB rates

  • Handles beam response and detection efficiency

  • Supports multiple luminosity functions (power-law, gamma)

  • Efficient updating for MCMC parameter exploration

Example

>>> from zdm import grid
>>> g = grid.Grid(survey, state, zDMgrid, zvals, dmvals, smear_mask)
>>> expected_rate = g.rates  # Expected detection rate per (z, DM) bin

Author: C.W. James

class zdm.grid.Grid(survey, state, zDMgrid, zvals, dmvals, smear_mask, wdist=None, prev_grid=None)[source]

2D grid for computing FRB detection rates as a function of z and DM.

The Grid class is the core computational object in zdm. It builds a 2D probability distribution representing expected FRB detection rates across the redshift-DM plane for a given survey and parameter set.

Assumptions: - Each z bin represents FRBs originating at that redshift (not integrated) - Linear uniform spacing in both z and DM - DM includes cosmic + host contributions convolved together

rates

2D array of expected FRB rates per (z, DM) bin.

Type:

ndarray

zvals

Redshift bin centers.

Type:

ndarray

dmvals

DM bin centers in pc/cm^3.

Type:

ndarray

state

Parameter state used for grid calculation.

Type:

parameters.State

survey

Associated survey object.

Type:

survey.Survey

__init__(survey, state, zDMgrid, zvals, dmvals, smear_mask, wdist=None, prev_grid=None)[source]

Initialize the Grid for a survey and parameter state.

Parameters:
  • survey (survey.Survey) – Survey object with telescope properties and FRB data.

  • state (parameters.State) – Parameter state defining the model. Note: grids share the same State object, so modifications affect all grids.

  • zDMgrid (ndarray) – 2D array of p(DM|z) probabilities, shape (nz, ndm).

  • zvals (ndarray) – Redshift bin centers. Bins span [z - dz/2, z + dz/2].

  • dmvals (ndarray) – DM bin centers in pc/cm^3. Bins span [DM - dDM/2, DM + dDM/2].

  • smear_mask (ndarray) – 1D convolution kernel for host DM smearing.

  • wdist (bool, optional) – If True, include width distribution effects.

  • prev_grid (Grid, optional) – Another Grid with same z/DM values but different survey. Allows reusing pre-computed cosmological quantities.

init_luminosity_functions()[source]

Set the luminsoity function for FRB energetics

parse_grid(zDMgrid, zvals, dmvals)[source]
load_grid(gridfile, zfile, dmfile)[source]
get_dm_coeffs(DMlist)[source]

Returns indices and coefficients for interpolating between DM values

dmlist: np.ndarray of dispersion measures (extragalactic!)

get_z_coeffs(zlist)[source]

Returns indices and coefficients for interpolating between z values

zlist: np.ndarray of dispersion measures (extragalactic!)

check_grid(TOLERANCE=1e-06)[source]

Check that the grid values are behaving as expected

TOLERANCE: defines the max relative difference in expected

and found values that will be tolerated

calc_dV(reINIT=False)[source]

Calculates volume per steradian probed by a survey.

Does this only in the z-dimension (for obvious reasons!)

EF(alpha=0, bandwidth=1000000000.0)[source]

Calculates the fluence–energy conversion factors as a function of redshift This does NOT account for the central frequency

set_evolution()[source]

Scales volumetric rate by SFR

calc_pdv(beam_b=None, beam_o=None)[source]

Calculates the rate per cell. Assumed model: a power-law between Emin and Emax (erg)

with slope gamma.

Efficiencies: list of efficiency response to DM So-far: does NOT include time x solid-angle factor

NOW: this includes a solid-angle and beam factor if initialised

This will recalculate beam factors if they are passed, however during iteration this is not recalculated

get_pw_dist()[source]

Function asking the grid to return the p(w) distribution.

This will be an “all-burst” distribution in case of a repeater inherited class.

Note that a grid does not actually know what a “width” means: it is simply an abstract category of FRBs corresponding to a particular efficiency and fraction of the population.

Args: None

Returns:

Rate per width bin Wzs (np.ndarray: Nw x Nz): Rate as a function of w and z Wdms (np.ndarray: Nw x Ndm): Rate as a function of w and DM

Return type:

Wtots (np.ndarray)

calc_rates()[source]

multiplies the rate per cell with the appropriate pdm plot

get_rates()[source]

Returns rates, multiplied by the relevant constant, and accounting for any DM preference via a DM mask

calc_thresholds(F0: float, eff_table, bandwidth=1000000000.0, nuRef=1300000000.0, weights=None)[source]

Sets the effective survey threshold on the zdm grid

Parameters:
  • F0 (float) – base survey threshold

  • eff_table ([type]) – table of efficiencies corresponding to DM-values. 1, 2, or 3 dimensions!

  • bandwidth ([type], optional) – [description]. Defaults to 1e9.

  • nuObs ([float], optional) – survey frequency (affects sensitivity via alpha - only for alpha method) Defaults to 1.3e9.

  • nuRef ([float], optional) – reference frequency we are calculating thresholds at Defaults to 1.3e9.

  • weights ([type], optional) – [description]. Defaults to None.

Raises:
smear_dm(smear: ndarray)[source]

Smears DM using the supplied array. Example use: DMX contribution

smear_grid is created in place

Parameters:

smear (np.ndarray) – Smearing array

get_p_zgdm(DMs: ndarray)[source]

Calcuates the probability of redshift given a DM We already have our grid of observed DM values. Just take slices!

Parameters:

DMs (np.ndarray) – array of DM values

Returns:

array of priors for the DMs

Return type:

np.ndarray

GenMCSample(N, Poisson=False)[source]

Generate a MC sample of FRB events

If Poisson=True, then interpret N as a Poisson expectation value Otherwise, generate precisely N FRBs

Generated values are [MCz, MCDM, MCb, MCs, MCw] NOTE: the routine GenMCFRB does not know ‘w’, merely

which w bin it generates.

initMC()[source]

Initialises the MC sample, if it has not been doen already This uses a great deal of RAM - hence, do not do this lightly!

GenMCFRB(Emax_boost)[source]

Generates a single FRB according to the grid distributions

Samples beam position b, FRB DM, z, s=SNR/SNRth, and w Currently: no interpolation included. This should be implemented in s,DM, and z.

NOTE: currently, the actual FRB widths are not part of ‘grid’

only the relative probabilities of any given width. Hence, this routine only returns the integer of the width bin not the width itelf.

Parameters:
  • pwb (optional) – probability(width,beam)

  • Emax_boost (float, optional) – Allow for larger energies than Emax The factor is logarithmic, i.e. Emax_boost = 2. allows for 10**2 higher energies than Emax

Returns:

FRBparams=[MCz,MCDM,MCb,j,MCs], pwb values These are:

MCz: redshift MCDM: dispersion measure (extragalactic) MCb: beam value j: MCs: SNR/SNRth value of FRB MCw: width value of FRB

[MCz, MCDM, MCb, j, MCs, MCw]

Return type:

tuple

build_sz()[source]
update(vparams: dict, ALL=False, prev_grid=None)[source]

Update the grid based on a set of input parameters

Hierarchy: Each indent corresponds to one ‘level’. This is used in the program control below to dictate how far each tree should proceed in calculation. Direct variable inputs are always listed first We see that sfr evolution and dm smearing lie just before the pdv step Hence, we deal with these first, and calc rates as a final step regardless of what else has changed.

Parameters:
  • vparams (dict) – dict containing the parameters to be updated and their values

  • prev_grid (Grid, optional) – If provided, it is assumed this grid has been updated on items that need not be repeated for the current grid. i.e. Speed up!

  • ALL (bool, optional) – If True, update the full grid

calc_rates:
calc_pdv

Emin Emax gamma H0 calc_thresholds

F0 alpha bandwidth

set_evolution

sfr_n H0

smear_grid

grid mask

dmx_params (lmean, lsigma)

dV zdm_grid

H0

Note that the grid is independent of the constant C (trivial dependence)

Parameters:

vparams (dict) – [description]

chk_upd_param(param: str, vparams: dict, update=False)[source]

Check to see whether a parameter is differs from that in self.state

Parameters:
  • param (str) – Paramter in question

  • vparams (dict) – Dict holding the value

  • update (bool, optional) – If True, update the value in self.state. Defaults to False.

Returns:

True if the parameter is different

Return type:

bool

Classes

Grid(survey, state, zDMgrid, zvals, dmvals, ...)

2D grid for computing FRB detection rates as a function of z and DM.

repeat_grid

Grid extension for repeating FRB population modeling. Models expected numbers of single and repeated detections given a distribution of repeater rates following dN/dR ~ R^Rgamma.

zdm.repeat_grid Module

Grid extension for repeating FRB population modeling.

This module provides the repeat_Grid class, which extends the base Grid class to handle repeating FRB populations. It models the expected number of single detections and repeated detections given a distribution of repeater rates.

Key Concepts

  • Repeater rate distribution: dN/dR ~ R^Rgamma for R in [Rmin, Rmax]

  • Single bursts: First detections from repeaters (and possibly non-repeaters)

  • Repeat bursts: Subsequent detections from the same source

Time Dilation Effects

  1. dVdtau: The base grid uses time-dilated volume elements. For repeater counts, we need the undilated volume (number of sources doesn’t change).

  2. Rmult: For alpha_method=1 (rate scaling), the per-source rate changes with frequency, requiring corrections for central frequency and redshift.

  3. SFR factor: Source evolution must be recalculated for alpha_method=1 since we’re counting progenitors, not burst rates.

param Repetition parameters are stored in state.rep:

param - Rmin:

type - Rmin:

Minimum repeater rate (bursts/day)

param - Rmax:

type - Rmax:

Maximum repeater rate (bursts/day)

param - Rgamma:

type - Rgamma:

Power-law index of rate distribution

Example

>>> from zdm import repeat_grid
>>> rg = repeat_grid.repeat_Grid(survey, state, ...)
>>> n_singles = rg.exact_singles  # Expected single detections
>>> n_repeats = rg.exact_reps     # Expected repeat detections

Author: C.W. James

class zdm.repeat_grid.repeat_Grid(survey, state, zDMgrid, zvals, dmvals, smear_mask, wdist, prev_grid=None, opdir=None, Exact=True, MC=False, verbose=False)[source]

This class is designed to take a p(z,DM) grid and calculate the effects of repeating FRBs.

It is an “add-on” to an existing grid class, i.e. it is passed an existing grid, and performs calculations from there.

Repetition parameters are contained within the grid object itself. Optionally, these can be sepcified as additional arguments at compilation.

Currently, only Poisson repeaters are enabled. This will change. Well, maybe…

__init__(survey, state, zDMgrid, zvals, dmvals, smear_mask, wdist, prev_grid=None, opdir=None, Exact=True, MC=False, verbose=False)[source]

Initialises repeater class :param Same as ‘grid.py’:

update(vparams: dict, ALL=False, prev_grid=None)[source]

Routine to update based upon new Rmin,Rmax,gamma parameters.

Inputs:
vparams (dict): dict containing the parameters

to be updated and their values

prev_grid (Grid, optional):

If provided, it is assumed this grid has been updated on items that need not be repeated for the current grid. i.e. Speed up!

ALL (bool, optional): If True, update the full grid

calc_constant(verbose=False)[source]
Calculates the constant of the repeating FRB function:

dPhi(R)/dR = Cr * (R/R0)^power between Rmin and Rmax. Here R0 is the unit of R, taken to be 1/day

The constant C is the constant burst rate at energy E0 per unit volume By definition, int_{R=Rmin}^{R=Rmax} R dPhi(R)/dR dR = C Hence, C=Cr * (power+2)^-1 (R_max^(power+2)-R_min^(power+2)) and thus Cr = C * (power+2)/(R_max^(power+2)-R_min^(power+2))

We also need to account for frequency dependence. The default frequency for FRB properties is 1.3 GHz. Under the rate approximation, the rate per repeater changes with frequency Under the spectral index approximation, FRBs become brighter/dimmer. This MUST therefore factor into calculations!

NOTE: if updating, in theory all steps before Rc = … could be held in memory

calc_Rthresh(Exact=True, MC=False, Pthresh=0.01, doplots=False, old=[False, False, False])[source]

For FRBs on a zdm grid, calculate the repeater rates below which we can reasonably treat the distribution as continuous

Steps:
  • Calculate the apparent repetition threshold to ignore repetition

  • Calculate rate scaling between energy at which repeat rates are defined, and energy threshold

Exact: if True, performs an “exact” analytic calculation of

the singles and repeater rates.

MC (bool or int): if bool and True, perform a single MC evaluation

if bool and False, use the analytic method if int >0: performs MC Monte Carlo evaluations

Pthresh: only if MC is true

threshold above which to allow progenitors to produce multilke bursts

Old defines which parameters (Rmin, Rmax, gamma) are being redone

perform_exact_calculations(slow=False)[source]
Performs exact calculations of:
  • <single bursts>

  • <no bursts>

  • < progenitors with N>2 bursts>

  • < number of N>2 bursts>

calc_expected_repeaters(expected_singles, expected_zeros)[source]

Calculates the expected number of FRBs observed as repeaters. The total expected number of observed repeaters is the total number of actual repeaters, minus those that are observed once, minus those observed not at all

calc_expected_repeat_bursts(expected_singles)[source]

Calculates the expected total number of bursts from repeaters.

This is simply calculated as <all bursts> - <single bursts>

calc_singles_exactly()[source]

Calculates exact expected number of single bursts from a repeater population

Probability is: int constant * R exp(-R) * R^(Rgamma) definition of gamma function is R^x-1 exp(-R) for gamma(x) # hence here x is gamma+2 limits set by Rmin and Rmax (determind after multiplying intrinsic by Rmult)

This is Gamma(Rgamma+2,Rmin) - Gamma(Rgamma+2,Rmax)

calc_zeroes_exactly(singles)[source]

Calculates the probability of observing zero bursts exactly

probability is: constant * exp(-R) * R^(Rgamma) definition of gamma function is R^x-1 exp(-R) for gamma(x) # hence here x is gamma+1 limits set by Rmin and Rmax (determind after multiplying intrinsic by Rmult)

This is Gamma(Rgamma+1,Rmin) - Gamma(Rgamma+1,Rmax)

calc_exact_repeater_probability(Nreps, DM, z=None, verbose=False)[source]

Calculates exact expected number of Nreps bursts from a repeater population We have this repeater at z-value z, DM value DM

INPUTS:

Nreps (int): Number of observed repetitions (>=2) DM (float): Extragalactic dispersion measure of the FRB z (float): Redshift of the FRB verbose (bool): if verbose output is required

Returns:

relative probability of observing an FRB with

Nreps given a repeater has been observed

Return type:

rel_prob (float)

MATH:
The singles probability is: int constant * R exp(-R) * R^(Rgamma)

where the factor “R exp(-R)” is Poisson(1) We now replace this with Poisson(N) = R^N exp(-R)/R!

The definition of gamma function is R^x-1 exp(-R) for gamma(x)

hence here x is gamma+N+1

This simply means we calculate a new gamma function at the relevant point

limits set by Rmin and Rmax (determind after multiplying intrinsic by Rmult) This is Gamma(Rgamma+N+1,Rmin) - Gamma(Rgamma+N+1,Rmax)

get_rep_prob_at_point(iz, idm, effGamma, factorial)[source]
Calculates the probability of getting a repeater at grid point

iz,idm with given number of repeates.

Key normalisation factors are missing and are added later

iz (int): index of redshift idm (int): index of dispersion measure eff_gamma (float): effective value of gamma for the integral factorial (floart): pre-computer factorial factor

slow_exact_calculation(exact_singles, exact_zeroes, exact_rep_bursts, exact_reps, plot=True, zonly=True)[source]

Calculates exact expected number of single bursts from a repeater population

Probability is: int constant * R exp(-R) * R^(Rgamma) definition of gamma function is R^x-1 exp(-R) for gamma(x) # hence here x is gamma+2 limits set by Rmin and Rmax (determind after multiplying intrinsic by Rmult)

This is Gamma(Rgamma+2,Rmin) - Gamma(Rgamma+2,Rmax)

sim_repeaters(Rthresh, beam_b, Solid, doplots=False, Exact=True, MC=False, Rmult=None)[source]

Simulates once-off and repeat bursts for a given value of b (sensitivity) Rthresh: threshold in ergs on a z-DM grid beam_b: value of beam for this calculation solid: solid angle corresponding to beam value b MC: if True, performs MC evaluation. Skips if False doplots: plots a bunch of stuff if True

calcRmult(beam_b=1, time_days=1)[source]

beam_b: value of sensitivity time: time spent on this pointing

We also need to account for the rate scaling if it exists.

MCsample(Rthresh, Rmult, doplots=False, tag=None)[source]

Samples FRBs from Rthresh upwards

Rmult scales a repeater rate to an expected Nevents rate

Rthresh alrady has the Tfield baked into it. Rmult also has the Tfield baked into it.

volume_grid should be in units of Mpc^3, accounting for solid angle and dV/dz/dOmega

tag: only used if plotting

GenNReps(Rthresh, Nreps)[source]

Samples N random FRB rates R above Rthresh

CDF [integral Rstar to Rmax] = (R**Rgamma - Rthresh**gamma) / (Rmax**Rgamma - Rthresh**gamma)

do_2D_plot(array, savename, log=True, clabel='', lrange=4, zmax=1)[source]

does a standard imshow

do_z_plot(array, savename, log=True, label='', ratio=False)[source]

does a standard 1d plot projected onto the z axis

if ratio is True: divide all plots by the last one

calc_p_no_repeaters(Npointings)[source]

Calculates the probability per volume that there are no progenitors there By default, does this for a single pointing AND all pointings combined Not currently used, might be in the future. Useful!

calc_stochastic_distance(p)[source]

Calculates the distance out to which the chance of there being any progenitors becomes p, beyond which the chance is higher

calc_p_no_bursts(Tobs, N1thresh=0.1, N3thresh=10.0)[source]

calculates the chance that no bursts are observed in a given volume This is an integral over the repeater and luminosity distributions

The chance of having no bursts is:

Outer integral over distribution of repeaters: int_Rmin ^ Rmax C_r R^gamma dV [] dR Inner integral

p(no bursts) = int (rate) p(no repeaters) + p(no bursts | repeaters) dR

The following gives the fraction of the total luminosity function visible

at any given distance. It has already been integrated over beamshape and width self.fractions

# breaks the calculation into many steps. These are:

# High repetition regime: chance of detecting an FRB given a repeater is 100% # Calculate pure chance of any FRB existing

# calculates the fraction of the luminosity function visible at any given distance calc_effective_rate()

Classes

repeat_Grid(survey, state, zDMgrid, zvals, ...)

This class is designed to take a p(z,DM) grid and calculate the effects of repeating FRBs.

Computation Modules

Physics and statistics modules for computing cosmological quantities, DM probability distributions, and energy functions.

cosmology

Lambda CDM cosmology calculations including distance measures (comoving, angular diameter, luminosity), volume elements, and source evolution functions. Uses interpolation tables for fast array operations.

zdm.cosmology Module

Cosmology module for the zdm package.

This module implements standard Lambda CDM cosmology calculations for Fast Radio Burst (FRB) redshift-dispersion measure analysis. It provides functions for computing cosmological distance measures, volume elements, and energy-fluence conversions.

The module uses a convention where the spectral index alpha is defined such that F_nu ~ nu^(-alpha), i.e., positive alpha corresponds to steeper spectra at higher frequencies.

Key Features

  • Hubble parameter and scale factor calculations

  • Distance measures: comoving (DM), angular diameter (DA), luminosity (DL)

  • Cosmological volume elements (dV) and time-volume elements (dVdtau)

  • Interpolated lookup tables for fast array operations

  • Energy-fluence conversions for FRB analysis

  • Source evolution functions (SFR, power-law)

Usage

Before using interpolated functions (dm, da, dl, dv, dvdtau), call init_dist_measures() to populate the lookup tables. The cosmology can be configured via set_cosmology().

Example

>>> from zdm import cosmology as cos
>>> cos.init_dist_measures()
>>> z = 0.5
>>> d_L = cos.dl(z)  # Luminosity distance in Mpc

Author: Clancy W. James (clancy.w.james@gmail.com)

zdm.cosmology.c_light_kms = 299792.458

Omega_m=DEF_Omega_m Omega_k=DEF_Omega_k Omega_lambda=DEF_Omega_lambda H0=DEF_H0 DH=c_light_kms/H0

zdm.cosmology.print_cosmology(params)[source]

Print the current cosmological parameters.

Parameters:

params (dict or State) – Parameter dictionary or State object containing ‘cosmo’ key with CosmoParams object.

zdm.cosmology.set_cosmology(params)[source]

Set the global cosmology parameters for this module.

This function must be called before using distance measure functions if non-default cosmology is desired.

Parameters:

params (dict or State) – Parameter dictionary or State object containing ‘cosmo’ key with CosmoParams object specifying H0, Omega_m, Omega_lambda, Omega_k.

zdm.cosmology.H(z)[source]

Hubble parameter (km/s/Mpc)

Parameters:

z (float) – redshift

Returns:

Hubble parameter [km/s/Mpc]

Return type:

float

zdm.cosmology.E(z)[source]

Dimensionless Hubble parameter E(z) = H(z)/H0.

Computes the normalized expansion rate assuming flat Lambda CDM cosmology.

Parameters:

z (float or array_like) – Redshift(s) at which to evaluate E(z).

Returns:

Dimensionless Hubble parameter E(z) = sqrt(Omega_m*(1+z)^3 + Omega_k*(1+z)^2 + Omega_lambda).

Return type:

float or ndarray

zdm.cosmology.inv_E(z)[source]

Inverse of dimensionless Hubble parameter, 1/E(z).

Used as integrand for computing comoving distance.

Parameters:

z (float) – Redshift.

Returns:

1/E(z), where E(z) is the dimensionless Hubble parameter.

Return type:

float

zdm.cosmology.DM(z)[source]

Comoving distance (line-of-sight) via numerical integration.

This is the slow but accurate version. For array operations, use the interpolated version dm() after calling init_dist_measures().

Parameters:

z (float) – Redshift.

Returns:

Comoving distance in Mpc.

Return type:

float

zdm.cosmology.DA(z)[source]

Angular diameter distance via numerical integration.

This is the slow but accurate version. For array operations, use the interpolated version da() after calling init_dist_measures().

Parameters:

z (float) – Redshift.

Returns:

Angular diameter distance in Mpc.

Return type:

float

zdm.cosmology.DL(z)[source]

Luminosity distance via numerical integration.

This is the slow but accurate version. For array operations, use the interpolated version dl() after calling init_dist_measures().

Parameters:

z (float) – Redshift.

Returns:

Luminosity distance in Mpc.

Return type:

float

zdm.cosmology.dV(z)[source]

Comoving volume element per unit redshift per steradian.

Computes dV/dz/dOmega, the differential comoving volume element. This does not include any time dilation factor for rate conversions.

Parameters:

z (float) – Redshift.

Returns:

Volume element in Mpc^3 per unit redshift per steradian.

Return type:

float

zdm.cosmology.dVdtau(z)[source]

Time-weighted comoving volume element per unit redshift per steradian.

Similar to dV(z) but includes an extra (1+z)^-1 factor to account for cosmological time dilation when converting between source-frame and observer-frame event rates.

Parameters:

z (float) – Redshift.

Returns:

Time-weighted volume element in Mpc^3 per unit redshift per steradian.

Return type:

float

zdm.cosmology.init_dist_measures(this_ZMIN=0, this_ZMAX=10, this_NZ=1000, verbose=False)[source]

Initialize interpolation tables for fast distance measure calculations.

This function populates lookup tables for comoving distance, angular diameter distance, luminosity distance, and volume elements. After initialization, the lowercase functions (dm, da, dl, dv, dvdtau) can be used for fast array operations.

Must be called before using the interpolated distance functions. Uses current cosmological parameters set via set_cosmology().

Parameters:
  • this_ZMIN (float, optional) – Minimum redshift for interpolation grid. Default is 0.

  • this_ZMAX (float, optional) – Maximum redshift for interpolation grid. Default is 10.

  • this_NZ (int, optional) – Number of redshift points in interpolation grid. Default is 1000.

  • verbose (bool, optional) – If True, print confirmation message. Default is False.

zdm.cosmology.dm(z)[source]

Comoving distance via linear interpolation (fast, array-compatible).

Requires prior call to init_dist_measures() to populate lookup tables.

Parameters:

z (float or array_like) – Redshift(s). Must be within [ZMIN, ZMAX] set during initialization.

Returns:

Comoving distance in Mpc.

Return type:

float or ndarray

zdm.cosmology.dl(z)[source]

Luminosity distance via linear interpolation (fast, array-compatible).

Requires prior call to init_dist_measures() to populate lookup tables.

Parameters:

z (float or array_like) – Redshift(s). Must be within [ZMIN, ZMAX] set during initialization.

Returns:

Luminosity distance in Mpc.

Return type:

float or ndarray

zdm.cosmology.da(z)[source]

Angular diameter distance via linear interpolation (fast, array-compatible).

Requires prior call to init_dist_measures() to populate lookup tables.

Parameters:

z (float or array_like) – Redshift(s). Must be within [ZMIN, ZMAX] set during initialization.

Returns:

Angular diameter distance in Mpc.

Return type:

float or ndarray

zdm.cosmology.dv(z)[source]

Comoving volume element via linear interpolation (fast, array-compatible).

Requires prior call to init_dist_measures() to populate lookup tables.

Parameters:

z (float or array_like) – Redshift(s). Must be within [ZMIN, ZMAX] set during initialization.

Returns:

Volume element in Mpc^3 per unit redshift per steradian.

Return type:

float or ndarray

zdm.cosmology.dvdtau(z)[source]

Time-weighted volume element via linear interpolation (fast, array-compatible).

Includes (1+z)^-1 factor for source-frame to observer-frame rate conversion. Requires prior call to init_dist_measures() to populate lookup tables.

Parameters:

z (float or array_like) – Redshift(s). Must be within [ZMIN, ZMAX] set during initialization.

Returns:

Time-weighted volume element in Mpc^3 per unit redshift per steradian.

Return type:

float or ndarray

zdm.cosmology.E_to_F(E, z, alpha=0, bandwidth=1000000000.0)[source]

Convert isotropic-equivalent energy to observed fluence.

Uses the formula from Macquart & Ekers (2018) to convert burst energy at the source to observed fluence at the telescope.

Parameters:
  • E (float or array_like) – Isotropic-equivalent burst energy in erg.

  • z (float or array_like) – Redshift of the source.

  • alpha (float, optional) – Spectral index where F_nu ~ nu^(-alpha). Default is 0 (flat spectrum).

  • bandwidth (float, optional) – Observation bandwidth in Hz. Default is 1e9 (1 GHz).

Returns:

Fluence in Jy ms.

Return type:

float or ndarray

zdm.cosmology.F_to_E(F, z, alpha=0, bandwidth=1000000000.0, Fobs=1300000000.0, Fref=1300000000.0)[source]

Convert observed fluence to isotropic-equivalent energy.

Uses the formula from Macquart & Ekers (2018) to convert observed fluence to source-frame burst energy. Supports array inputs for z.

Parameters:
  • F (float or array_like) – Observed fluence in Jy ms.

  • z (float or array_like) – Redshift of the source.

  • alpha (float, optional) – Spectral index where F_nu ~ nu^(-alpha). Default is 0 (flat spectrum). Note: This uses the convention F ~ nu^(-alpha), opposite to some papers.

  • bandwidth (float, optional) – Observation bandwidth in Hz. Default is 1e9 (1 GHz).

  • Fobs (float, optional) – Observation frequency in Hz. Default is 1.3e9 (1.3 GHz, ASKAP/Parkes).

  • Fref (float, optional) – Reference frequency for energy normalization in Hz. Default is 1.3e9.

Returns:

Isotropic-equivalent burst energy in erg.

Return type:

float or ndarray

Notes

Unit conversion factor 9.523396e22 accounts for: - 10^-26 from Jy to W/m^2/Hz - 1e-3 from ms to s - (3.086e22 m/Mpc)^2 for distance conversion - 1e7 from J to erg

zdm.cosmology.dFnu_to_dEnu(z, alpha=0, bandwidth=1000000000.0)[source]

Compute the Jacobian dE/dF for fluence-to-energy transformations.

Useful for converting “per fluence” statistics to “per energy” statistics. This is the derivative of energy with respect to fluence at fixed z.

Parameters:
  • z (float or array_like) – Redshift.

  • alpha (float, optional) – Spectral index where F_nu ~ nu^(-alpha). Default is 0.

  • bandwidth (float, optional) – Observation bandwidth in Hz. Default is 1e9.

Returns:

Jacobian dE/dF for the transformation.

Return type:

float or ndarray

zdm.cosmology.choose_source_evolution_function(which=0)[source]

Select a source evolution function for FRB population modeling.

Returns a function that computes the relative FRB source density as a function of redshift. These functions are parameterized to allow for different evolution scenarios.

Parameters:

which (int, optional) –

Model selection: - 0: Star formation rate from Madau & Dickinson (2014) raised to power n.

SFR(z)^n where SFR follows the cosmic star formation history.

  • 1: Simple power law (1+z)^(2.7*n), without the high-z turnover.

    Useful for comparison with SFR model.

Default is 0.

Returns:

Source evolution function with signature f(z, n) where z is redshift and n is the evolution power parameter.

Return type:

callable

Raises:

ValueError – If which is not 0 or 1.

zdm.cosmology.sfr_evolution(z, *params)[source]

Star formation rate evolution model from Madau & Dickinson (2014).

Computes the cosmic star formation rate raised to a power n, normalized to unity at z=0.

Parameters:
  • z (float or array_like) – Redshift.

  • *params (float) – First parameter is n, the power to which the SFR is raised. Typically n=1 for direct SFR tracking.

Returns:

Relative source density at redshift z, normalized to 1 at z=0.

Return type:

float or ndarray

zdm.cosmology.opz_evolution(z, *params)[source]

Simple power-law source evolution model.

Computes (1+z)^(2.7*n), which matches the low-z behavior of the SFR model but lacks the high-z turnover. The factor 2.7 ensures that n-values are comparable between models.

Parameters:
  • z (float or array_like) – Redshift.

  • *params (float) – First parameter is n, the evolution power parameter.

Returns:

Relative source density at redshift z.

Return type:

float or ndarray

zdm.cosmology.sfr(z)[source]

Star formation rate density from Madau & Dickinson (2014).

Deprecated since version Use: sfr_evolution(z, 1) instead for parameterized models.

Parameters:

z (float or array_like) – Redshift.

Returns:

Star formation rate in solar masses per year per cubic Mpc, normalized to approximately 1 at z=0.

Return type:

float or ndarray

Functions

DA(z)

Angular diameter distance via numerical integration.

DL(z)

Luminosity distance via numerical integration.

DM(z)

Comoving distance (line-of-sight) via numerical integration.

E(z)

Dimensionless Hubble parameter E(z) = H(z)/H0.

E_to_F(E, z[, alpha, bandwidth])

Convert isotropic-equivalent energy to observed fluence.

F_to_E(F, z[, alpha, bandwidth, Fobs, Fref])

Convert observed fluence to isotropic-equivalent energy.

H(z)

Hubble parameter (km/s/Mpc)

choose_source_evolution_function([which])

Select a source evolution function for FRB population modeling.

dFnu_to_dEnu(z[, alpha, bandwidth])

Compute the Jacobian dE/dF for fluence-to-energy transformations.

dV(z)

Comoving volume element per unit redshift per steradian.

dVdtau(z)

Time-weighted comoving volume element per unit redshift per steradian.

da(z)

Angular diameter distance via linear interpolation (fast, array-compatible).

dl(z)

Luminosity distance via linear interpolation (fast, array-compatible).

dm(z)

Comoving distance via linear interpolation (fast, array-compatible).

dv(z)

Comoving volume element via linear interpolation (fast, array-compatible).

dvdtau(z)

Time-weighted volume element via linear interpolation (fast, array-compatible).

init_dist_measures([this_ZMIN, this_ZMAX, ...])

Initialize interpolation tables for fast distance measure calculations.

inv_E(z)

Inverse of dimensionless Hubble parameter, 1/E(z).

opz_evolution(z, *params)

Simple power-law source evolution model.

print_cosmology(params)

Print the current cosmological parameters.

set_cosmology(params)

Set the global cosmology parameters for this module.

sfr(z)

Star formation rate density from Madau & Dickinson (2014).

sfr_evolution(z, *params)

Star formation rate evolution model from Madau & Dickinson (2014).

pcosmic

Probability distribution of cosmic dispersion measure given redshift, p(DM|z). Implements the Macquart relation from Macquart et al. (2020) with the feedback parameter F controlling variance. Also provides host galaxy DM convolution kernels.

zdm.pcosmic Module

Probability distribution of cosmic dispersion measure given redshift, p(DM|z).

This module implements the Macquart relation - the probability distribution of cosmic (extragalactic) dispersion measure as a function of redshift. It is based on the formalism described in Macquart et al. (2020, Nature) and implements Equation 4 from that work.

The cosmic DM arises from free electrons in the intergalactic medium (IGM). The distribution is characterized by a feedback parameter F that controls the variance, and normalization constant C0 that ensures <DM> = DM_cosmic.

Key Features

  • p(DM|z) calculation using the modified lognormal distribution

  • Mean cosmic DM from the Macquart relation using astropy/frb cosmology

  • Lognormal host galaxy DM contribution convolution

  • Interpolation utilities for fast grid-based calculations

Main Functions

  • pcosmic: Core probability distribution function p(delta|z,F)

  • get_mean_DM: Compute mean cosmic DM at given redshifts

  • get_pDM_grid: Generate 2D grid of p(DM|z) probabilities

  • get_dm_mask: Generate host galaxy DM convolution kernel

References

Macquart et al. (2020), Nature, 581, 391 - “A census of baryons in the Universe from localized fast radio bursts”

Author: C.W. James

zdm.pcosmic.p(DM, z, F)[source]
zdm.pcosmic.pcosmic(delta, z, logF, C0)[source]

Probability density of fractional cosmic DM, p(delta|z).

Implements Equation 4 from Macquart et al. (2020) for the probability distribution of cosmic DM fluctuations. The distribution is parameterized such that delta = DM_cosmic / <DM_cosmic> follows a modified log-normal with redshift-dependent width.

Parameters:
  • delta (float or array_like) – Fractional cosmic DM, defined as DM_cosmic / <DM_cosmic>. Must be positive.

  • z (float) – Redshift. Used to compute the width parameter sigma = F * z^(-0.5).

  • logF (float) – Log10 of the feedback/fluctuation parameter F. Controls the width of the distribution. Typical values are logF ~ -0.5 to 0.

  • C0 (float) – Normalization constant that ensures <delta> = 1. Should be computed via iterate_C0() for each (z, F) pair.

Returns:

Probability density p(delta|z). Not normalized; integrate over delta for normalization.

Return type:

float or ndarray

Notes

Uses module-level constants alpha=3, beta=3 as shape parameters. The standard deviation scales as F * z^(-0.5), reflecting the central limit theorem averaging of IGM fluctuations along the line of sight.

zdm.pcosmic.p_delta_DM(z, F, C0, deltas=None, dmin=0.001, dmax=10, ndelta=10000)[source]

Calculate the probability distribution of fractional DM.

Wrapper around pcosmic that generates a grid of delta values and computes the probability at each point.

Parameters:
  • z (float) – Redshift.

  • F (float) – Log10 of the feedback parameter.

  • C0 (float) – Normalization constant.

  • deltas (array_like, optional) – Pre-defined delta values. If None, generates a linear grid.

  • dmin (float, optional) – Minimum delta value if generating grid. Default is 1e-3.

  • dmax (float, optional) – Maximum delta value if generating grid. Default is 10.

  • ndelta (int, optional) – Number of delta points if generating grid. Default is 10000.

Returns:

  • deltas (ndarray) – Array of fractional DM values.

  • pdeltas (ndarray) – Probability density at each delta value.

zdm.pcosmic.iterate_C0(z, F, C0=1, Niter=10)[source]

Iteratively solve for the normalization constant C0.

The constant C0 ensures that the mean of the p(delta) distribution equals unity, i.e., <delta> = 1. This is required for the distribution to correctly represent DM_cosmic / <DM_cosmic>.

Parameters:
  • z (float) – Redshift.

  • F (float) – Log10 of the feedback parameter.

  • C0 (float, optional) – Initial guess for C0. Default is 1.

  • Niter (int, optional) – Number of iterations. Default is 10.

Returns:

Converged value of C0.

Return type:

float

zdm.pcosmic.make_C0_grid(zeds, F)[source]

Pre-compute C0 normalization constants for a grid of redshifts.

Parameters:
  • zeds (ndarray) – Array of redshift values.

  • F (float) – Log10 of the feedback parameter.

Returns:

Array of C0 values, one per redshift.

Return type:

ndarray

zdm.pcosmic.get_mean_DM(zeds: ndarray, state: State, Plot=False)[source]

Compute the mean cosmic DM at given redshifts (Macquart relation).

Calculates <DM_cosmic>(z) using the IGM electron density model from the frb package. Assumes a FlatLambdaCDM cosmology with parameters from the state object.

Parameters:
  • zeds (ndarray) – Redshifts at which to compute mean DM. Must be linearly spaced and represent bin centers (e.g., 0.5*dz, 1.5*dz, 2.5*dz, …).

  • state (parameters.State) – State object containing cosmological parameters (H0, Omega_b, Omega_m).

  • Plot (bool, optional) – If True, generate diagnostic plots of DM vs z. Default is False.

Returns:

Mean cosmic DM values in pc/cm^3 at each redshift.

Return type:

ndarray

Notes

Uses frb.dm.igm.average_DM for the underlying calculation. The redshifts must be evenly spaced for correct bin assignment.

zdm.pcosmic.get_log_mean_DM(zeds: ndarray, state: State)[source]

Compute mean cosmic DM for arbitrarily-spaced redshifts.

Similar to get_mean_DM but does not require linearly-spaced redshifts. Slower because it evaluates each redshift independently.

Parameters:
  • zeds (ndarray) – Redshifts at which to compute mean DM. Can have any spacing.

  • state (parameters.State) – State object containing cosmological parameters.

Returns:

Mean cosmic DM values in pc/cm^3 at each redshift.

Return type:

ndarray

zdm.pcosmic.get_C0(z, F, zgrid, Fgrid, C0grid)[source]

Interpolate C0 from a pre-computed grid.

Performs bilinear interpolation on a pre-computed grid of C0 values to obtain C0 for arbitrary (z, F) pairs.

Parameters:
  • z (float) – Redshift at which to interpolate.

  • F (float) – Log10 of feedback parameter.

  • zgrid (ndarray) – Redshift grid points used to build C0grid.

  • Fgrid (ndarray) – Log10(F) grid points used to build C0grid.

  • C0grid (ndarray) – 2D array of pre-computed C0 values, shape (len(zgrid), len(Fgrid)).

Returns:

Interpolated C0 value.

Return type:

float

zdm.pcosmic.get_pDM(z, F, DMgrid, zgrid, Fgrid, C0grid, zlog=False)[source]

Compute p(DM|z) for a single redshift using pre-computed tables.

Parameters:
  • z (float) – Redshift.

  • F (float) – Log10 of feedback parameter.

  • DMgrid (ndarray) – DM values at which to evaluate the distribution.

  • zgrid (ndarray) – Redshift grid for C0 interpolation.

  • Fgrid (ndarray) – Feedback parameter grid for C0 interpolation.

  • C0grid (ndarray) – Pre-computed C0 values.

  • zlog (bool, optional) – If True, use log-spaced z grid. If False (default), use linear spacing.

Returns:

Probability density p(DM|z) at each DM grid point.

Return type:

ndarray

zdm.pcosmic.get_pDM_grid(state: State, DMgrid, zgrid, C0s, verbose=False, zlog=False)[source]

Generate a 2D grid of p(DM|z) probabilities.

Computes the probability distribution of cosmic DM for each redshift in the grid. This is the main function for building z-DM grids.

Parameters:
  • state (parameters.State) – State object containing cosmological and IGM parameters.

  • DMgrid (ndarray) – DM values (bin centers) for the output grid, in pc/cm^3.

  • zgrid (ndarray) – Redshift values for the output grid.

  • C0s (ndarray) – Pre-computed C0 normalization constants for each redshift.

  • verbose (bool, optional) – If True, print diagnostic information. Default is False.

  • zlog (bool, optional) – If True, zgrid is log-spaced. If False (default), linearly spaced.

Returns:

2D array of shape (len(zgrid), len(DMgrid)) containing normalized p(DM|z) values. Each row sums to 1.

Return type:

ndarray

zdm.pcosmic.linlognormal_dlin(DM, *args)[source]

Lognormal probability density in linear DM space.

Computes p(DM) where DM follows a lognormal distribution with parameters given in natural log space. Includes the 1/DM Jacobian for conversion from log to linear probability density.

Parameters:
  • DM (float or array_like) – Dispersion measure values (linear scale).

  • *args (tuple) – (logmean, logsigma) - mean and standard deviation in natural log space.

Returns:

Probability density p(DM) such that integral p(DM) dDM = 1.

Return type:

float or ndarray

zdm.pcosmic.loglognormal_dlog(logDM, *args)[source]

Gaussian probability density in log DM space.

This is simply a Gaussian distribution where the variable happens to be log(DM). Does not include Jacobian for log-to-linear conversion.

Parameters:
  • logDM (float or array_like) – Natural log of dispersion measure.

  • *args (tuple) – (logmean, logsigma, norm) - Gaussian parameters in log space.

Returns:

Probability density p(log DM) such that integral p(log DM) d(log DM) = 1.

Return type:

float or ndarray

zdm.pcosmic.plot_mean(zvals, saveas, title='Mean DM')[source]
zdm.pcosmic.get_dm_mask(dmvals, params, zvals=None, plot=False)[source]

Generate a convolution kernel for host galaxy DM contribution.

Creates a probability distribution p(DM_host) following a lognormal distribution. This kernel can be convolved with p(DM_cosmic|z) to obtain the full p(DM_extragalactic|z) = p(DM_cosmic + DM_host|z).

The host DM contribution is redshift-corrected: observed DM_host is reduced by (1+z) relative to the rest-frame value.

Parameters:
  • dmvals (ndarray) – DM grid values (bin centers) in pc/cm^3.

  • params (array_like) – [log10_mean, log10_sigma] - lognormal parameters for host DM distribution in log10 space.

  • zvals (ndarray, optional) – If provided, compute a redshift-dependent mask where host DM is scaled by 1/(1+z). If None, return a single z-independent mask.

  • plot (bool, optional) – If True, generate diagnostic plots. Default is False.

Returns:

If zvals is None: 1D array of shape (len(dmvals),) containing p(DM_host). If zvals is provided: 2D array of shape (len(zvals), len(dmvals)). Each row/vector is normalized to sum to 1.

Return type:

ndarray

Notes

The mask is designed for discrete convolution: p(DM_EG)[i] = sum_j p(DM_cosmic)[i-j] * mask[j]

zdm.pcosmic.integrate_pdm(ddm, ndm, logmean, logsigma, quick=True, plot=False)[source]

Discretize a lognormal DM distribution onto histogram bins.

Converts a continuous lognormal probability distribution into discrete bin probabilities for use in convolution operations. Two methods are available: fast (evaluate at bin centers) and slow (integrate each bin).

Parameters:
  • ddm (float) – Bin spacing in pc/cm^3.

  • ndm (int) – Number of DM bins. Bins span [0, ndm*ddm] with first bin [0, 0.5*ddm].

  • logmean (float) – Mean of the lognormal distribution in natural log space.

  • logsigma (float) – Standard deviation in natural log space.

  • quick (bool, optional) – If True (default), use fast method evaluating at bin centers. If False, integrate over each bin (slower but more accurate).

  • plot (bool, optional) – If True, generate comparison plot of quick vs slow methods and exit. Default is False.

Returns:

Array of shape (ndm,) containing probability mass in each bin. Not normalized; caller should normalize if needed.

Return type:

ndarray

Functions

embed(*[, header, compile_flags])

Call this to embed IPython at the current point in your program.

get_C0(z, F, zgrid, Fgrid, C0grid)

Interpolate C0 from a pre-computed grid.

get_dm_mask(dmvals, params[, zvals, plot])

Generate a convolution kernel for host galaxy DM contribution.

get_log_mean_DM(zeds, state)

Compute mean cosmic DM for arbitrarily-spaced redshifts.

get_mean_DM(zeds, state[, Plot])

Compute the mean cosmic DM at given redshifts (Macquart relation).

get_pDM(z, F, DMgrid, zgrid, Fgrid, C0grid)

Compute p(DM|z) for a single redshift using pre-computed tables.

get_pDM_grid(state, DMgrid, zgrid, C0s[, ...])

Generate a 2D grid of p(DM|z) probabilities.

integrate_pdm(ddm, ndm, logmean, logsigma[, ...])

Discretize a lognormal DM distribution onto histogram bins.

iterate_C0(z, F[, C0, Niter])

Iteratively solve for the normalization constant C0.

linlognormal_dlin(DM, *args)

Lognormal probability density in linear DM space.

loglognormal_dlog(logDM, *args)

Gaussian probability density in log DM space.

make_C0_grid(zeds, F)

Pre-compute C0 normalization constants for a grid of redshifts.

p(DM, z, F)

p_delta_DM(z, F, C0[, deltas, dmin, dmax, ...])

Calculate the probability distribution of fractional DM.

pcosmic(delta, z, logF, C0)

Probability density of fractional cosmic DM, p(delta|z).

plot_mean(zvals, saveas[, title])

energetics

FRB luminosity/energy function implementations including power-law and gamma-function distributions. Uses spline interpolation of the upper incomplete gamma function for computational efficiency during grid calculations.

zdm.energetics Module

FRB luminosity/energy function implementations.

This module provides functions for computing FRB luminosity (energy) distributions, including both cumulative and differential forms. The main luminosity functions implemented are:

  1. Power Law: Simple power-law distribution dN/dE ~ E^gamma between Emin and Emax

  2. Gamma Function: Upper incomplete gamma function distribution with exponential cutoff

The gamma function implementation uses spline interpolation for efficiency, as direct evaluation of the incomplete gamma function is computationally expensive when called many times during grid calculations.

Key Functions

  • vector_cum_power_law: Cumulative power-law luminosity function

  • vector_cum_gamma_spline: Cumulative gamma function with spline interpolation

  • array_cum_gamma_spline: N-dimensional array wrapper for gamma function

  • init_igamma_splines: Initialize spline lookup tables for gamma functions

Module Variables

igamma_splinesdict

Cache of spline interpolators keyed by gamma value.

SplineMin, SplineMaxfloat

Log10 range for spline interpolation.

SplineLogbool

If True, perform interpolation in log-log space (recommended).

Example

>>> from zdm import energetics
>>> Eth = np.logspace(38, 42, 100)  # Energy thresholds in erg
>>> params = (1e38, 1e42, -1.5)  # Emin, Emax, gamma
>>> fraction = energetics.vector_cum_power_law(Eth, *params)
zdm.energetics.init_igamma_splines(gammas, reinit=False, k=3)[source]

Initialize spline interpolators for the upper incomplete gamma function.

Pre-computes spline representations of the upper incomplete gamma function Gamma(gamma, x) for fast evaluation during grid calculations. Splines are cached globally and reused across calls.

Parameters:
  • gammas (list of float) – Values of gamma (the shape parameter) for which to create splines.

  • reinit (bool, optional) – If True, reinitialize splines even if they already exist. Default False.

  • k (int, optional) – Degree of spline interpolation. Default is 3 (cubic). Valid range: 1-5. Note: k=2 and k=4 not recommended due to numerical issues.

Notes

If module variable SplineLog is True (default), interpolation is performed in log-log space, which provides better accuracy over the wide dynamic range of the incomplete gamma function.

zdm.energetics.init_igamma_linear(gammas: list, reinit: bool = False, log: bool = False)[source]

Initialize linear interpolators for the upper incomplete gamma function.

Alternative to spline interpolation using scipy’s interp1d.

Parameters:
  • gammas (list of float) – Values of gamma for which to create interpolators.

  • reinit (bool, optional) – If True, reinitialize even if interpolator exists. Default False.

  • log (bool, optional) – If True, perform interpolation in log10 space. Default False.

zdm.energetics.template_array_cumulative_luminosity_function(Eth, *params)[source]

Template for a cumulative luminosity function Returns fraction of cumulative distribution above Eth Luminosity function is defined by *params Eth is a multidimensional numpy array Always just wraps the vector version

zdm.energetics.template_vector_cumulative_luminosity_function(Eth, *params)[source]

Template for a cumulative luminosity function Returns fraction of cumulative distribution above Eth Luminosity function is defined by *params Eth is a 1D numpy array This example uses a cumulative power law

zdm.energetics.vector_cum_power_law(Eth, *params)[source]

Cumulative power-law luminosity function.

Computes the fraction of bursts with energy above threshold Eth for a power-law distribution dN/dE ~ E^gamma between Emin and Emax.

Parameters:
  • Eth (ndarray) – Energy threshold values in erg.

  • *params (tuple) – (Emin, Emax, gamma) - minimum energy, maximum energy, power-law index. Gamma is typically negative (e.g., -1.5).

Returns:

Fraction of bursts with E > Eth. Returns 1 for Eth < Emin, 0 for Eth > Emax.

Return type:

ndarray

zdm.energetics.array_diff_power_law(Eth, *params)[source]

Calculates the differential fraction of bursts for a power law at a given Eth, where Eth is an N-dimensional array

zdm.energetics.array_cum_power_law(Eth, *params)[source]

Calculates the fraction of bursts above a certain power law for a given Eth, where Eth is an N-dimensional array

zdm.energetics.vector_diff_power_law(Eth, *params)[source]
zdm.energetics.vector_cum_gamma(Eth, *params)[source]

Cumulative gamma-function luminosity function (slow, exact version).

Computes the fraction of bursts with energy above threshold Eth using an upper incomplete gamma function distribution. This version evaluates the gamma function directly using mpmath - accurate but slow.

Parameters:
  • Eth (ndarray) – Energy threshold values in erg.

  • *params (tuple) – (Emin, Emax, gamma) - minimum energy, characteristic energy, shape parameter.

Returns:

Fraction of bursts with E > Eth. Returns 1 for Eth < Emin.

Return type:

ndarray

See also

vector_cum_gamma_spline

Fast spline-interpolated version (recommended).

zdm.energetics.vector_cum_gamma_spline(Eth: ndarray, *params)[source]

Cumulative gamma-function luminosity function using spline interpolation.

Fast version of vector_cum_gamma that uses pre-computed spline interpolators. This is the recommended function for grid calculations.

Parameters:
  • Eth (ndarray) – Energy threshold values in erg.

  • *params (tuple) – (Emin, Emax, gamma) - minimum energy, characteristic energy, shape parameter.

Returns:

Fraction of bursts with E > Eth. Returns 1 for Eth < Emin.

Return type:

ndarray

Notes

Automatically initializes splines for new gamma values if needed.

zdm.energetics.vector_cum_gamma_linear(Eth: ndarray, *params)[source]

Calculate cumulative Gamma function using a linear interp1d

Parameters:

Eth (np.ndarray) – Energy threshold in ergs

Returns:

cumulative probability above Eth

Return type:

np.ndarray

zdm.energetics.array_diff_gamma(Eth, *params)[source]

Calculates the differential fraction of bursts for a gamma function at a given Eth, where Eth is an N-dimensional array

zdm.energetics.array_cum_gamma(Eth, *params)[source]

Calculates the fraction of bursts above a certain gamma function for a given Eth, where Eth is an N-dimensional array

zdm.energetics.array_cum_gamma_spline(Eth, *params)[source]

Calculates the fraction of bursts above a certain gamma function for a given Eth, where Eth is an N-dimensional array

zdm.energetics.array_cum_gamma_linear(Eth, *params)[source]

Calculates the fraction of bursts above a certain gamma function for a given Eth, where Eth is an N-dimensional array

zdm.energetics.vector_diff_gamma(Eth, *params)[source]

Differential gamma-function luminosity function.

Computes dN/dE normalized such that the integral from Emin to infinity equals 1. This is the probability density of burst energies.

Parameters:
  • Eth (ndarray) – Energy values in erg at which to evaluate.

  • *params (tuple) – (Emin, Emax, gamma) - minimum energy, characteristic energy, shape parameter.

Returns:

Probability density dN/dE at each energy. Returns 0 for E < Emin.

Return type:

ndarray

Functions

array_cum_gamma(Eth, *params)

Calculates the fraction of bursts above a certain gamma function for a given Eth, where Eth is an N-dimensional array

array_cum_gamma_linear(Eth, *params)

Calculates the fraction of bursts above a certain gamma function for a given Eth, where Eth is an N-dimensional array

array_cum_gamma_spline(Eth, *params)

Calculates the fraction of bursts above a certain gamma function for a given Eth, where Eth is an N-dimensional array

array_cum_power_law(Eth, *params)

Calculates the fraction of bursts above a certain power law for a given Eth, where Eth is an N-dimensional array

array_diff_gamma(Eth, *params)

Calculates the differential fraction of bursts for a gamma function at a given Eth, where Eth is an N-dimensional array

array_diff_power_law(Eth, *params)

Calculates the differential fraction of bursts for a power law at a given Eth, where Eth is an N-dimensional array

embed(*[, header, compile_flags])

Call this to embed IPython at the current point in your program.

init_igamma_linear(gammas[, reinit, log])

Initialize linear interpolators for the upper incomplete gamma function.

init_igamma_splines(gammas[, reinit, k])

Initialize spline interpolators for the upper incomplete gamma function.

template_array_cumulative_luminosity_function(...)

Template for a cumulative luminosity function Returns fraction of cumulative distribution above Eth Luminosity function is defined by *params Eth is a multidimensional numpy array Always just wraps the vector version

template_vector_cumulative_luminosity_function(...)

Template for a cumulative luminosity function Returns fraction of cumulative distribution above Eth Luminosity function is defined by *params Eth is a 1D numpy array This example uses a cumulative power law

vector_cum_gamma(Eth, *params)

Cumulative gamma-function luminosity function (slow, exact version).

vector_cum_gamma_linear(Eth, *params)

Calculate cumulative Gamma function using a linear interp1d

vector_cum_gamma_spline(Eth, *params)

Cumulative gamma-function luminosity function using spline interpolation.

vector_cum_power_law(Eth, *params)

Cumulative power-law luminosity function.

vector_diff_gamma(Eth, *params)

Differential gamma-function luminosity function.

vector_diff_power_law(Eth, *params)

iteration

Likelihood calculation routines for z-DM grids. Computes log-likelihoods of FRB survey data given model predictions, including components for p(DM,z), Poisson number counts, SNR distributions, and width/scattering.

zdm.iteration Module

Likelihood calculation routines for z-DM grids.

This module provides functions for computing log-likelihoods of FRB survey data given model predictions from a Grid object. These likelihoods are used for parameter estimation via MCMC or maximum likelihood methods.

The main likelihood components include: - p(DM, z): Probability of observed DM and redshift (if localized) - p(N): Poisson probability of total number of FRBs detected - p(SNR): Signal-to-noise ratio distribution - p(w, tau): Width and scattering time distributions

Main Functions

  • get_log_likelihood: Compute total log-likelihood for a grid/survey pair

  • calc_likelihoods_1D: Likelihood for 1D (DM only) FRB data

  • calc_likelihoods_2D: Likelihood for 2D (DM + z) localized FRBs

Example

>>> from zdm import iteration
>>> ll = iteration.get_log_likelihood(grid, survey)
>>> print(f"Log-likelihood: {ll}")

Author: C.W. James

zdm.iteration.get_log_likelihood(grid, s, norm=True, psnr=True, Pn=False, pNreps=True, ptauw=False, pwb=False)[source]

Compute total log-likelihood for a grid given survey data.

This is the main likelihood function used for parameter estimation. It combines multiple likelihood components depending on what data is available (DM only, localized z, SNR, etc.).

Parameters:
  • grid (Grid or repeat_Grid) – Grid object containing model predictions.

  • s (Survey) – Survey object containing FRB observations.

  • norm (bool, optional) – If True, include normalization terms. Default True.

  • psnr (bool, optional) – If True, include SNR distribution likelihood. Default True.

  • Pn (bool, optional) – If True, include Poisson likelihood for total number. Default False.

  • pNreps (bool, optional) – If True, include number of repeaters likelihood. Default True.

  • ptauw (bool, optional) – If True, include p(tau, width) likelihood. Default False.

  • pwb (bool, optional) – If True, include width/beam likelihood. Default False.

Returns:

Total log-likelihood value.

Return type:

float

zdm.iteration.calc_likelihoods_1D(grid, survey, doplot=False, norm=True, psnr=True, Pn=False, pNreps=True, ptauw=False, pwb=False, dolist=0, grid_type=0)[source]

Calculates 1D likelihoods using only observedDM values Here, Zfrbs is a dummy variable allowing it to be treated like a 2D function for purposes of calling.

grid: the grid object calculated from survey

survey: survey object containing the observed z,DM values

doplot: will generate a plot of z,DM values

psnr:

True: calculate probability of observing each FRB at the observed SNR False: do not calculate this

Pn:

True: calculate probability of observing N FRBs False: do not calculate this

pNreps:

True: calculate probability of the number of repetitions for each repeater False: do not calculate this

ptauw:

True: calculate probability of intrinsic width and scattering given total width False: do not calculate this

pwb:

True: calculate probability of specific width and beam values, and psnr | bw False: do not calculate this; simply sum psnr over all possible p(b,w)

dolist:

0: returns total log10 likelihood llsum only [float] 1: also returns a dict of individual statistical contributions to log-likelihood 2: also returns the above for every FRB individually Structure of llsum and longlist:

[“pzDM”][“pDM”] [“pN”] [“Nexpected”] (only for [“ptauw”]

[“pbar”] [“piw”] [“ptau”] [“w_indices”]

[“pbw”]

[“pb”] [“pw”] [“pbgw”] [“pwgb”] [“pbw”] [“psnr_gbw”] [“psnrbw”]

lllist: <Nfrbs> longlist [list of lists]:

Pn: float zDM: PzDM zDM extras: P(z) P(DM), P(DM|z), P(z|DM) ptauw: p(tau|wtot), p(wtot), p(snr|wtot) psnr: p_snr (over all beams/widths) pwb: p(snr|b,w,z,dm), p(snr,b,w|z,DM), p(b|zDM), p(w|zDM), p(b|w,zDM), p(w|b,zDM), p(wb|zDM)

else: returns nothing (actually quite useful behaviour!)

grid_type:

0: normal zdm grid 1: assumes the grid passed is a repeat_grid.zdm_repeat_grid object and calculates likelihood for repeaters 2: assumes the grid passed is a repeat_grid.zdm_repeat_grid object and calculates likelihood for single bursts

zdm.iteration.calc_likelihoods_2D(grid, survey, doplot=False, norm=True, psnr=True, printit=False, Pn=False, pNreps=True, ptauw=False, pwb=False, dolist=0, verbose=False, grid_type=0)[source]

Calculates 2D likelihoods using observed DM,z values

grid: the grid object calculated from survey

survey: survey object containing the observed z,DM values

doplot: will generate a plot of z,DM values

psnr:

True: calculate probability of observing each FRB at the observed SNR False: do not calculate this

Pn:

True: calculate probability of observing N FRBs False: do not calculate this

pNreps:

True: calculate probability that each repeater detects the given number of bursts False: do not calculate this

ptauw:

True: calculate probability of intrinsic width and scattering given total width False: do not calculate this

pwb:

True: calculate probability of specific width and beam values, and psnr | bw False: do not calculate this; simply sum psnr over all possible p(b,w)

dolist:

0: returns total log10 likelihood llsum only [float] 1: also returns a dict of individual statistical contributions to log-likelihood 2: also returns the above for every FRB individually Structure of llsum and longlist:

[“pzDM”][“pDM”] [“pN”] [“Nexpected”] (only for [“ptauw”]

[“pbar”] [“piw”] [“ptau”] [“w_indices”]

[“pbw”]

[“pb”] [“pw”] [“pbgw”] [“pwgb”] [“pbw”] [“psnr_gbw”] [“psnrbw”]

lllist: <Nfrbs> longlist [list of lists]:

Pn: float zDM: PzDM zDM extras: P(z) P(DM), P(DM|z), P(z|DM) ptauw: p(tau|wtot), p(wtot), p(snr|wtot) psnr: p_snr (over all beams/widths) pwb: p(snr|b,w,z,dm), p(snr,b,w|z,DM), p(b|zDM), p(w|zDM), p(b|w,zDM), p(w|b,zDM), p(wb|zDM)

else: returns nothing (actually quite useful behaviour!)

norm:

True: calculates p(z,DM | FRB detected) False: calculates p(detecting an FRB with z,DM). Meaningless unless

some sensible normalisation has already been applied to the grid.

grid_type:

0: normal zdm grid 1: assumes the grid passed is a repeat_grid.zdm_repeat_grid object and calculates likelihood for repeaters 2: assumes the grid passed is a repeat_grid.zdm_repeat_grid object and calculates likelihood for single bursts

zdm.iteration.calc_DMG_weights(DMEGs, DMhalos, DM_ISMs, dmvals, sigma_ISM=0.5, sigma_halo_abs=15.0, log=False)[source]

Given an uncertainty on the DMG value, calculate the weights of DM values to integrate over

Inputs:

DMEGs = Extragalactic DMs DMhalo = Assumed constant (average) DMhalo DM_ISMs = Array of each DM_ISM value dmvals = Vector of DM values used sigma_ISM = Fractional uncertainty in DMG values sigma_halo = Uncertainty in DMhalo value (in pc/cm3)

Returns:

weights = Relative weights for each of the DM grid points iweights = Indices of the corresponding weights

zdm.iteration.CalculateMeaningfulConstant(pset, grid, survey, newC=False)[source]

Gets the flux constant, and quotes it above some energy minimum Emin

zdm.iteration.ConvertToMeaningfulConstant(state, Eref=1e+39)[source]

Gets the flux constant, and quotes it above some energy minimum Emin

zdm.iteration.Poisson_p(observed, expected)[source]

returns the Poisson likelihood

zdm.iteration.CalculateConstant(grid, survey)[source]

Calculates the best-fitting constant for the total number of FRBs. Units are:

  • grid volume units of ‘per Mpc^3’,

  • survey TOBS of ‘days’,

  • beam units of ‘steradians’

  • flux for FRBs with E > Emin

Hence the constant is ‘Rate (FRB > Emin) Mpc^-3 day^-1 sr^-1’ This should be scaled to be above some sensible value of Emin or otherwise made relevant.

zdm.iteration.CalculateIntegral(rates, survey, reps=False)[source]

Calculates the total expected number of FRBs for that rate array and survey

This does NOT include the aboslute number of FRBs (through the log-constant)

zdm.iteration.GetFirstConstantEstimate(grids, surveys, pset)[source]

simple 1D minimisation of the constant

zdm.iteration.minus_poisson_ps(log10C, data)[source]
zdm.iteration.minimise_const_only(vparams: dict, grids: list, surveys: list, Verbose=False, use_prev_grid: bool = True, update=False)[source]

Only minimises for the constant, but returns the full likelihood It treats the rest as constants the grids must be initialised at the currect values for pset already

Parameters:
  • vparams (dict) – Parameter dict. Can be None if nothing has varied.

  • grids (list) – List of grids

  • surveys (list) – List of surveys A bit superfluous as these are in the grids..

  • Verbose (bool, optional) – [description]. Defaults to True.

  • use_prev_grid (bool, optional) – If True, make use of the previous grid when looping over them. Defaults to True.

Raises:
Returns:

newC,llC,lltot

Return type:

tuple

zdm.iteration.parse_input_dict(input_dict: dict)[source]

Method to parse the input dict for generating a cube It is split up into its various pieces

Parameters:

input_dict (dict) – [description]

Returns:

dicts (can be empty): state, cube, input

Return type:

tuple

This is almost deprecated, but not quite!

Functions

CalculateConstant(grid, survey)

Calculates the best-fitting constant for the total number of FRBs. Units are: - grid volume units of 'per Mpc^3', - survey TOBS of 'days', - beam units of 'steradians' - flux for FRBs with E > Emin Hence the constant is 'Rate (FRB > Emin) Mpc^-3 day^-1 sr^-1' This should be scaled to be above some sensible value of Emin or otherwise made relevant.

CalculateIntegral(rates, survey[, reps])

Calculates the total expected number of FRBs for that rate array and survey

CalculateMeaningfulConstant(pset, grid, survey)

Gets the flux constant, and quotes it above some energy minimum Emin

ConvertToMeaningfulConstant(state[, Eref])

Gets the flux constant, and quotes it above some energy minimum Emin

GetFirstConstantEstimate(grids, surveys, pset)

simple 1D minimisation of the constant

Poisson_p(observed, expected)

returns the Poisson likelihood

calc_DMG_weights(DMEGs, DMhalos, DM_ISMs, dmvals)

Given an uncertainty on the DMG value, calculate the weights of DM values to integrate over

calc_likelihoods_1D(grid, survey[, doplot, ...])

Calculates 1D likelihoods using only observedDM values Here, Zfrbs is a dummy variable allowing it to be treated like a 2D function for purposes of calling.

calc_likelihoods_2D(grid, survey[, doplot, ...])

Calculates 2D likelihoods using observed DM,z values

embed(*[, header, compile_flags])

Call this to embed IPython at the current point in your program.

get_log_likelihood(grid, s[, norm, psnr, ...])

Compute total log-likelihood for a grid given survey data.

minimise_const_only(vparams, grids, surveys)

Only minimises for the constant, but returns the full likelihood It treats the rest as constants the grids must be initialised at the currect values for pset already

minimize(fun, x0[, args, method, jac, hess, ...])

Minimization of scalar function of one or more variables.

minus_poisson_ps(log10C, data)

parse_input_dict(input_dict)

Method to parse the input dict for generating a cube It is split up into its various pieces

Utility Modules

Helper functions for data loading, plotting, and common operations.

loading

High-level functions for loading surveys and initializing analysis state. Provides convenience functions like set_state() for creating properly configured State objects with default or best-fit parameters.

zdm.loading Module

High-level functions for loading surveys and initializing analysis state.

This module provides convenience functions for setting up zdm analysis, including loading survey data and creating properly configured State objects.

Main Functions

  • set_state: Create a State object with best-fit or default parameters

  • load_survey: Load a single survey from file

  • load_CHIME, load_Parkes, etc.: Survey-specific loaders

Example

>>> from zdm import loading
>>> state = loading.set_state()
>>> surveys, grids = loading.surveys_and_grids()
zdm.loading.set_state(alpha_method=1, cosmo=FlatLambdaCDM(name='Planck18', H0=<Quantity 67.66 km / (Mpc s)>, Om0=0.30966, Tcmb0=<Quantity 2.7255 K>, Neff=3.046, m_nu=<Quantity [0., 0., 0.06] eV>, Ob0=0.04897))[source]

Create a State object with default or best-fit parameters.

Initializes a State with parameters appropriate for FRB z-DM analysis. Parameter values depend on the chosen alpha_method.

Parameters:
  • alpha_method (int, optional) – Method for handling spectral index alpha. 0: Spectral index interpretation with k-correction. 1: Rate interpretation with (1+z)^alpha evolution (default).

  • cosmo (astropy.cosmology.Cosmology, optional) – Astropy cosmology to use. Default is Planck18.

Returns:

Initialized State object with all parameters set.

Return type:

parameters.State

zdm.loading.load_CHIME(Nbin: int = 6, make_plots: bool = False, opdir='CHIME/', Verbose=False, state=None)[source]

Loads CHIME grids Nbins is the number of declination bins to use

Parameters:
  • Nbin (int, optional) – Number of declination bins to use. Defaults to 6. 30 is allowed too

  • make_plots (bool, optional) – Whether to make plots. Defaults to False.

Returns:

dmvals (np.ndarray): 1D array of DM values zvals (np.ndarray): 1D array of redshift values all_rates (np.ndarray): 2D array of rates all_singles (np.ndarray): 2D array of single FRB rates all_reps (np.ndarray): 2D array of repeating FRB rates

Return type:

tuple

zdm.loading.surveys_and_grids(init_state=None, alpha_method=1, survey_names=None, nz: int = 500, ndm: int = 1400, zmax=5, dmmax=7000, NFRB=None, repeaters=False, sdir=None, edir=None, rand_DMG=False, discard_empty=False, state_dict=None, survey_dict=None, verbose=False)[source]

Load up a survey and grid for a real dataset

Parameters:
  • init_state (State, optional) – Initial state

  • survey_name (str, optional) – Defaults to ‘CRAFT/CRACO_1_5000’.

  • state_dict (dict, optional) – Used to init state instead of alpha_method, lum_func parameters

  • survey_names (list, optional) – List of surveys to load

  • add_20220610A (bool, optional) – Include this FRB (a bit of a hack)

  • nz (int, optional) – Number of redshift bins

  • ndm (int, optional) – Number of DM bins

  • zmax (float,optional) – Maximum value of redshift

  • dmmax (float,optional) – Maximum value of dispersion measure

  • edir (string, optional) – Directory containing efficiency files if using FRB-specific responses

  • rand_DMG (bool, optional) – If true, randomise the galactic DM - for MCMC studies

  • discard_empty (bool, optional) – If true, does not calculate empty surveys (mostly for after latitude cuts)

  • survey_dict (dict,None) – list of survey metadata and values to apply

Raises:

IOError – [description]

Returns:

lists of Survey, Grid objects

Return type:

tuple

Functions

embed(*[, header, compile_flags])

Call this to embed IPython at the current point in your program.

load_CHIME([Nbin, make_plots, opdir, ...])

Loads CHIME grids Nbins is the number of declination bins to use

set_state([alpha_method, cosmo, Om0, Tcmb0, ...])

Create a State object with default or best-fit parameters.

surveys_and_grids([init_state, ...])

Load up a survey and grid for a real dataset

misc_functions

Miscellaneous utility functions including grid initialization, parameter updates, probability calculations, and other common operations used throughout the package.

zdm.misc_functions Module

Miscellaneous utility functions for the zdm package.

This module contains various helper functions used throughout the zdm package including grid initialization, parameter updates, probability calculations, and other common operations.

Main Functions

  • make_zDMgrid: Initialize z-DM probability grids

  • get_zdm_grids: Create grids for multiple surveys

  • update_grid: Update grid with new parameter values

  • interpolate_grid: Interpolate grid values

zdm.misc_functions.get_w_tau_dist(grid, norm=True)[source]

This function determins the total width, tau, and intrinsic width distributions predicted by zDM. It returns histograms of each of these parameters, both 1D hists of total rates, and 2D hists projected onto the redshift axis.

Parameters:

grid – zdm grid object. Not yet implemented for a repeating grid

Returns:

array of width values pw [np.ndarray]: relative probabilities of observing those widths zvals [np.ndarray: nz]: grid.zvals pwz [np.ndarray: nw x nz]: probability of observing each width as a function of z dmvals [np.ndarray: ndm]: grid.dmvals pwdm [np.ndarray: nw x ndm]

Return type:

wvals [np.ndarray]

zdm.misc_functions.make_cum_dist(data)[source]

Gets cumulative distribution of the data ready for plotting

Parameters:

data (list or np.ndarray) – data for the distribution

Returns:

x values of cumulative distribution yvals (np.ndarray): x values of cumulative distribution

Return type:

xvals (np.ndarray)

zdm.misc_functions.get_width_stats(s, g)[source]

gets the probability of detecting tau or w for a given survey and grid

Parameters:
  • s – survey

  • g – correspondiong grid object

Returns:

Rate (per day) of detecting intrinsic width w Rtau (np.ndarray): Rate (per day) of detecting scattering time tau Nw (np.ndarray): Total number of FRBs as a function of total width Nwz (np.ndarray): Number of FRBs as a function of total width and redshift Nwdm (np.ndarray): Number of FRBs as a function of total width and DM

Return type:

Rw (np.ndarray)

zdm.misc_functions.j2000_to_galactic(ra_deg, dec_deg)[source]

Convert Galactic coordinates to Equatorial J2000 coordinates.

Parameters: l_deg (float): Galactic longitude in degrees b_deg (float): Galactic latitude in degrees

Returns: tuple: Right Ascension and Declination in degrees (RA, Dec)

# this code written by ChatGPT

zdm.misc_functions.galactic_to_j2000(l_deg, b_deg)[source]

Convert J2000 Equatorial coordinates to Galactic coordinates.

Parameters: ra_deg (float): Right Ascension in degrees dec_deg (float): Declination in degrees

Returns: tuple: Galactic longitude and latitude in degrees (l, b)

# this code written by ChatGPT

zdm.misc_functions.coord_string_to_deg(cstring, hr=False)[source]

Converts a coordinate string in form of deg:min:sec to deg

Parameters:
  • cstring (string) – string of deg:min:sec

  • hr (optional) – if True, assumes its hr:min:sec

Returns:

coordinate in degrees

Return type:

deg (float)

zdm.misc_functions.get_source_counts(grid, plot=None, Slabel=None)[source]

Calculates the source-counts function for a given grid It does this in terms of p(SNR)dSNR

WARNING: this function may not currently work, but is kept here as an example “how-to”

zdm.misc_functions.make_dm_redshift(grid, savename='', DMmax=1000, zmax=1, loc='upper left', Macquart=None, H0=None, showplot=False)[source]

generates full dm-redhsift (Macquart) relation

zdm.misc_functions.basic_width_test(pset, surveys, grids, logmean=2, logsigma=1)[source]

Tests the effects of intrinsic widths on FRB properties WARNING: outdated, but kept here for future width analysis

zdm.misc_functions.width_test(pset, surveys, grids, names, logmean=2, logsigma=1, plot=True, outdir='Plots/', NP=5, scale=3.5)[source]

Tests the effects of intrinsic widths on FRB properties Considers three cases:

  • width distribution of Wayne Arcus et al (2020)

  • width distribution specified by user (logmean, logsigma)

  • “practical” width distribution with a few width parameters

  • no width distribution (i.e. for width = 0)

WARNING: outdated, but kept here for future width analysis

zdm.misc_functions.test_pks_beam(surveys, zDMgrid, zvals, dmvals, pset, outdir='Plots/BeamTest/', zmax=1, DMmax=1000)[source]

WARNING: likely outdated, kept here for potential future adaptation

zdm.misc_functions.test_beam_rates(survey, zDMgrid, zvals, dmvals, pset, binset, method=2, outdir='Plots/BeamTest/', thresh=0.001, zmax=1, DMmax=1000)[source]

For a list of surveys, construct a zDMgrid object binset is the set of bins which we use to simplify the beamset We conclude that method=2, nbeams=5, acc=0 is the best here

WARNING: likely outdated, to be updated

zdm.misc_functions.initialise_grids(surveys: list, zDMgrid: ndarray, zvals: ndarray, dmvals: ndarray, state: State, wdist=True, repeaters=False)[source]

For a list of surveys, construct a zDMgrid object wdist indicates a distribution of widths in the survey, i.e. do not use the mean efficiency Assumes that survey efficiencies ARE initialised

Parameters:
  • surveys (list) – [description]

  • zDMgrid (np.ndarray) – [description]

  • zvals (np.ndarray) – [description]

  • dmvals (np.ndarray) – [description]

  • state (parameters.State) – parameters guiding the analysis Each grid gets its own copy

  • wdist (bool, optional) – [description]. Defaults to False.

Returns:

list of Grid objects

Return type:

list

zdm.misc_functions.get_filenames(datdir, state, tag, method)[source]

Initialises filenames for saving grid data.

Parameters:
  • [string] (method) – directory for saving

  • [zdm.state] (state) – state construct

  • [string] – unique tag to identify save files

  • [string] – MC or analytic

zdm.misc_functions.get_zdm_grid(state: State, new=True, plot=False, method='analytic', nz=500, zmin=0.01, zmax=5, ndm=1400, dmmax=7000.0, datdir='GridData', tag='', orig=False, verbose=False, save=False, zlog=False)[source]

Generate a grid of z vs. DM for an assumed F value for a specified z range and DM range.

Parameters:
  • state (parameters.State) – Object holding all the key parameters for the analysis

  • new (bool, optional) – True (default): generate a new grid False: load from file.

  • plot (bool, optional) – True: Make a2D plot of the zdm distribution. False (default): do nothing.

  • method (str, optional) – Method of generating p(DM|z). Analytic (default): use pcosic make_c0_grid MC: generate via Monte Carlo using dlas.monte_dm

  • nz (int, optional) – Size of grid in redshift. Defaults to 500.

  • zmin (float,optional) – Minimum z. Used only for log-spaced grids.

  • zmax (float, optional) – Maximum z. Defaults to 5. Represents the upper edge of the maximum zbin.

  • ndm (int, optional) – Size of grid in DM. Defaults to 1400.

  • dmmax ([type], optional) – Maximum DM of grid. Defaults to 7000. Represents the upper edge of the max bin in the DM grid.

  • datdir (str, optional) – Directory to load/save grid data. Defaults to ‘GridData’.

  • tag (str, optional) – Label for grids (unique identifier). Defaults to “”.

  • orig (bool, optional) – Use original calculations for things like C0. Defaults to False.

  • save (bool, optional) – Save the grid to disk?

  • zlog (bool, optional) – Use a log-spaced redshift grid? Defaults to False.

Returns:

zDMgrid, zvals, dmvals

Return type:

tuple

Functions

basic_width_test(pset, surveys, grids[, ...])

Tests the effects of intrinsic widths on FRB properties WARNING: outdated, but kept here for future width analysis

coord_string_to_deg(cstring[, hr])

Converts a coordinate string in form of deg:min:sec to deg

galactic_to_j2000(l_deg, b_deg)

Convert J2000 Equatorial coordinates to Galactic coordinates.

get_filenames(datdir, state, tag, method)

Initialises filenames for saving grid data.

get_source_counts(grid[, plot, Slabel])

Calculates the source-counts function for a given grid It does this in terms of p(SNR)dSNR

get_w_tau_dist(grid[, norm])

This function determins the total width, tau, and intrinsic width distributions predicted by zDM.

get_width_stats(s, g)

gets the probability of detecting tau or w for a given survey and grid

get_zdm_grid(state[, new, plot, method, nz, ...])

Generate a grid of z vs.

initialise_grids(surveys, zDMgrid, zvals, ...)

For a list of surveys, construct a zDMgrid object wdist indicates a distribution of widths in the survey, i.e. do not use the mean efficiency Assumes that survey efficiencies ARE initialised.

j2000_to_galactic(ra_deg, dec_deg)

Convert Galactic coordinates to Equatorial J2000 coordinates.

make_cum_dist(data)

Gets cumulative distribution of the data ready for plotting

make_dm_redshift(grid[, savename, DMmax, ...])

generates full dm-redhsift (Macquart) relation

mean(a[, axis, dtype, out, keepdims, where])

Compute the arithmetic mean along the specified axis.

test_beam_rates(survey, zDMgrid, zvals, ...)

For a list of surveys, construct a zDMgrid object binset is the set of bins which we use to simplify the beamset We conclude that method=2, nbeams=5, acc=0 is the best here

test_pks_beam(surveys, zDMgrid, zvals, ...)

WARNING: likely outdated, kept here for potential future adaptation

width_test(pset, surveys, grids, names[, ...])

Tests the effects of intrinsic widths on FRB properties Considers three cases: - width distribution of Wayne Arcus et al (2020) - width distribution specified by user (logmean, logsigma) - "practical" width distribution with a few width parameters - no width distribution (i.e. for width = 0).

figures

Plotting functions for visualizing z-DM grids and FRB data. Provides publication-quality plots of probability distributions and analysis results.

zdm.figures Module

Plotting functions for visualizing z-DM grids and FRB data.

This module provides functions for creating publication-quality plots of z-DM probability distributions, FRB populations, and analysis results.

Main Functions

  • plot_grid: Plot 2D z-DM probability grid with optional FRB overlays

  • plot_zdm_basic: Basic z-DM grid visualization

  • plot_1d_projection: Project grid onto z or DM axis

Author: C.W. James

zdm.figures.plot_grid(zDMgrid, zvals, dmvals, zmax=1, DMmax=1000, norm=0, log=True, name='temp.pdf', label='$\\log_{10}p(DM_{\\rm EG},z)$', ylabel='${\\rm DM}_{\\rm EG}$ (pc cm$^{-3}$)', logrange=4, project=False, conts=False, FRBZs=None, FRBDMs=None, plt_dicts=None, cont_dicts=None, cmap=None, Aconts=None, Macquart=None, title=None, H0=None, showplot=False, DMlines=None, DMlims=None, clim=False, special=None, pdmgz=None, save=True, othergrids=None, othernames=None, c_cmap=None, cont_clrs=None)[source]

Very complicated routine for plotting 2D zdm grids

Parameters:
  • zDMgrid (2D array) – P(z,DM) grid

  • zvals (1D array) – z values corresponding to zDMgrid

  • dmvals (1D array) – DM values corresponding to zDMgrid

  • zmax (int, optional) – Maximum z value to display

  • DMmax (int, optional) – Maximum DM value to display

  • norm (int, optional) – Method to normalise zDMgrid. 0: No normalisation 1: Normalise by dm bin 2: Normalise by sum of zDMgrid 3: Normalise by max value of zDMgrid 4: Set peak value at each z to unity

  • log (bool, optional) – Plot P(z,DM) in log space

  • name (str, optional) – Outfile name

  • label (str, optional) – Colourbar label

  • ylabel (str,optional) – Label on y axis of plot

  • logrange (float,optional) – range in logspace of the z axis (defaults to 4)

  • project (bool, optional) – Add projections of P(z) and P(DM)

  • conts (bool, optional) – create contours in probability p(dm|z), at fractional levels set by conts. Defaults to False.

  • FRBZs (list of 1D arrays, optional) – List of FRB Zs to plot (each list can have customised plotting styles, e.g. for different surveys)

  • FRBDMs (list of 1D arrays, optional) – List of FRB DMs to plot (corrseponding to FRBZs)

  • plt_dicts (list of dictionaries, optional) – List of dictionaries containing the plotting parameters for each ‘set’ of data points (corresponding to FRBZs and FRBDMs). E.g. can contain marker, color, label etc

  • cmap (str, optional) – Alternate color map for PDF

  • Aconts (bool, optional) – Create contours in 2D probabilty space, at fractional levels set by Aconts. Defaults to False.

  • Macquart (state, optional) – state object. Used to generate the Maquart relation. Defaults to None, i.e. do not show the Macquart relation.

  • title (str, optional) – Title of the plot

  • H0 ([type], optional) – [description]. Defaults to None.

  • showplot (bool, optional) – use plt.show to show plot. Defaults to False.

  • DMlines (list, optional) – plot lines for unlocalised FRBs at these DMs

  • DMlims (list, optional) – plot horizontal lines to indicate the maximum searched DM of a given survey

  • clim ([float,float], optional) – pair of floats giving colorbar limits. Defaults to False (automatic limit)

  • special (list,optional) – list of [z,dm] values to show as a special big star

  • pdmgz (list of floats, optional) – a list of cumulative values of p(DM|z) to plot. Must range from 0 to 1.

  • othergrids (list of grids) – a list of grids to plot contours for. Uses Aconts

  • othernames (list of names) – list of names for original and other grid. Used only if othergrids is not None. Must be length of othergrids +1.

  • c_cmap (string) – Name of colormap used to plot “Acont” contours

  • cont_clrs (float, np.ndarray) – list of colors in colourmap to use for contours

zdm.figures.get_alevels(zDMgrid, Aconts)[source]

Gets contour levels giving

Grid: inoput zDM grid Aconts: list of contour levels giving %

zdm.figures.find_Alevels(pgrid: ndarray, Aconts: list, norm: bool = True, log: bool = True)[source]
zdm.figures.proc_pgrid(pgrid: ndarray, ivals: ndarray, imnx: tuple, jvals: ndarray, jmnx: tuple, norm: bool = True, log: bool = True)[source]
zdm.figures.ticks_pgrid(vals, everyn=5, fmt=None, these_vals=None)[source]

Generate ticks for one of the P(x,x,x) grids

Parameters:
  • vals (_type_) – _description_

  • everyn (int, optional) – _description_. Defaults to 5.

  • fmt (_type_, optional) – _description_. Defaults to None.

  • these_vals (list or np.ndarray, optional) – Values to place the ticks at

Returns:

Tick locations, values

Return type:

np.ndarray, np.ndarray

zdm.figures.gen_cdf_hist(origx)[source]
Parameters:

origx (np.ndarray) – x values of the data

Returns:

x values of cdf plot yvals (np.ndarray): y values of cdf plot

Return type:

xvals (np.ndarray)

zdm.figures.plot_repeaters_zdist(g, prefix='', zmax=2)[source]

Plots the distribution of sources for a repeat grid

Parameters:
  • grids – list of repeat grid objects to plot

  • prefix – prfix for the output

Functions

find_Alevels(pgrid, Aconts[, norm, log])

gen_cdf_hist(origx)

get_alevels(zDMgrid, Aconts)

Gets contour levels giving

plot_grid(zDMgrid, zvals, dmvals[, zmax, ...])

Very complicated routine for plotting 2D zdm grids

plot_repeaters_zdist(g[, prefix, zmax])

Plots the distribution of sources for a repeat grid

proc_pgrid(pgrid, ivals, imnx, jvals, jmnx)

ticks_pgrid(vals[, everyn, fmt, these_vals])

Generate ticks for one of the P(x,x,x) grids

beams

Telescope beam pattern modeling utilities. Provides functions for generating and loading beam patterns (Gaussian, Airy, measured) that affect solid angle and sensitivity variations across the field of view.

zdm.beams Module

Telescope beam pattern modeling utilities.

This module provides functions for modeling and loading telescope beam patterns, which are essential for computing FRB detection efficiencies. Different telescopes have different beam shapes (Gaussian, Airy, measured) that affect the solid angle and sensitivity variations across the field of view.

Main Functions

  • gauss_beam: Generate Gaussian beam pattern

  • load_beam: Load measured beam pattern from file

  • Airy_beam: Generate Airy disk beam pattern

The beam is typically represented as a histogram of response values (b) and corresponding solid angle fractions (omega), allowing efficient integration over the beam when computing detection rates.

Author: C.W. James

zdm.beams.gauss_beam(thresh=0.001, nbins=10, freq=1400000000.0, D=64, sigma=None)[source]

initialises a Gaussian beam D in m, freq in MHz e.g. Parkes HWHM is 7 arcmin at 1.4 GHz #thresh 1e-3 means -6.7 is range in lnb, 3.74 range in sigma

zdm.beams.load_beam(prefix)[source]

Loads beams data, returns it with beam values b in log space

prefix: looks for files named [prefix]_bins.npy and [prefix]_hist.npy basedir: directory the histogram files are expected to be found in

The ‘_bins’ file should contain the (nbins+1) bin edges The ‘_hist’ file should contain solid angles within each bin Summing the _hist should return the total solid angle over

which the calculation has been performed.

zdm.beams.simplify_beam(logb, omega_b, nbins, thresh=0.0, weight=1.5, method=1, savename=None)[source]

Simplifies a beam to smaller histogram

Thresh is the threshold below which we cut out measurements. Defaults to including 99% of the rate. Simpler! weight tells us how to scale the omega_b to get effective means

method:

1: attempts to place equal probability into each beam bin 2: starts with lowest b-value where cumulative rate above thresh 3: no simplification, returns the full beam! 4: favours the first few bins 5: ignores the data, simply sets omeba_b to 1, b to 1 (e.g. for testing)

Functions

embed(*[, header, compile_flags])

Call this to embed IPython at the current point in your program.

files(package)

Get a Traversable resource from a package

gauss_beam([thresh, nbins, freq, D, sigma])

initialises a Gaussian beam D in m, freq in MHz e.g. Parkes HWHM is 7 arcmin at 1.4 GHz #thresh 1e-3 means -6.7 is range in lnb, 3.74 range in sigma.

load_beam(prefix)

Loads beams data, returns it with beam values b in log space

simplify_beam(logb, omega_b, nbins[, ...])

Simplifies a beam to smaller histogram

Analysis Modules

Parameter estimation and analysis tools.

MCMC

MCMC parameter estimation using the emcee package. Provides functions for running samplers, computing log-posteriors, and exploring parameter space with support for multiple surveys and uniform priors.

zdm.MCMC Module

MCMC parameter estimation for FRB z-DM analysis.

This module provides functions for running Markov Chain Monte Carlo (MCMC) parameter estimation using the emcee package. It interfaces with the zdm likelihood calculations to explore the parameter space and constrain FRB population and cosmological parameters.

Main Functions

  • calc_log_posterior: Compute log-posterior for a parameter vector

  • run_mcmc: Execute MCMC sampling with emcee

  • get_initial_walkers: Initialize walker positions

Features

  • Uniform priors with configurable bounds

  • Optional log/linear priors for specific parameters (DMhalo, host DM)

  • Support for multiple surveys and repeater populations

  • Grid re-initialization on each evaluation for parameter exploration

Example

>>> from zdm import MCMC
>>> params = {'gamma': {'min': -2.5, 'max': -0.5}, ...}
>>> sampler = MCMC.run_mcmc(state, params, surveys, nwalkers=32, nsteps=1000)
>>> samples = sampler.get_chain(flat=True)

Author: Jordan Hoffmann Date: 06/12/23

zdm.MCMC.calc_log_posterior(param_vals, state, params, surveys_sep, Pn=False, pNreps=True, ptauw=False, log_halo=False, lin_host=False, ind_surveys=False, g0info=None)[source]

Calculate log-posterior probability for a parameter vector.

This is the main function called by emcee samplers. It evaluates the log-posterior (proportional to log-likelihood for uniform priors) by building grids and computing likelihoods for all surveys.

Parameters:
  • param_vals (ndarray) – Array of parameter values for this MCMC step.

  • state (parameters.State) – State object to be updated with new parameter values.

  • params (dict) – Dictionary defining parameters to vary. Each key is a parameter name, with value dict containing ‘min’ and ‘max’ for prior bounds.

  • surveys_sep (list) – Two-element list: [non_repeater_surveys, repeater_surveys].

  • Pn (bool, optional) – Include Poisson likelihood for total number of FRBs. Default False.

  • pNreps (bool, optional) – Include likelihood for number of repeaters. Default True.

  • ptauw (bool, optional) – Include p(tau, width) likelihood. Default False.

  • log_halo (bool, optional) – Use log-uniform prior on DMhalo. Default False.

  • lin_host (bool, optional) – Use linear-uniform prior on host DM mean. Default False.

  • ind_surveys (bool, optional) – If True, return list of individual survey likelihoods. Default False.

  • g0info (list, optional) – Pre-computed [zDMgrid, zvals, DMvals] for speedup.

Returns:

Log-posterior value. Returns -inf if parameters outside prior bounds. If ind_surveys=True, returns (llsum, ll_list) with individual likelihoods.

Return type:

float or tuple

zdm.MCMC.mcmc_runner(logpf, outfile, state, params, surveys, nwalkers=10, nsteps=100, nthreads=1, Pn=False, pNreps=True, ptauw=False, log_halo=False, lin_host=False, ind_surveys=False, g0info=None, reset=False)[source]

Handles the MCMC running.

Inputs:

logpf (function) = Log posterior function handle outfile (string) = Name of the output file (excluding .h5 extension) state (params.state) = State object to modify params (dictionary) = Parameter names, min and max values surveys (list) = surveys_sep[0] : list of non-repeater surveys

surveys_sep[1] : list of repeater surveys

grid_params (dictionary) = nz, ndm, dmmax nwalkers (int) = Number of walkers nsteps (int) = Number of steps nthreads (int) = Number of threads (currently not implemented - uses default) Pn (bool) = Include Pn or not pNreps (bool) = Include pNreps or not ptauw (bool) = Include ptauw or not log_halo (bool) = Use a log uniform prior on DMhalo ind_surveys (bool) = Return individual survey data g0info (list) = List of [zDMgrid, zvals, DMvals] Passed to use as speedup if needed

Outputs:

posterior_sample (emcee.EnsembleSampler) = Final sample outfile.h5 (HDF5 file) = HDF5 file containing the sampler

Functions

calc_log_posterior(param_vals, state, ...[, ...])

Calculate log-posterior probability for a parameter vector.

mcmc_runner(logpf, outfile, state, params, ...)

Handles the MCMC running.

MCMC_analysis

Analysis utilities for MCMC chains including convergence diagnostics, corner plots, and posterior summaries.

zdm.MCMC_analysis Module

This file contains routines for analysing MCMC results

Routines here were written by Jordan Hoffmann

zdm.MCMC_analysis.plot_walkers(samples, labels, outfile, burnin=None, legend=True, xlim=None)[source]

Puts all walkers from all samples on one plot If you want different samples per plot, call this function multiple times

Parameters:
  • outfile (string) – name of outfile to print to

  • burnin (int) – length of initial burnin to discard

  • legend (bool) – Plot legend or not

  • xlim (None or [xmin,xmax] flots) – apply x limit, to zoom in for visibility purposes

zdm.MCMC_analysis.plot_autocorrelations(samples, opfile)[source]

Plot the autocorrelation time to estimate the burnin Do this once bad walkers have been discarded. To be done: proper explanation of what this routine is doing

zdm.MCMC_analysis.change_priors(sample, param_num, max=inf, min=-inf)[source]
zdm.MCMC_analysis.next_pow_two(n)[source]
zdm.MCMC_analysis.autocorr_func_1d(x, norm=True)[source]
zdm.MCMC_analysis.auto_window(taus, c)[source]
zdm.MCMC_analysis.autocorr(y, c=5.0)[source]
zdm.MCMC_analysis.auto_corr_rej(samples, burnin=0)[source]
zdm.MCMC_analysis.std_rej(samples, burnin=0)[source]

Functions

auto_corr_rej(samples[, burnin])

auto_window(taus, c)

autocorr(y[, c])

autocorr_func_1d(x[, norm])

change_priors(sample, param_num[, max, min])

next_pow_two(n)

plot_autocorrelations(samples, opfile)

Plot the autocorrelation time to estimate the burnin Do this once bad walkers have been discarded.

plot_walkers(samples, labels, outfile[, ...])

Puts all walkers from all samples on one plot If you want different samples per plot, call this function multiple times

std_rej(samples[, burnin])

analyze_cube

Tools for analyzing pre-computed parameter cubes.

zdm.analyze_cube Module

Codes to analyze cube outputs

zdm.analyze_cube.slurp_cube(input_file: str, prefix: str, outfile: str, nsurveys, debug: bool = False, suffix: str = '.csv')[source]

Slurp the cube ASCII output files and write lC and ll into a numpy savez file

Parameters:
  • input_file (str) – parameter file used to generate the cube

  • prefix (str) – prefix on the output files

  • outfile (str) – output file name. Should have .npz extension

  • nsurveys (int) – Number of surveys in the analysis.

  • debug (int, optional) – Debug?

  • suffix (str, optional) – File ending. Allows for old .out files

zdm.analyze_cube.apply_gaussian_prior(lls: ndarray, iparam: int, values: ndarray, mean: float, sigma: float)[source]

Applies a prior to parameter iparam with mean mean and deviation sigma.

Returns a vector of length lls modified by that prior.

zdm.analyze_cube.apply_H0_prior(lls: ndarray, H0dim: int, H0values: ndarray, cmbH0: float, cmb_sigma: float, sn1aH0: float, sn1a_sigma: float)[source]

Applies a prior as a function of H0

This is flat between two systematic values

Parameters:
  • lls (np.ndarray) – values of likelihoods

  • H0dim (int) – dimension of H0 in the data

  • H0values (float) – vector specifying values of H0

  • cmbH0 (float) – value of H0 from the CMB

  • cmb_sigma (float) – 1 sigma uncertainty on H0 from CMB

  • sn1aH0 (float) – value of H0 from SN1a (distance ladder) measurements

  • sn1a_sigma (float) – 1 sigma uncertainty on H0 from SN1A

Returns a vector of length lls modified by that prior.

zdm.analyze_cube.apply_F_prior(lls: ndarray, Fdim: int, Fvalues: ndarray, F_0: float, F_sigma: float)[source]

Applies a prior as a function of F

This is a Gaussian prior.

Parameters:
  • lls (np.ndarray) – values of likelihoods

  • Fdim (int) – dimension of F0 in the data

  • Fvalues (float) – vector specifying values of H0

  • F_0 (float) – value of F

  • F_sigma (float) – 1 sigma uncertainty on F

Returns a vector of length lls modified by that prior.

zdm.analyze_cube.get_slice_from_parameters(data, plist, mcvals, verbose=False, wanted='ll')[source]

Selects from data according to parameters which are as close to those in the mcvals as possible.

Parameters:
  • data – .npz structure generated by slurp_cube

  • plist (list of strings) – is a list of strings giving parameters

  • mcvals (list of floats) – is a float list of values one wants to approximate

  • verbose (bool) – toggle output level

  • wanted – which column from the data to extract

Returns:

Array of NDIM=dim(data)-dim(plist) likelihood values

zdm.analyze_cube.get_bayesian_data(lls: ndarray, plls: ndarray = None, pklfile=None)[source]

Method to perform simple Bayesian analysis on the Log-likelihood cube

Parameters:
  • lls (np.ndarray) – Log-likelood cube

  • plls (np.ndarray, optional) – Log-likelihood cube corrected for priors (e.g. alpha). Defaults to None.

  • pklfile (str, optional) – If given, write the output to this pickle file. Defaults to None.

Returns:

uvals,vectors,wvectors

lists of np.ndarray’s of LL analysis One item per parameter in the cube

Return type:

tuple

zdm.analyze_cube.get_2D_bayesian_data(lls: ndarray, plls: ndarray = None, pklfile=None)[source]

Method to perform simple Bayesian analysis on the Log-likelihood cube

Parameters:
  • lls (np.ndarray) – Log-likelood cube

  • plls (np.ndarray, optional) – Log-likelihood cube corrected for priors (e.g. alpha). Defaults to None.

  • pklfile (str, optional) – If given, write the output to this pickle file. Defaults to None.

Returns:

uvals,ijs,arrays,warrays,

uvals: values of each array, in form ijs: order of which parameters are combined in the arrays (e.g. [2,4]) arrays: lists of 2D np.ndarray’s of LL analysis warrays: weighted with prior on alpha ijs, arrays, and warrays have Nitems = Nparams*(Nparams-1)/2

Return type:

tuple

zdm.analyze_cube.get_maxl_data(lls: ndarray, plls: ndarray = None, pklfile=None)[source]

Method to perform simple Bayesian analysis on the Log-likelihood cube

Parameters:
  • lls (np.ndarray) – Log-likelood cube

  • plls (np.ndarray, optional) – Log-likelihood cube corrected for priors (e.g. alpha). Defaults to None.

  • pklfile (str, optional) – If given, write the output to this pickle file. Defaults to None.

Returns:

uvals,vectors,wvectors

lists of np.ndarray’s of LL analysis One item per parameter in the cube

Return type:

tuple

zdm.analyze_cube.get_2D_maxl_data(lls: ndarray, plls: ndarray = None, pklfile=None)[source]

Method to perform simple Bayesian analysis on the Log-likelihood cube

Parameters:
  • lls (np.ndarray) – Log-likelood cube

  • plls (np.ndarray, optional) – Log-likelihood cube corrected for priors (e.g. alpha). Defaults to None.

  • pklfile (str, optional) – If given, write the output to this pickle file. Defaults to None.

Returns:

uvals,ijs,arrays,warrays,

uvals: values of each array, in form ijs: order of which parameters are combined in the arrays (e.g. [2,4]) arrays: lists of 2D np.ndarray’s of LL analysis warrays: weighted with prior on alpha ijs, arrays, and warrays have Nitems = Nparams*(Nparams-1)/2

Return type:

tuple

zdm.analyze_cube.interpolate_points(oldx, oldy, logspline=False, kind='cubic')[source]

performs simle spline interpolation of the data :param oldx: np array of original data on x axis :param oldy: np array of original data on y axis :param logspline: perform interpolation in log space :type logspline: bool :param kind: type of spline to fit

Returns:

interpolated points

Return type:

x,y

zdm.analyze_cube.extract_limits(x, y, p, method=1, dumb=False, interp=False)[source]
Parameters:
  • x (np.ndarray) – xvalues of data (independent variable on which we place limits)

  • y (np.ndarray) – yvalues of data (probability distribution)

  • p – probability at each tail of the distribution (e.g. 0.16 for ~1 sigma, 0.025 for 2 sigma) Use “dumb = True” to interpet this as the C.I. (e.g. 0.68 for 1 sigma, 0.95 for 2 sigma)

  • p – probability of confidence interval (e.g. (1-0.68)/2 for ~1 sigma)

  • method – 1: includes most-likely points in C.I. first 2: sets equal probability to either side

  • interp – if True, interpolates between points

Returns:

lower and upper bounds of range

Return type:

v0,v1

zdm.analyze_cube.do_single_plots(uvals, vectors, wvectors, names, tag=None, fig_exten='.png', dolevels=False, log=True, outdir='SingleFigs/', vparams_dict=None, prefix='', truth=None, latexnames=None, units=None, logspline=True, others=None, compact=False, others_labels=None)[source]

Generate a series of 1D plots of the cube parameters

Parameters:
  • uvals (list) – List, each element containing a np.ndarray giving the parameter values for each parameter. Total length nparams.

  • vectors (list) – [For each parameter, contains an unweighted vector giving 1D probabilities for that value of the parameter]

  • wvectors ([list]) – [For each parameter, contains a weighted (with prior) vector giving 1D probabilities for that value of the parameter]

  • names ([type]) – [description]

  • tag ([type], optional) – [description]. Defaults to None.

  • fig_exten (str, optional) – [description]. Defaults to ‘.png’.

  • dolevels (bool, optional) – [description]. Defaults to False.

  • log (bool, optional) – [description]. Defaults to True.

  • outdir (str, optional) – [description]. Defaults to ‘SingleFigs/’.

  • vparams_dict (dict, optional) – parameter dict – used to set x-values. Defaults to None.

  • prefix (str, optional) – [description]. Defaults to ‘’.

  • latexnames – latex of axis names

  • units – latex of units to attach to x-axis only

  • logspline (bool) – do spline fitting in logspace?

  • others (list of arrays) – list of other plots to add to data

  • compact

    ???

  • others_labels (list of strings) – labels for others

zdm.analyze_cube.make_1d_plots_by_contribution(data, contributions, labels, prefix='', fig_exten='.png', log=False, splines=True, latexnames=None, units=None, linestyles=None, colors=None)[source]

contributions: list of vectors giving various likelihood terms :param splines: draw cubic splines :type splines: bool :param Labels: lists labels stating what these are :param latexnames: latex for x and p(X) :param units: appends units to x axis but not p(X)

zdm.analyze_cube.gen_vparams(indices: tuple, vparam_dict: dict)[source]
zdm.analyze_cube.make_2d_plot(array, xlabel, ylabel, xvals, yvals, savename=None, norm=None)[source]

Makes 2D plot given an array of probabilities

array: 2D grid of data to plot

xlabel: string to label on x axis ylabel: string to label y axis

xvals: np array, values of x data yvals: np array, values of y data

savename (optional): string to save data under

Functions

apply_F_prior(lls, Fdim, Fvalues, F_0, F_sigma)

Applies a prior as a function of F

apply_H0_prior(lls, H0dim, H0values, cmbH0, ...)

Applies a prior as a function of H0

apply_gaussian_prior(lls, iparam, values, ...)

Applies a prior to parameter iparam with mean mean and deviation sigma.

do_single_plots(uvals, vectors, wvectors, names)

Generate a series of 1D plots of the cube parameters

embed(*[, header, compile_flags])

Call this to embed IPython at the current point in your program.

extract_limits(x, y, p[, method, dumb, interp])

gen_vparams(indices, vparam_dict)

get_2D_bayesian_data(lls[, plls, pklfile])

Method to perform simple Bayesian analysis on the Log-likelihood cube

get_2D_maxl_data(lls[, plls, pklfile])

Method to perform simple Bayesian analysis on the Log-likelihood cube

get_bayesian_data(lls[, plls, pklfile])

Method to perform simple Bayesian analysis on the Log-likelihood cube

get_maxl_data(lls[, plls, pklfile])

Method to perform simple Bayesian analysis on the Log-likelihood cube

get_slice_from_parameters(data, plist, mcvals)

Selects from data according to parameters which are as close to those in the mcvals as possible.

interpolate_points(oldx, oldy[, logspline, kind])

performs simle spline interpolation of the data :param oldx: np array of original data on x axis :param oldy: np array of original data on y axis :param logspline: perform interpolation in log space :type logspline: bool :param kind: type of spline to fit

make_1d_plots_by_contribution(data, ...[, ...])

contributions: list of vectors giving various likelihood terms :param splines: draw cubic splines :type splines: bool :param Labels: lists labels stating what these are :param latexnames: latex for x and p(X) :param units: appends units to x axis but not p(X)

make_2d_plot(array, xlabel, ylabel, xvals, yvals)

Makes 2D plot given an array of probabilities

slurp_cube(input_file, prefix, outfile, nsurveys)

Slurp the cube ASCII output files and write lC and ll into a numpy savez file

vvmax

V/Vmax statistical tests for FRB population analysis.

zdm.vvmax Module

This file contains routines generally associated with V/Vmax calculations.

They were originally developed for the “VVmax” paper (Arcus et al).

Specific features unique to that paper can be found in the /papers/Vvmax subdirectory.

zdm.vvmax.get_vvmax(BeamBs, BeamOs, Bfrb, sfrb, z0, DM0, DMcosmic0, w0, freqMHz, tsamp, macquartz, macquartDM, alpha, Vsplines, LimZ)[source]

Calculates the values of V and Vmax [Mpc^3 dtau] for the given inputs

INPUTS:

BeamBs [np.ndarray (floats)]: list of relative beam values B BeamOs [np.ndarray (floats)]: list of solid angles for B Bfrb [float]: value of B at which the FRB is detected sfrb [float]: value of s=SNR/SNRth at which the FRB is detected z0 [float]: measured FRB redshift DM0 [float]: measured FRB total dispersion measures [pc cm^-3] DMcosmic0: estimated FRB cosmic dispersion measures [pc cm^-3] w0 [float]: measured FRB width [ms] freqMHz [float]: frequency of detection [MHz] tsamp [float]: integration time of data [ms] Macquartz [float]: redshift estimated from the Macquart relation MacquartDM [float]: cosmic dispersion measure estimated from the Macquart relation alpha [float]: frequency dependence of FRBs - Fnu ~ nu^lpha Vsplines [cubic spline interpolation]: precalcuated cubic spline interpolation

of volume as a function of redshift (for speed!)

LimZ [None or float]: maximum redshift for V/Vmax calculations

zdm.vvmax.calc_zmax(s0, z0, DM0, DMcosmic0, w0, freq, tsamp, Macquartz, MacquartDM, alpha)[source]

Routine which calculates the maximum redshift at which an FRB could have been detected.

We begin with the ratio s0, which is SNR(det)/SNR(thresh) This tells us how much fluence we can lose as a function of redshift

We then account for luminosity distance, and changing efficiency with distance

‘0’ properties indicate those at detection

Macquartz and MacquartDM are pre-computed values of Macquart relation

We must have values of z which span the range from the minimum z at which the FRB lies, to the maximum z at which it could be detected E.g. at S/N of 1000, that’s a factor of ~10 for SNRthresh=10

INPUTS:

s0 [float]: measured SNR/SNRthresh of detected FRB z0 [float]: measured FRB redshift DM0 [float]: measured FRB total dispersion measures [pc cm^-3] DMcosmic0: estimated FRB cosmic dispersion measures [pc cm^-3] w0 [float]: measured FRB width [ms] freq [float]: frequency of detection [MHz] tsamp [float]: integration time of data [ms] Macquartz [float]: redshift estimated from the Macquart relation MacquartDM [float]: cosmic dispersion measure estimated from the Macquart relation alpha [float]: frequency dependence of FRBs - Fnu ~ nu^lpha

Returns:

maximum redshift that the FRB could have been detected at

zdm.vvmax.zefficiency(z0, w0, DM0, freq, tsamp, newz, newDM)[source]

Calculates width if the burst had been at a higher redshift Returns efficiency: propto w**-0.5 This modifies detectable fluence.

The new DM and z must be input by the user.

This is a similar model to that within the “survey” class.

INPUTS:

z0 [float]: measured FRB redshift w0 [float]: measured FRB width [ms] DM0 [float]: measured FRB total dispersion measures [pc cm^-3] freq [float]: frequency of detection [MHz] tsamp [float]: integration time of data [ms] newz [float]: redshift at which to calculate burst properties newDM [float]: DM at which to calculate burst properties

zdm.vvmax.calc_effz(s0, DMcosmic0, z0, w0, DM0, freq, tsamp, alpha, ztrials, DMcosmicz)[source]

calculates s=SNR/SNRth that an FRB would have as a function of redshift

Includes luminosity distance and efficiency factors.

INPUTS:

s0 [float]: measured SNR/SNRthresh of detected FRB DMcosmic0: estimated FRB cosmic dispersion measures [pc cm^-3] z0 [float]: measured FRB redshift w0 [float]: measured FRB width [ms] DM0 [float]: measured FRB total dispersion measures [pc cm^-3] freq [float]: frequency of detection [MHz] tsamp [float]: integration time of data [ms] ztrials [np.ndarray (floats)]: array of redshifts at which to calculate s alpha [float]: frequency dependence of FRBs - Fnu ~ nu^lpha

Returns:

s as a function of ztrials eff0 [float]: efficiency at detected redshift effz [np.ndarray (float)]: efficiency as a function of ztrials modFz: fluence as a function of redshift

Return type:

sz

zdm.vvmax.get_macquart_z(DMeg, state, DMhost, zmin=0.001, zmax=2, NZ=2000)[source]

gets z(DM) from the Macquart relation

INPUTS:
DMeg [float or np.ndarray]: extragalactic DM at which

to calculate z [pc/cm3]

state [instance of parameter state class] DMhost: assumed value of DM host zmin [int]: minimum redshift for interpolation zmax [int]: maximum redshift for interpolation NZ [int]: number of redshifts for interpolation

Returns:

Macquart relation expectation for

redshift of FRBs with DMeg

Return type:

zFRBs (float or np.ndarray)

zdm.vvmax.get_DM_cosmic(z, state)[source]

gets z(DM) from the Macquart relation

Functions

calc_effz(s0, DMcosmic0, z0, w0, DM0, freq, ...)

calculates s=SNR/SNRth that an FRB would have as a function of redshift

calc_zmax(s0, z0, DM0, DMcosmic0, w0, freq, ...)

Routine which calculates the maximum redshift at which an FRB could have been detected.

get_DM_cosmic(z, state)

gets z(DM) from the Macquart relation

get_macquart_z(DMeg, state, DMhost[, zmin, ...])

gets z(DM) from the Macquart relation

get_vvmax(BeamBs, BeamOs, Bfrb, sfrb, z0, ...)

Calculates the values of V and Vmax [Mpc^3 dtau] for the given inputs

zefficiency(z0, w0, DM0, freq, tsamp, newz, ...)

Calculates width if the burst had been at a higher redshift Returns efficiency: propto w**-0.5 This modifies detectable fluence.

Data Classes

Base classes and data structures.

data_class

Base dataclass utilities for parameter management. Provides common functionality for serialization, dictionary access, and parameter metadata handling used by all parameter dataclasses.

zdm.data_class Module

Base dataclass utilities for parameter management.

This module provides base classes used by the parameter dataclasses in the zdm package. These provide common functionality for serialization, dictionary access, and parameter metadata handling.

Classes

myDataClass

Base class for parameter dataclasses with metadata access methods.

myData

Base class for composite data objects containing multiple dataclasses.

class zdm.data_class.myDataClass[source]
property fields
meta(attribute_name)[source]
chk_options(attribute_name)[source]
__init__() None
class zdm.data_class.myData[source]
__init__()[source]
classmethod from_dict(param_dict: dict)[source]
classmethod from_jsonfile(jfile: str)[source]

Load from a JSON file

Parameters:

jfile (str) – name of the JSON file

Return type:

myDataClass

classmethod from_jsonstr(jsonstr: str)[source]
set_dataclasses()[source]
set_params()[source]

Generate a simple dict for parameters

__getitem__(attrib: str)[source]

Enables dict like access to the state

Parameters:

attrib (str) – name of the attribute

Returns:

Value of the attribute requested

Return type:

?

update_param_dict(params: dict)[source]
update_params(params: dict)[source]

Update the state parameters using the input dict

Parameters:

params (dict) – New parameters+values

update_param(param: str, value)[source]

Update the value of a single parameter

Parameters:
  • param (str) – name of the parameter

  • value – value

to_dict()[source]

Generate a dict holding all of the object parameters

Returns:

[description]

Return type:

dict

write(outfile: str)[source]

Write the parameters to a JSON file

Parameters:

outfile (str) – name of output file

vet(obj, dmodel: dict, verbose=True)[source]

Vet the input object against its data model

Parameters:
  • obj (dict or pandas.DataFrame) – Instance of the data model

  • dmodel (dict) – Data model

  • verbose (bool) – Print when something doesn’t check

Returns:

chk (bool), disallowed_keys (list), badtype_keys (list)

Return type:

tuple

Classes

myData()

myDataClass()

survey_data

Data structures for survey metadata and FRB observations.

zdm.survey_data Module

Survey data

class zdm.survey_data.FRB(BW: float = 0.0, DM: float = 0.0, DMG: float = 0.0, FBAR: float = 0.0, FRES: float = 1.0, Gb: float = None, Gl: float = None, RA: float = None, DEC: float = None, NREP: numpy.int64 = 1, SNR: float = 0.0, SNRTHRESH: float = 10.0, THRESH: float = 1.0, TNS: str = '', TRES: float = 0.0, WIDTH: float = -1, TAU: float = -1.0, Z: float = -1.0, B: float = -1.0)[source]
BW: float = 0.0
DM: float = 0.0
DMG: float = 0.0
FBAR: float = 0.0
FRES: float = 1.0
Gb: float = None
Gl: float = None
RA: float = None
DEC: float = None
NREP: int64 = 1
SNR: float = 0.0
SNRTHRESH: float = 10.0
THRESH: float = 1.0
TNS: str = ''
TRES: float = 0.0
WIDTH: float = -1
TAU: float = -1.0
Z: float = -1.0
B: float = -1.0
__init__(BW: float = 0.0, DM: float = 0.0, DMG: float = 0.0, FBAR: float = 0.0, FRES: float = 1.0, Gb: float = None, Gl: float = None, RA: float = None, DEC: float = None, NREP: int64 = 1, SNR: float = 0.0, SNRTHRESH: float = 10.0, THRESH: float = 1.0, TNS: str = '', TRES: float = 0.0, WIDTH: float = -1, TAU: float = -1.0, Z: float = -1.0, B: float = -1.0) None
class zdm.survey_data.Telescope(BEAM: str = '', BW: float = 336.0, DIAM: float = 0.0, DMG: float = 30.0, NBEAMS: int = 1, NBINS: int = 5, WDATA: int = 2, WBIAS: str = 'StdDev', DMMASK: str = None, BMETHOD: int = 2, DRIFT_SCAN: int = 1, BTHRESH: float = 0.001, THRESH: float = 1.0, SNRTHRESH: float = 10.0, FBAR: float = 1300.0, FRES: float = 1.0, TRES: float = 1.26, WIDTH: float = 0.1)[source]
BEAM: str = ''
BW: float = 336.0
DIAM: float = 0.0
DMG: float = 30.0
NBEAMS: int = 1
NBINS: int = 5
WDATA: int = 2
WBIAS: str = 'StdDev'
DMMASK: str = None
BMETHOD: int = 2
DRIFT_SCAN: int = 1
BTHRESH: float = 0.001
THRESH: float = 1.0
SNRTHRESH: float = 10.0
FBAR: float = 1300.0
FRES: float = 1.0
TRES: float = 1.26
WIDTH: float = 0.1
__init__(BEAM: str = '', BW: float = 336.0, DIAM: float = 0.0, DMG: float = 30.0, NBEAMS: int = 1, NBINS: int = 5, WDATA: int = 2, WBIAS: str = 'StdDev', DMMASK: str = None, BMETHOD: int = 2, DRIFT_SCAN: int = 1, BTHRESH: float = 0.001, THRESH: float = 1.0, SNRTHRESH: float = 10.0, FBAR: float = 1300.0, FRES: float = 1.0, TRES: float = 1.26, WIDTH: float = 0.1) None
class zdm.survey_data.Observing(NORM_FRB: int = 0, NORM_REPS: int = None, NORM_SINGLES: int = None, TOBS: float = None, TFIELD: float = None, NFIELDS: int = None, MAX_DM: float = None, MAX_IDT: int = None, MAX_IW: int = None, MAXWMETH: int = 0, MAX_LOC_DMEG: int = -1)[source]
NORM_FRB: int = 0
NORM_REPS: int = None
NORM_SINGLES: int = None
TOBS: float = None
TFIELD: float = None
NFIELDS: int = None
MAX_DM: float = None
MAX_IDT: int = None
MAX_IW: int = None
MAXWMETH: int = 0
MAX_LOC_DMEG: int = -1
__init__(NORM_FRB: int = 0, NORM_REPS: int = None, NORM_SINGLES: int = None, TOBS: float = None, TFIELD: float = None, NFIELDS: int = None, MAX_DM: float = None, MAX_IDT: int = None, MAX_IW: int = None, MAXWMETH: int = 0, MAX_LOC_DMEG: int = -1) None
class zdm.survey_data.SurveyData[source]

Hold the SurveyData in a convenient object

set_dataclasses()[source]

Classes

FRB([BW, DM, DMG, FBAR, FRES, Gb, Gl, RA, ...])

Observing([NORM_FRB, NORM_REPS, ...])

SurveyData()

Hold the SurveyData in a convenient object

Telescope([BEAM, BW, DIAM, DMG, NBEAMS, ...])

Specialized Modules

Additional modules for specific use cases.

galactic_dm_models

Models for Galactic DM contributions including different halo models.

zdm.galactic_dm_models Module

zdm.galactic_dm_models.dmg_sanskriti2020(l_FRB, b_FRB, sep_th=5, sep_tol=5, verb=False)[source]

Functions

dmg_sanskriti2020(l_FRB, b_FRB[, sep_th, ...])

optical

Optical counterpart and host galaxy association utilities.

zdm.optical Module

This library contains routines that interact with the FRB/astropath module and (optical) FRB host galaxy information.

It includes the class “host_model” for describing the intrinsic FRB host galaxy distribution, associated functions, and the approximate fraction of detectable FRBs from Marnoch et al (https://doi.org/10.1093/mnras/stad2353)

class zdm.optical.host_model(opstate=None, verbose=False)[source]

A class to hold information about the intrinsic properties of FRB host galaxies. Eventually, this should be expanded to be a meta-class with different internal models. But for now, it’s just a simple one

Ingredients are:
A model for describing the intrinsic distribution

of host galaxies. This model must be described by some set of parameters, and be able to return a prior as a function of intrinsic host galaxy magnitude. This model is initialised via opstate.AbsModelID

A model for converting absolute to apparent host magnitudes.

This is by defult an apparent r-band magnitude, though in theory a user can work in whatever band they wish.

Internally, this class initialises:

An array of absolute magnitudes, which get weighted according to the host model. Internal variables associated with this are prefaced “Model”

An array of apparent magnitudes, which is used to compare with host galaxy candidates Internal variables associated with this are prefaced “App”

Arrays mapping intrinsic to absolute magnitude as a function of redshift, to allow quick estimation of p(apparent_mag | DM) for a given FRB survey with many FRBs Internal variables associated with this are prefaced “Abs”

Note that while this class describes the intrinsic “magnitudes”, really magnitude here is a proxy for whatever parameter is used to intrinsically describe FRBs. However, only 1D descriptions are currently implemented. Future descriptions will include redshift evolution, and 2D descriptions (e.g. mass, SFR) at any given redshift.

__init__(opstate=None, verbose=False)[source]

Class constructor

Parameters:
  • (class (opstate) – Hosts, optional): class defining parameters of optical state model

  • verbose (bool, optional) – to be verbose y/n

init_abs_prior()[source]

Initialises prior on absolute magnitude of galaxies according to the method.

init_app_bins()[source]

Initialises bins in apparent magnitude It uses these to calculate priors for any given host galaxy magnitude. This is a very simple set of uniformly log-spaced bins in magnitude space, and linear interpolation is used between them.

init_abs_bins()[source]

Initialises internal array of absolute magnitudes This is a simple set of uniformly log-spaced bins in terms of absolute magnitude, which the absolute magnitude model gets projected onto

init_model_bins()[source]

Initialises bins for the simple model of an absolute magnitude prior. This is much sparser than the app or abs bins, since these model bins correspond to parameters which may get adjusted by e.g. an MCMC

The base unit here is assumed to be absolute r-band magnitude M, but in principle this works for whatever absolute unit is being used by the model.

init_zmapping(zvals)[source]

For a set of redshifts, initialise mapping between intrinsic magnitudes and apparent magnitudes

This routine only needs to be called once, since the model to convert absolute to apparent magnitudes is fixed

It is not set automatically however, and needs to be called with a set of z values. This is all for speedup purposes.

Parameters:

zvals (np.ndarray, float) – array of redshifts over which to map absolute to apparent magnitudes.

init_maghist()[source]

Initialises the array mapping redshifts and absolute magnitudes to redshift and apparent magnitude

Calculates the internal maghist array, of size self.NAppBins X self.NZ

No return value.

reinit_model()[source]

Re-initialises all internal info which depends on the optical param model. It assumes that the changes have been implemented in self.AbsPrior

init_abs_mag_weights()[source]

Assigns a weight to each of the absolute magnitudes in the internal array (which generally is very large) in terms of the absolute magnitude parameterisation (generally, only a few parameters)

estimate_unseen_prior(mag_limit)[source]

Calculates PU, the prior that an FRB host galaxy of a particular DM is unseen in the optical image

This requires initialisation of init_path_raw_prior_Oi

NOTE: The total normalisation of priors in the magnitude range

may be less than unity. This is because some probability may fall outside of the magnitude range being examined. Hence, the correct normalisation is found by summing the visible magnitudes, and subtracting them from unity.

Parameters:

mag_limit (float) – maximum observable magnitude of host galaxies

Returns:

probability PU of true hist being unseen in the optical

image.

Return type:

PU (float)

path_raw_prior_Oi(mags, ang_sizes, Sigma_ms)[source]

Function to pass to astropath module for calculating a raw FRB prior.

NOTE: as of all recent PATH iterations, the galaxy angular

size should NOT be included in the calculation, since this gets integrated over in estimating the offset error. Nonetheless, this function must accept an ang_size argument.

NOTE2: Before using this function, the call “init_path_raw_prior_Oi”

must be called. This is because the full prior requires a zDM grid and an FRB DM, yet this cannot be passed to raw_prior_Oi within PATH.

Parameters:
  • mags (tuple, float) – host galaxy r-band magnitudes

  • ang_sizes (tuple, float) – host galaxy angular sizes (arcsec I believe)

  • Sigma_ms (tuple, float) – galaxy densities on the sky

Returns:

priors on host galaxy magnitdues mags

Return type:

Ois (tuple)

init_path_raw_prior_Oi(DM, grid)[source]

Initialises the priors for a particlar DM. This performs a function very similar to “get_posterior” except that it expicitly only operates on a single DM, and saves the information internally so that path_raw_prior_Oi can be called for numerous host galaxy candidates.

It returns the priors distribution.

Parameters:
  • [float] (DM) – dispersion measure of an FRB (pc cm-3)

  • grid (class grid) – initialised grid object from which to calculate priors

Returns:

vector of priors on host galaxy apparent magnitude

Return type:

priors (float)

calc_magnitude_priors(zlist: ndarray, pzlist: ndarray)[source]

Calculates priors as a function of magnitude for a given redshift distribution.

Parameters:
  • zlist (np.ndarray, float) – array of redshifts

  • pz (np.ndarray, float) – array of probabilities of the FRB occurring at each of those redshifts

# returns probability-weighted magnitude distribution, as a function of # self.AppBins

get_posterior(grid, DM)[source]

Returns posterior redshift distributiuon for a given grid, and DM magnitude distribution, for FRBs of DM given a grid object. Note: this calculates a prior for PATH, but is a posterior

from zDM’s point of view.

Parameters:
  • grid (class grid object) – grid object defining p(z,DM)

  • DM (float, np.ndarray OR scalar) – FRB DM(s)

Returns:

probability distribution of apparent magnitudes given DM pz (np.ndarray, floats): probability distribution of redshift given DM

Return type:

papps (np.ndarray, floats)

zdm.optical.get_pz_prior(grid, DM)[source]

Returns posterior redshift distributiuon for a given grid and DM magnitude distribution for FRBs of DM given a grid object

Parameters:
  • grid (class grid object) – grid object modelling p(z,DM)

  • DM (float or np.ndarray of floats) – FRB dispersion measure, pc cm^-3

Returns:

probability distribution in redshift space

Return type:

pz (np.ndarray)

zdm.optical.SimpleApparentMags(Abs, zs)[source]

Function to convert galaxy absolue to apparent magnitudes.

Nominally, magnitudes are r-band magnitudes, but this function is so simple it doesn’t matter.

Just applies a distance correction - no k-correction.

Parameters:
  • Abs (float or array of floats) – intrinsic galaxy luminosities

  • zs (float or array of floats) – redshifts of galaxies

Returns:

NAbs x NZ array of magnitudes, where these

are the dimensions of the inputs

Return type:

ApparentMags

zdm.optical.p_unseen_Marnoch(zvals, plot=False)[source]

Returns probability of a hist being unseen in typical VLT observations.

Inputs:

zvals [float, array]: array of redshifts

Returns:

p(Unseen) for redshift zvals

Return type:

fitv [float, array]

zdm.optical.simplify_name(TNSname)[source]

Simplifies an FRB name to basics

zdm.optical.matchFRB(TNSname, survey)[source]

Gets the FRB id from the survey list Returns None if not in the survey Used to match properties between a survey and other FRB libraries

zdm.optical.run_path(name, model, PU=0.1, usemodel=False, sort=False)[source]

evaluates PATH on an FRB

absolute [bool]: if True, treats rel_error as an absolute value

in arcseconds

zdm.optical.plot_frb(name, ralist, declist, plist, opfile)[source]

does an frb

absolute [bool]: if True, treats rel_error as an absolute value

in arcseconds

clist: list of astropy coordinates plist: list of p(O|x) for candidates hosts

zdm.optical.load_marnoch_data()[source]

Loads the Marnoch et al data on r-band magnitudes from FRB hosts

Functions

SimpleApparentMags(Abs, zs)

Function to convert galaxy absolue to apparent magnitudes.

get_pz_prior(grid, DM)

Returns posterior redshift distributiuon for a given grid and DM magnitude distribution for FRBs of DM given a grid object

load_marnoch_data()

Loads the Marnoch et al data on r-band magnitudes from FRB hosts

matchFRB(TNSname, survey)

Gets the FRB id from the survey list Returns None if not in the survey Used to match properties between a survey and other FRB libraries

p_unseen_Marnoch(zvals[, plot])

Returns probability of a hist being unseen in typical VLT observations.

plot_frb(name, ralist, declist, plist, opfile)

does an frb

run_path(name, model[, PU, usemodel, sort])

evaluates PATH on an FRB

simplify_name(TNSname)

Simplifies an FRB name to basics

Classes

CubicSpline(x, y[, axis, bc_type, extrapolate])

Piecewise cubic interpolator to fit values (C2 smooth).

host_model([opstate, verbose])

A class to hold information about the intrinsic properties of FRB host galaxies.

io

Input/output utilities for file handling including JSON I/O and grid data persistence.

zdm.io Module

Input/output utilities for the zdm package.

This module provides helper functions for file I/O operations including JSON file handling and grid data persistence.

Functions

  • process_jfile: Load a JSON file

  • savejson: Save a Python object to JSON

  • save_grid: Save grid data to compressed file

  • load_grid: Load grid data from compressed file

zdm.io.process_jfile(jfile: str)[source]

Load up a JSON file

Parameters:

jfile (str) – JSON file

Returns:

JSON parsed

Return type:

dict

zdm.io.savejson(filename, obj, overwrite=False, indent=None, easy_to_read=False, **kwargs)[source]

Save a python object to filename using the JSON encoder. :param filename: :type filename: str :param obj: Frequently a dict :type obj: object :param overwrite: :type overwrite: bool, optional :param indent: Input to json.dump :type indent: int, optional :param easy_to_read: Another approach and obj must be a dict :type easy_to_read: bool, optional :param kwargs: Passed to json.dump :type kwargs: optional

zdm.io.load_data(filename)[source]

Functions

load_data(filename)

process_jfile(jfile)

Load up a JSON file

savejson(filename, obj[, overwrite, indent, ...])

Save a python object to filename using the JSON encoder.