enterprise_warp API

Below is a more detailed information about different modules of enterprise_warp.


enterprise_warp

This is the main module that allows to load parameter file, noise model files, python noise model functions and possible noise files for fixed white noise parameters into Enterprise.

The main module for running enterprise_warp: - Reads command line arguments, parameter files (.dat). - Based on the input, creates a enterprise.PTA object, with methods to compute likelihoods and priors.

class enterprise_warp.enterprise_warp.ModelParams(model_id)[source]

A simple template for a new class. Used as a nested enterprise_warp.Params class for multiple model parameters within ont enterprise_warp.Params class. It is used with product-space sampling method and ptmcmcsampler, which evaluate posterior odds ratios (Bayes factors) for a given number of compared models.

Parameters

model_id: int

Index of a model

class enterprise_warp.enterprise_warp.Params(input_file_name, opts=None, custom_models_obj=None, init_pulsars=True)[source]

Load parameters with instructions for how to run Enterprise.

Parameters

input_file_name: str

Path to enterprise_warp parameter file.

opts: optparse.OptionParser

The output of enterprise_warp.parse_commandline()

custom_models_obj: enterprise_models.EnterpriseModels or a child class

A class of enterprise_warp models to use later on (not initialized)

init_pulsars: bool

Initiate enterprise pulsars (use True by default)

init_pulsars()[source]

Initiate Enterprise or Discovery pulsar objects.

override_params_using_opts()[source]

If opts from command line parser has a non-None parameter argument, override this parameter for all models.

read_modeldicts()[source]

Reading general noise model (which will overwrite model-specific ones, if they exists).

selection_pulsars(psr_strings)[source]

psr_strings: list of pulsar names or paths with pulsar names

set_default_params()[source]

Setting some default parameters here

enterprise_warp.enterprise_warp.dict_to_label_attr_map(input_dict)[source]

Converting python dict with one value into Params.label_attr_map format

enterprise_warp.enterprise_warp.get_pta_package(filename)[source]

Extracting pta_package from parameter name ahead of the rest

enterprise_warp.enterprise_warp.init_pta_enterprise(params_all)[source]

Initiate enterprise signal models and enterprise.signals.signal_base.PTA.

enterprise_warp.enterprise_warp.load_to_dict(filename)[source]

Load file to Python dictionary

enterprise_warp.enterprise_warp.merge_two_noise_model_dicts(dict1, dict2)[source]

Merging dict2 into dict1 given the noise model dict format: {‘PSR_name’: {‘noise_term’: parameter}}, parameter is either a string or a list of strings.

enterprise_warp.enterprise_warp.parse_commandline()[source]

Parse the command-line options.

Most important options:

  • --prfile: parameter file, the only option that must be set.

  • --num: index of a pulsar in a data directory (default: 0).

See other options and their description in the code.

Returns

opts: optparse.OptionParser

Command line arguments to be used later in the code.

enterprise_warp.enterprise_warp.psrname_from_filename(filename)[source]

This function splits a strong based on symbols: “.”, “/”, “_”. Thus, it converts any of the strings below: 1. /path/0_J0437-4715.par 2. /path/J0437-4715.tim 3. J0437-4715 Into pulsar name: J0437-4715

enterprise_warp.enterprise_warp.read_tim(tim_file_name, column=1)[source]

Returning column elements for all lines of .tim files (except commented) Column 1 is a file name. For example: t180327_095957.rf.pcm.dzTf8p. It is used to see what ToAs are from the same subband.


enterprise_models

This module contains basic models for pulsar timing analyses and serves as a base class for custom noise models. Timing model is set up in enterprise_warp.py.

Documentation for enterprise_warp.models. Here, EnterpriseModels has a set of methods which return enterprise signal objects. Names of the class methods are keys in .json noise model files, and method kwargs “option” must be a dict with values from .json noise model files. The class is used under the hood, unless the user choses to use their custom models. For custom models, it is recommended to create a child class of CustomModels, with additional methods, and then pass it to Params:

>>> custom = my_models.My_CustomModels
>>> params = enterprise_warp.Params(opts.prfile,opts=opts,custom_models_obj=custom)
>>> pta = enterprise_warp.init_pta(params)

Examples of how to add signal and noise term to .json noise model files:

“measurement_noise”: {

“selection”: “no_selection”

}

Here, value “no_selection” is the name of the function in enterprise.selection or this Python file (globals()).

“spin_noise”: {

“psd”: “powerlaw”, # enterprise.gp_priors or “n_freqs”: 30 # n_days: 240

}

Here, “powerlaw” is function name from enterprise.gp_priors or this Python file (globals()). E.g., gp_priors has functions powerlaw, free_spectrum, whereas this file has a function powerlaw_bpl (see below).

“system_noise”: {

“psd”: “powerlaw”, # enterprise.gp_priors or “n_freqs”: 30 # n_days: 240 “flags_flagvals”: {

“group”: []

}

}

“global_gp”: {

“psd”: “powerlaw”, “n_freqs”: 30, # n_days: 240 “orf”: “hd_orf”, “parameters”: {

“log10_A”: -15.0, “gamma”: 4.33

}

}

Here, “orf” value is a function name from enterprise.utils (hd_orf, monopole_orf, dipole_orf) or this Python file (globals()).

class enterprise_warp.enterprise_models.EnterpriseModels(psr=None, params=None)[source]

Standard models for pulsar timing analyses.

Single-pulsar signals include white noise (efac, equad, ecorr), spin noise, DM noise, band noise, system noise, chromatic noise. Common signals include errors in Solar System ephemerides and gravitational-wave background with Hellings-Downs spatial correlations.

Custom models should be derived from this class. See /examples.

Parameters

psr: enterprise.pulsar.Pulsar

Enterprise Pulsar object, where custom atrributes are written for band noise and system noise because enterprise.selections function have access to Pulsar object attributes to select certain parts of data.

For common signals between multiple pulsars this parameter is not needed and can remain as “None”.

params: enterprise_warp.Params

Parameter object, where default prior distribution parameters are added from self.priors if not specified in a parameter file (–prfile …)

Attributes

psr: enterprise.pulsar.Pulsar

Enterprise Pulsar object

params: enterprise_warp.Params

Parameter object

priors: dict

Dictionary with keys being prior probability parameters for models or some model-specific settings, described in the current model object (if not hard-coded). Dictionary values serve as default parameters and as parameter format for input from parameter files.

sys_noise_count: int

Internal variable that counts how many times we created a new selection function for band noise, system noise, or any other noise with multiple terms for different segments of the data.

bayes_ephem(option={})[source]

Deterministic signal from errors in Solar System ephemerides.

chromred(option={})[source]

This is an generalization of DM noise, with the dependence of Fourier amplitudes on radio frequency nu as ~ 1/nu^chi, where chi is a free parameter.

Examples of chi:

  • Pulse scattering in the ISM: chi = 4 (Lyne A., Graham-Smith F., 2012, Pulsar astronomy)

  • Refractive propagation: chi = 6.4 (Shannon, R. M., and J. M. Cordes. MNRAS, 464.2 (2017): 2075-2089).

common_gp(option={})[source]

Common-spectrum red process (common red noise) More information: https://doi.org/10.3847/2041-8213/ac17f4

determine_nfreqs(sel_func_name=None, cadence=60, common_signal=False)[source]

Determine whether to model red noise process with a fixed number of Fourier frequencies or whether to choose a number frequencies between the inverse of observation time and cadence (default 60) days.

Parameters

sel_func_name: str

Name of the selection function, stored in the current noise model object. It is needed to determine the observation span for a selected data (which is equal or smaller than the total observation span). If None, then enterprise.signals.selections.no_selection is assumed.

cadence: float

Period of highest-frequency component modelled (days)

common_signal: bool

True if determining a baseline observation span for a whole pulsar timing array with several pulsars.

determine_tspan(sel_func_name=None, common_signal=False)[source]

Determine the time span of TOAs under a given selection

Parameters

sel_func_name: str

Name of the selection function, stored in the current noise model object. It is needed to determine the observation span for a selected data (which is equal or smaller than the total observation span). If None, then enterprise.signals.selections.no_selection is assumed.

common_signal: bool

True if determining a baseline observation span for a whole pulsar timing array with several pulsars.

dm_noise(option={})[source]

A term to account for stochastic variations in DM. It is based on spin noise model, with Fourier amplitudes depending on radio frequency nu as ~ 1/nu^2.

ecorr(option={})[source]

Similar to EFAC and EQUAD, ECORR is a white noise parameter that describes a correlation between ToAs in a single epoch (observation).

Arzoumanian, Zaven, et al. The Astrophysical Journal 859.1 (2018): 47.

efac(option={})[source]

EFAC signal: multiplies ToA variance by EFAC**2, where ToA variance are diagonal components of the Likelihood covariance matrix.

equad(option={})[source]

EQUAD signal: adds EQUAD**2 to the ToA variance, where ToA variance are diagonal components of the Likelihood covariance matrix. TempoNest format: sigma**2 = EFAC**2 * toaerr**2 + EQUAD**2

get_label_attr_map()[source]

Convert self.priors dict to enterprise_warp.Params.label_attr_map dict

global_gp(option={})[source]

Gaussian process with inter-pulsar correlations (e.g., Hellings-Downs)

global_gp_2(option={})[source]

A second global_gp, in case two need to be added.

global_gp_3(option={})[source]

A third global_gp, in case three need to be added.

measurement_noise(option={})[source]

EFAC + EQUAD in tempo2 format: sigma**2 = EFAC**2 * (toaerr**2 + EQUAD**2)

option format: {

“selection”: “by_backend”

}

option_nfreqs(option, sel_func_name=None, selection_flag=None, selection_flagval=None)[source]

Selecting and removing nfreqs from option, otherwise from 1/Tobs to 1/60days

save_nfreqs_information(sel_func_name, n_freqs)[source]

Enterprise does not store a number of Fourier frequencies for red noise processes. This function stores this information in the output folder.

Parameters

sel_func_name: str

Selection function name (None for no selection)

n_freqs: int

Number of Fourier frequencies of a red noise process

spin_noise(option={})[source]

Achromatic red noise process is called spin noise, although generally this model is used to model any unknown red noise. If this model is preferred over chromatic models then the observed noise is really spin noise, associated with pulsar rotational irregularities.

system_noise(option={})[source]

Including red noise terms by “-group” flag, only with flagvals in noise model file.

See Lentati, Lindley, et al. MNRAS 458.2 (2016): 2161-2187.

enterprise_warp.enterprise_models.get_enterprise_function(option, key, kwargs, module, custom_models={})[source]

Returns enterprise @signal_base function with set up priors, passing only those priors from kwargs which are relevant for this function. The function is collected from: 1. This module (enterprise_warp/enteprirse_models.py) 2. A relevant imported enterprise module (arg module) 3. Custom models globals(), if applicable (kwarg custom_models)

Arguments: option: dict, the standard kwarg of methods of EnterpriseModels. module: enterprise module name (e.g., gp_priors). key: str, a key in option (dict), the value of which corresponds a function in module. Example keys: “psd”, “orf”. kwargs: dict, all possible parameters for the function corresponding to option[key].

custom_models: globals() if used in a child class of EnterpriseModels, to pass all local applicable functions. Otherwise, {}.

Equivalent to returning pl here: >>> log10_A = parameter.Uniform(self.params.sn_lgA[0],self.params.sn_lgA[1]) >>> gamma = parameter.Uniform(self.params.sn_gamma[0],self.params.sn_gamma[1]) >>> pl = utils.powerlaw(log10_A=log10_A, gamma=gamma)

enterprise_warp.enterprise_models.interpret_white_noise_prior(prior)[source]

Interpret prior distribution parameters, passed from parameter file. Adding only one numbers sets prior to be a constant, while two numbers are interpreted as Uniform prior bounds.

enterprise_warp.enterprise_models.selection_factory(new_selection_name)[source]

This function constructs new selection functions for band and system noise, so that the specific band/system selection with flag and flag values (i.e., “group” and “CPSR2_50CM”) are passed as arrays “sys_flags” and “sys_flagvals” in enterprise.pulsar.Pulsar object. The selection function name contains an index for these arrays, which tell the function which flag and value to use.

This method is not ideal, but it allows to create the right number of selection functions for any given number of band/system noise terms, without the need to pre-define them or modify the Enterprise code.

Parameters

new_selection_name: str

Python string with selection function name that we need to create. Selection function name format is “name_N”, where N is an integer, an array index for “sys_flags” and “sys_flagvals”.

enterprise_warp.enterprise_models.toa_mask_from_selection_function(psr, selfunc)[source]

Create numpy array mask for ToA array, by applying selection function to enterprise.pulsar.Pulsar object.

Parameters

psr: enterprise.pulsar.Pulsar

Pulsar object in Enterprise format

selfunc: function

Selection function. Examples are in enterprise.signals.selections


results

This module is used to load and analyze the results: calculate Bayes factors, plot posterior distributions, make noise files.

Result view and plotting for enterprise warp. Example:

>>> python -m enterprise_warp.results --result parameter_file_dat_or_directory --info 1
>>> python -m enterprise_warp.results --result enterprise_dir --result discovery_dir --corner 2 --hists 1 --chains 1
See python -m enterprise_warp.results -h for a list of available options:

–corner 1: for corner plot (–corner 2 for ChainConsumer); –par gw: to only include parameter with “gw” in its name into the corner plot; –name J0437: to only plot results for pulsars which names contain string “J0437”. –chains 1: to make a plot of MCMC chain for all parameters.

class enterprise_warp.results.DiscoveryWarpResult(opts, custom_models_obj=None)[source]

Result handler for Discovery/NumPyro runs that save CSV chains.

load_chains()[source]

Load NumPyro CSV chains.

class enterprise_warp.results.FakeResultOpts(outdir)[source]

Fake output of parse_commandline()

class enterprise_warp.results.ResultCollection(opts, result_cls, custom_models_obj=None)[source]

Compare multiple result directories using their loaded sample arrays.

class enterprise_warp.results.ResultsParser[source]

Parser class for enterprise_warp result actions.

enterprise_warp.results.add_result_commandline_options(parser=None)[source]

Add command line arguments for action on results.

enterprise_warp.results.check_if_psr_dir(folder_name)[source]

Check if the folder name (without path) is in the enterprise_warp format: integer, underscore, pulsar name.

enterprise_warp.results.dist_mode_position(values, nbins=50)[source]

Parameters

values: float

Values of a distribution

method: int

Approximating a distribution with a histogram with this number of bins

Returns

valuefloat

Position of the largest frequency bin

enterprise_warp.results.estimate_from_distribution(values, method='mode', errorbars_cdf=[16, 84])[source]

Return estimate of a value from a distribution (i.e., an MCMC posterior)

Parameters

values: float

Values of a distribution

method: str

Currently available: mode or median

Returns

valuefloat

Position of a mode or a median of a distribution, along the “values” axis

enterprise_warp.results.main()[source]

The pipeline script

enterprise_warp.results.make_noise_dict(psrname, chain, pars, method='mode', suffix='noise', outdir='noisefiles/', recompute=True)[source]

Create noise dictionary for a given MCMC or nested sampling chain. This is a dict that assigns a characteristic value (mode/median) to a parameter from the distribution of parameter values in a chain. Can be used for outputting a noise file or for use in further analysis (e.g. optimal statistic)

enterprise_warp.results.make_noise_files(psrname, chain, pars, outdir='noisefiles/', method='mode', suffix='noise')[source]

Create noise files from a given MCMC or nested sampling chain. Noise file is a dict that assigns a characteristic value (mode/median) to a parameter from the distribution of parameter values in a chain.

enterprise_warp.results.parse_commandline()[source]

Parsing command line arguments for action on results.

enterprise_warp.results.suitable_estimator(levels, errorbars_cdf=[16, 84])[source]

Returns maximum-posterior value (posterior mode position) if it is within credible levels, otherwise returns 50%-CDF value. The function complements estimate_from_distribution().


bilby_warp

This module contains a wrapper for Bilby (the Bayesian Inference LiBrarY), a software developed in the LIGO collaboration. Bilby provides access to multiple likelihood samplers and other useful tools for data analysis.

enterprise_warp.bilby_warp.get_bilby_prior_dict(pta)[source]

Get Bilby parameter dict from Enterprise PTA object. Currently only works with uniform priors.

Parameters

pta: enterprise.signals.signal_base.PTA

Enterprise PTA object that contains pulsar data and noise models


tempo2_warp

This module contains a function to run tempo2 in Python, in order to produce maximum-likelihood time-correlated (red) noise realizations.

enterprise_warp.tempo2_warp.get_tempo2_prediction(par, tim, configuration, output_file, execute='tempo2')[source]

Runs tempo2 and returns noise reconstruction in a file. Plugin “general2” for Tempo2 is required.

See tempo2 manual online for more information. Output can be loaded with numpy.loadtxt().

Parameters

par: str

Path to a .par file

tim: str

Path to a .tim file

configuration: str

String in a string, with tempo2-general2 parameters: ‘”{bat}t{freq}t{post}t{err}t{posttn}t{tndm}t{tnrn}n”’

output_file: str

Output file name with a full path

execute: str

A shell command to run Tempo2 or the full path to the tempo2 executable file, if other user’s tempo2 executable is sourced and aliased.


libstempo_warp

This model contains useful tools for pulsar timing array data simulation with libstempo. It extends libstempo simulations to realistic pulsar data with multiple observing backends, based on real pulsar data.

enterprise_warp.libstempo_warp.add_noise(t2pulsar, noise_dict, sim_dm=True, sim_white=True, sim_red=True, seed=None)[source]

Recognize noise from noise parameter name, and add to t2pulsar.

enterprise_warp.libstempo_warp.added_noise_psd_to_vector(added_noise_psd_params, param='efac')[source]

Conversion of dict to vector to simulate efac/equad in libstempo