### Complete Analysis Example - GWB Search Source: https://context7.com/nanograv/enterprise/llms.txt This section provides a comprehensive example demonstrating the setup and execution of a gravitational wave background (GWB) search analysis using the Enterprise library. ```APIDOC ## Complete Analysis Example - GWB Search ### Description A complete example showing how to set up and run a gravitational wave background analysis. ### Method Loading pulsar data, defining noise models, and setting up the PTA for analysis. ### Endpoint N/A (Script Example) ### Parameters None (Illustrative example) ### Request Example ```python import numpy as np from enterprise.pulsar import Pulsar from enterprise.signals import signal_base, white_signals, gp_signals, gp_priors, utils, parameter, selections from enterprise.signals.selections import Selection # Load pulsar data import glob parfiles = sorted(glob.glob('data/*.par')) timfiles = sorted(glob.glob('data/*.tim')) psrs = [Pulsar(p, t) for p, t in zip(parfiles, timfiles)] # Calculate time span for frequency basis tmin = min(psr.toas.min() for psr in psrs) tmax = max(psr.toas.max() for psr in psrs) Tspan = tmax - tmin # White noise with per-backend EFAC/EQUAD selection = Selection(selections.by_backend) efac = parameter.Uniform(0.5, 1.5) equad = parameter.Uniform(-10, -5) ef = white_signals.MeasurementNoise(efac=efac, log10_t2equad=equad, selection=selection) # ECORR ecorr = parameter.Uniform(-10, -5) ec = white_signals.EcorrKernelNoise(log10_ecorr=ecorr, selection=selection) # Intrinsic red noise per pulsar log10_A_rn = parameter.Uniform(-20, -11) gamma_rn = parameter.Uniform(0, 7) pl_rn = gp_priors.powerlaw(log10_A=log10_A_rn, gamma=gamma_rn) rn = gp_signals.FourierBasisGP(spectrum=pl_rn, components=30, Tspan=Tspan, name='red_noise') ``` ### Response #### Success Response (200) N/A (Illustrative example) #### Response Example (Further steps in a GWB analysis would involve combining these signals into a PTA, defining the GWB model, and running inference.) ``` -------------------------------- ### Example Parameter Initialization Output Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/usage.ipynb Illustrates the expected output when printing the parameters of an initialized timing model. This shows the parameter names, including the pulsar designation, and their associated prior distributions. ```text ["B1855+09_efac":Uniform(0.5,5), "B1855+09_gamma":Uniform(1,7), "B1855+09_log10_A":Uniform(-18,-12), "B1855+09_log10_ecorr":Uniform(-10,-5), "B1855+09_log10_equad":Uniform(-10,-5)] ``` -------------------------------- ### Get Initial Sampled Parameters for Enterprise PTA Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/mdc.ipynb Generates a dictionary of initial parameter values by sampling from their defined priors for the enterprise PTA. This dictionary is used to start the MCMC chain. ```python xs = {par.name: par.sample() for par in pta.params} print(xs) ``` -------------------------------- ### Clone Enterprise Repository and Set Up Remotes Source: https://github.com/nanograv/enterprise/blob/master/docs/contributing.md This set of commands guides users through forking the enterprise repository, cloning their fork locally, and setting up the official repository as an 'upstream' remote for pulling updates. ```shell # Clone your forked repository $ git clone git@github.com:your_name_here/enterprise.git # Navigate into the cloned directory $ cd enterprise/ # Add the official nanograv/enterprise repository as an upstream remote $ git remote add upstream https://github.com/nanograv/enterprise.git ``` -------------------------------- ### Run PTMCMC Sampler Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/nano9.ipynb Executes the PTMCMC sampler for a specified number of steps (N). Initializes the sampler with starting parameters (x0) and specifies weights for different sampling algorithms (SCAM, AM, DE). ```python # sampler for N steps N = 1000000 x0 = np.hstack(p.sample() for p in pta.params) sampler.sample(x0, N, SCAMweight=30, AMweight=15, DEweight=50, ) ``` -------------------------------- ### Setup Simple Noise Model in enterprise Source: https://github.com/nanograv/enterprise/blob/master/docs/mdc.md This Python snippet demonstrates setting up a basic noise model for a single pulsar using enterprise. It defines parameters and priors for EFAC and red noise (power-law), sets up corresponding signals (MeasurementNoise, FourierBasisGP), and combines them with a TimingModel into a full PTA object. ```python import enterprise.signals.signal_utils as utils import enterprise.signals.gp_signals as gp_signals import enterprise.signals.white_signals as white_signals from enterprise.core import parameter from enterprise.core import signal_base ##### parameters and priors ##### # Uniform prior on EFAC efac = parameter.Uniform(0.1, 5.0) # red noise parameters # Uniform in log10 Amplitude and in spectral index log10_A = parameter.Uniform(-18,-12) gamma = parameter.Uniform(0,7) ##### Set up signals ##### # white noise ef = white_signals.MeasurementNoise(efac=efac) # red noise (powerlaw with 30 frequencies) pl = utils.powerlaw(log10_A=log10_A, gamma=gamma) rn = gp_signals.FourierBasisGP(spectrum=pl, components=30) # timing model tm = gp_signals.TimingModel() # full model is sum of components model = ef + rn + tm # initialize PTA pta = signal_base.PTA([model(psrs[0])]) ``` -------------------------------- ### Install Local Enterprise Fork with Pip Source: https://github.com/nanograv/enterprise/blob/master/docs/contributing.md This command installs the 'enterprise' package in editable mode from the local source code. This is typically done after cloning the repository and setting up the development environment, allowing changes in the source code to be immediately reflected. ```shell # Install the local enterprise fork in editable mode $ pip install -e . ``` -------------------------------- ### Get Initial Parameters for MCMC Sampling Source: https://github.com/nanograv/enterprise/blob/master/docs/mdc.md This Python code generates an initial parameter dictionary for MCMC sampling. It iterates through the parameters defined in the PTA object and samples a starting value for each using their respective sample() methods. This dictionary is used to initialize the sampler. ```python xs = {par.name: par.sample() for par in pta.params} print(xs) ``` -------------------------------- ### Define Enterprise Parameter with Uniform Prior Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/usage.ipynb Demonstrates how to define a signal parameter in Enterprise with a specified prior distribution. This example creates an 'efac' parameter with a uniform prior ranging from 0.5 to 5. Abstract parameter classes allow for flexible initialization with different names. ```python # lets define an efac parameter with a uniform prior from [0.5, 5] efac = parameter.Uniform(0.5, 5) ``` -------------------------------- ### Setup Sampler for PTA Analysis (Python) Source: https://github.com/nanograv/enterprise/blob/master/docs/mdc.md This Python code initializes the MCMC sampler for the PTA analysis. It generates initial parameter values, determines the parameter space dimension, and creates an initial jump covariance matrix. Jump groups are defined to optimize the sampling process, particularly for red noise parameters. ```python # initial parameters xs = {par.name: par.sample() for par in pta.params} # dimension of parameter space ndim = len(xs) # initial jump covariance matrix cov = np.diag(np.ones(ndim) * 0.01**2) # set up jump groups by red noise groups ndim = len(xs) groups = [range(0, ndim)] groups.extend(map(list, zip(range(0,ndim,2), range(1,ndim,2)))) sampler = ptmcmc(ndim, pta.get_lnlikelihood, pta.get_lnprior, cov, groups=groups, outDir='chains/mdc/open1_gwb/') ``` -------------------------------- ### Install local enterprise fork Source: https://github.com/nanograv/enterprise/blob/master/CONTRIBUTING.rst Installs the local development version of the enterprise project into the active Python environment using pip. This command assumes dependencies are already installed, potentially via conda. ```shell $ pip install -e . ``` -------------------------------- ### Initialize and activate enterprise virtual environment Source: https://github.com/nanograv/enterprise/blob/master/CONTRIBUTING.rst Initializes a Python virtual environment named '.enterprise' and activates it. This is an alternative method for setting up the development environment if dependencies were not installed via conda. ```shell $ make init $ source .enterprise/bin/activate ``` -------------------------------- ### Python Class Factory Example Source: https://github.com/nanograv/enterprise/blob/master/docs/data.md Demonstrates a Python class factory, a function that returns a class. This allows for 'global' parameters to be passed to a class without needing them during instantiation. The example shows how arguments passed to the factory are accessible within the class instances. ```python def A(farg1, farg2): class A(object): def __init__(self, iarg): self.iarg = iarg def print_info(self): print('Object instance {}\nInstance argument: {}\nFunction args: {} {} '.format( self, self.iarg, farg1, farg2)) return A ``` ```python # define class A with arguments that can be seen within the class a = A('arg1', 'arg2') # instantiate 2 instances of class A with different arguments a1 = a('iarg1') a2 = a('iarg2') # call print_info method a1.print_info() a2.print_info() ``` -------------------------------- ### Complete Gravitational Wave Background Search Analysis in Python Source: https://context7.com/nanograv/enterprise/llms.txt Provides a comprehensive example of setting up and running a gravitational wave background (GWB) search analysis. This includes loading pulsar data, calculating time span, defining white noise parameters (EFAC, EQUAD, ECORR), modeling intrinsic red noise, and setting up the PTA object for analysis. ```python import numpy as np from enterprise.pulsar import Pulsar from enterprise.signals import signal_base, white_signals, gp_signals, gp_priors, utils, parameter, selections from enterprise.signals.selections import Selection import glob # Load pulsar data parfiles = sorted(glob.glob('data/*.par')) timfiles = sorted(glob.glob('data/*.tim')) psrs = [Pulsar(p, t) for p, t in zip(parfiles, timfiles)] # Calculate time span for frequency basis tmin = min(psr.toas.min() for psr in psrs) tmax = max(psr.toas.max() for psr in psrs) Tspan = tmax - tmin # White noise with per-backend EFAC/EQUAD selection = Selection(selections.by_backend) efac = parameter.Uniform(0.5, 1.5) equad = parameter.Uniform(-10, -5) ef = white_signals.MeasurementNoise(efac=efac, log10_t2equad=equad, selection=selection) # ECORR ecorr = parameter.Uniform(-10, -5) ec = white_signals.EcorrKernelNoise(log10_ecorr=ecorr, selection=selection) # Intrinsic red noise per pulsar log10_A_rn = parameter.Uniform(-20, -11) gamma_rn = parameter.Uniform(0, 7) pl_rn = gp_priors.powerlaw(log10_A=log10_A_rn, gamma=gamma_rn) rn = gp_signals.FourierBasisGP(spectrum=pl_rn, components=30, Tspan=Tspan, name='red_noise') ``` -------------------------------- ### Import Enterprise Libraries and Setup Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/data.ipynb Imports necessary libraries for enterprise, including numpy, matplotlib, and specific enterprise modules like Pulsar and parameter. It also sets up matplotlib for inline plotting and retina display. ```python % matplotlib inline %config InlineBackend.figure_format = 'retina' from __future__ import division import numpy as np import matplotlib.pyplot as plt import enterprise from enterprise.pulsar import Pulsar import enterprise.signals.parameter as parameter from enterprise.signals import utils from enterprise.signals import signal_base from enterprise.signals import selections from enterprise.signals.selections import Selection datadir = enterprise.__path__[0] + '/datafiles/ng9/' ``` -------------------------------- ### Setup PTA Model for GWB Analysis (Python) Source: https://github.com/nanograv/enterprise/blob/master/docs/mdc.md This Python code sets up a PTA model for analyzing the Gravitational Wave Background (GWB) across 36 pulsars. It defines white noise parameters, red noise using a powerlaw spectrum, and the GWB signal with Hellings and Downs spatial correlations. The model is then compiled and used to initialize the PTA object. ```python # find the maximum time span to set GW frequency sampling tmin = [p.toas.min() for p in psrs] tmax = [p.toas.max() for p in psrs] Tspan = np.max(tmax) - np.min(tmin) ##### parameters and priors ##### # white noise parameters # in this case we just set the value here since all efacs = 1 # for the MDC data efac = parameter.Constant(1.0) # red noise parameters log10_A = parameter.Uniform(-18,-12) gamma = parameter.Uniform(0,7) ##### Set up signals ##### # white noise ef = white_signals.MeasurementNoise(efac=efac) # red noise (powerlaw with 30 frequencies) pl = utils.powerlaw(log10_A=log10_A, gamma=gamma) rn = gp_signals.FourierBasisGP(spectrum=pl, components=30, Tspan=Tspan) # gwb # We pass this signal the power-law spectrum as well as the standard # Hellings and Downs ORF orf = utils.hd_orf() crn = gp_signals.FourierBasisCommonGP(pl, orf, components=30, name='gw', Tspan=Tspan) # timing model tm = gp_signals.TimingModel() # full model is sum of components model = ef + rn + tm + crn # initialize PTA pta = signal_base.PTA([model(psr) for psr in psrs]) ``` -------------------------------- ### Python Parameter Class Factory Usage Source: https://github.com/nanograv/enterprise/blob/master/docs/data.md Illustrates the use of the Parameter class factory in enterprise for defining signal parameters with prior distributions. It shows how to create a Uniform prior, instantiate it with a name, and access its methods like getting the PDF and sampling. ```python # lets define an efac parameter with a uniform prior from [0.5, 5] efac = parameter.Uniform(0.5, 5) print(efac) ``` ```python # initialize efac parameter with name "efac_1" efac1 = efac('efac_1') print(efac1) # return parameter name print(efac1.name) # get pdf at a point (log pdf is access) print(efac1.get_pdf(1.3), efac1.get_logpdf(1.3)) # return 5 samples from this prior distribution print(efac1.sample(n=5)) ``` -------------------------------- ### Setup PTMCMCSampler for enterprise PTA Source: https://github.com/nanograv/enterprise/blob/master/docs/mdc.md This snippet configures the PTMCMCSampler for use with an enterprise PTA object. It determines the parameter space dimension, sets up an initial covariance matrix, defines jump groups for correlated parameters, and initializes the sampler with the PTA's log-likelihood and log-prior functions. ```python import numpy as np from PTMCMCSampler.sampler import Sampler as ptmcmc # dimension of parameter space ndim = len(xs) # initial jump covariance matrix cov = np.diag(np.ones(ndim) * 0.01**2) # set up jump groups by red noise groups ndim = len(xs) groups = [range(0, ndim)] groups.extend([[1,2]]) # intialize sampler sampler = ptmcmc(ndim, pta.get_lnlikelihood, pta.get_lnprior, cov, groups=groups, outDir='chains/mdc/open1/') ``` -------------------------------- ### Initialize and Activate Enterprise Development Environment (Manual) Source: https://github.com/nanograv/enterprise/blob/master/docs/contributing.md This sequence of commands is for manually setting up a Python 3 virtual environment for local enterprise development. It first initializes the environment and then activates it, making the local fork of enterprise available. ```shell # Initialize the development environment (creates .enterprise directory) $ make init # Activate the Python 3 virtual environment $ source .enterprise/bin/activate ``` -------------------------------- ### Install enterprise dependencies and development version Source: https://github.com/nanograv/enterprise/blob/master/CONTRIBUTING.rst Installs the 'enterprise-pulsar' package using conda, then removes it to allow for the use of a local development version. Finally, it installs a conditional coverage plugin for tests. ```shell $ conda install -c conda-forge enterprise-pulsar $ conda remove enterprise-pulsar --force $ pip install coverage-conditional-plugin ``` -------------------------------- ### Initialize Linear Timing Model (Python) Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/usage.ipynb Sets up the linear timing model as a Gaussian Process with very large variances. This approach is equivalent to marginalizing over the linear timing model coefficients assuming uniform priors, and is implemented using enterprise's TimingModel class. ```python # timing model as GP (no parameters) tm = gs.TimingModel() ``` -------------------------------- ### Initialize and Print Sine Wave Function Source: https://github.com/nanograv/enterprise/blob/master/docs/data.md Demonstrates the initialization of a sine wave function using `enterprise.parameter.Uniform` for logarithmic amplitude and frequency, and then prints the resulting function object. This shows the basic structure of an enterprise function. ```python sw_function = sine_wave(log10_A=parameter.Uniform(-10,-5), log10_f=parameter.Uniform(-9, -7)) print(sw_function) ``` -------------------------------- ### Install and Manage Enterprise Dependencies with Conda Source: https://github.com/nanograv/enterprise/blob/master/docs/contributing.md This code sequence installs the 'enterprise-pulsar' package using Conda, then immediately removes it to allow for local development versions. It also installs a conditional coverage plugin for testing. ```shell # Install enterprise-pulsar from conda-forge channel $ conda install -c conda-forge enterprise-pulsar # Remove the installed version to use local development version $ conda remove enterprise-pulsar --force # Install a plugin for conditional test coverage $ pip install coverage-conditional-plugin ``` -------------------------------- ### Python Function Structure Example Source: https://github.com/nanograv/enterprise/blob/master/docs/data.md Demonstrates the enterprise Function structure, which converts standard Python functions into objects that can interact with Pulsar data and enterprise Parameters. The example shows a sine wave function decorated with @signal_base.function. ```python @signal_base.function def sine_wave(toas, log10_A=-7, log10_f=-8): return 10**log10_A * np.sin(2*np.pi*toas*10**log10_f) ``` ```python # treat it just as a standard function with a vector input sw = sine_wave(np.array([1,2,3]), log10_A=-8, log10_f=-7.5) print(sw) ``` -------------------------------- ### Initialize and Use Enterprise Parameter Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/usage.ipynb Initializes an abstract Enterprise parameter with a specific name ('efac_1') and demonstrates its methods. This includes retrieving the parameter name, calculating the probability density function (PDF) and log PDF at a given point, and sampling from the prior distribution. ```python # initialize efac parameter with name "efac_1" efac1 = efac('efac_1') # return parameter name print(efac1.name) # get pdf at a point (log pdf is access) print(efac1.get_pdf(1.3), efac1.get_logpdf(1.3)) # return 5 samples from this prior distribution print(efac1.sample(size=5)) ``` -------------------------------- ### Run Enterprise Tests and Documentation Builds Source: https://github.com/nanograv/enterprise/blob/master/docs/contributing.md These commands are used to verify local changes before committing. 'make test' runs the project's test suite, and 'make docs' builds the project's documentation, ensuring that code changes adhere to project standards and that documentation is correctly formatted. ```shell # Run the test suite $ make test # Build the documentation $ make docs ``` -------------------------------- ### Initialize MCMC Sampler Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/mdc.ipynb Sets up the PTMCMC sampler for a PTA analysis. It defines the parameter space, initial covariance matrix, and jump groups for efficient sampling. ```python # initial parameters xs = {par.name: par.sample() for par in pta.params} # dimension of parameter space ndim = len(xs) # initial jump covariance matrix cov = np.diag(np.ones(ndim) * 0.01**2) # set up jump groups by red noise groups ndim = len(xs) groups = [range(0, ndim)] groups.extend(map(list, zip(range(0,ndim,2), range(1,ndim,2)))) sampler = ptmcmc(ndim, pta.get_lnlikelihood, pta.get_lnprior, cov, groups=groups, outDir='chains/mdc/open1_gwb/') ``` -------------------------------- ### Clone and set up enterprise repository Source: https://github.com/nanograv/enterprise/blob/master/CONTRIBUTING.rst Clones the enterprise repository from GitHub, navigates into the directory, and sets the upstream remote to the main nanograv/enterprise repository for pulling updates. ```shell $ git clone git@github.com:your_name_here/enterprise.git $ cd enterprise/ $ git remote add upstream https://github.com/nanograv/enterprise.git ``` -------------------------------- ### Get Par and Tim Files for Pulsar Data Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/mdc.ipynb Retrieves the par and tim files for the open MDC1 dataset. These files contain pulsar timing information necessary for analysis. ```python parfiles = sorted(glob.glob(datadir + '/*.par')) timfiles = sorted(glob.glob(datadir + '/*.tim')) ``` -------------------------------- ### Set Up Signal Components Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/nano9.ipynb Configures various signal components for the PTA model, including white noise (MeasurementNoise, EquadNoise, EcorrKernelNoise), red noise (FourierBasisGP with powerlaw spectrum), gravitational wave background (FourierBasisGP with powerlaw spectrum), and a timing model. Dependencies include 'white_signals', 'utils', 'gp_signals', and 'signal_base'. ```python # white noise ef = white_signals.MeasurementNoise(efac=efac, selection=selection) eq = white_signals.EquadNoise(log10_equad=equad, selection=selection) ec = white_signals.EcorrKernelNoise(log10_ecorr=ecorr, selection=selection) # red noise (powerlaw with 30 frequencies) pl = utils.powerlaw(log10_A=log10_A, gamma=gamma) rn = gp_signals.FourierBasisGP(spectrum=pl, components=30, Tspan=Tspan) # gwb (no spatial correlations) cpl = utils.powerlaw(log10_A=log10_A_gw, gamma=gamma_gw) gw = gp_signals.FourierBasisGP(spectrum=cpl, components=30, Tspan=Tspan) # timing model tm = gp_signals.TimingModel() # full model is sum of components model = ef + eq + ec + rn + tm + gw # intialize PTA pta = signal_base.PTA([model(psr) for psr in psrs]) ``` -------------------------------- ### Initialize Parameter Caches Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/nano9.ipynb Initializes parameter caches by sampling from the prior and evaluating the likelihood and prior. This step is optional as caches are filled on the first sampler call, but explicit evaluation can be useful for debugging or pre-computation. ```python xs = {par.name: par.sample() for par in pta.params} print pta.get_lnlikelihood(xs); print pta.get_lnprior(xs); ``` -------------------------------- ### Define Parameter Priors with ENTERPRISE Source: https://context7.com/nanograv/enterprise/llms.txt Illustrates how to define parameters with various prior distributions using the `enterprise.signals.parameter` module. This includes Uniform, Normal, LinearExp, Truncated Normal, Constant, and Vector parameters, along with sampling from multiple parameters. ```python from enterprise.signals import parameter from enterprise.signals.parameter import sample # Uniform prior efac = parameter.Uniform(0.5, 1.5) efac_param = efac('B1855+09_efac') print(f"Parameter name: {efac_param.name}") print(f"Sample: {efac_param.sample()}") print(f"PDF at 1.0: {efac_param.get_pdf(1.0)}") print(f"Log PDF: {efac_param.get_logpdf(1.0)}") # Normal prior (Gaussian) log10_A = parameter.Normal(mu=-15, sigma=2) gamma = parameter.Normal(mu=4.33, sigma=0.5) # LinearExp prior (uniform in linear space, log parameter) log10_equad = parameter.LinearExp(-10, -5) # Truncated Normal bounded_param = parameter.TruncNormal(mu=0, sigma=1, pmin=-2, pmax=2) # Constant parameter (fixed value) efac_fixed = parameter.Constant(1.0) # Vector parameter (multiple values) jup_orb = parameter.Uniform(-0.05, 0.05, size=6)('jup_orb_elements') # Sample from multiple parameters consistently params = [efac('efac'), log10_A('log10_A'), gamma('gamma')] sampled = sample(params) print(f"Sampled parameters: {sampled}") ``` -------------------------------- ### Import Enterprise Libraries (Python) Source: https://github.com/nanograv/enterprise/blob/master/tests/data.ipynb Imports necessary libraries from the Enterprise package and its dependencies, including numpy, matplotlib, and specific modules for pulsar data, signal parameters, and utility functions. This setup is crucial for subsequent data analysis and modeling. ```python % matplotlib inline %config InlineBackend.figure_format = 'retina' from __future__ import division import numpy as np import matplotlib.pyplot as plt from enterprise.pulsar import Pulsar import enterprise.signals.parameter as parameter from enterprise.signals import utils from enterprise.signals import signal_base from enterprise.signals import selections from enterprise.signals.selections import Selection #from tests.enterprise_test_data import datadir from enterprise_test_data import datadir ``` -------------------------------- ### Load Pulsar Object from Feather File Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/usage.ipynb Loads a Pulsar object from a previously saved feather file. This process does not require 'libstempo' or 'PINT' to be installed, making it efficient for accessing stored pulsar data. The loaded object can then be used for further analysis within Enterprise. ```python psr = Pulsar(datadir + f"/{psr_name}_NANOGrav_9yv1.t2.feather") ``` -------------------------------- ### Set Up MCMC Sampler Source: https://github.com/nanograv/enterprise/blob/master/docs/nano9.md Configures and sets up the PTMCMC sampler for Bayesian inference. It defines the dimensionality of the parameter space, the initial jump covariance matrix, and groups parameters for efficient sampling. The output directory for chain files is also specified. ```python # dimension of parameter space ndim = len(xs) # initial jump covariance matrix cov = np.diag(np.ones(ndim) * 0.01**2) # set up jump groups by red noise groups ndim = len(xs) groups = [range(0, ndim)] groups.extend(map(list, zip(range(0,ndim,2), range(1,ndim,2)))) groups.extend([[36]]) sampler = ptmcmc(ndim, pta.get_lnlikelihood, pta.get_lnprior, cov, groups=groups, outDir='chains/nano_9_gwb/') ``` -------------------------------- ### Get Pulsar Timing Data Files Source: https://github.com/nanograv/enterprise/blob/master/docs/mdc.md This snippet uses the glob module to find all .par and .tim files in a specified directory. These files are essential for loading pulsar timing data into the enterprise package. The files are sorted to ensure consistent ordering. ```python import glob parfiles = sorted(glob.glob(datadir + '/*.par')) timfiles = sorted(glob.glob(datadir + '/*.tim')) ``` -------------------------------- ### Examine MCMC Chain Output Source: https://github.com/nanograv/enterprise/blob/master/docs/mdc.md This Python snippet loads the MCMC chain data from a text file and prepares it for analysis. It reads the chain, sorts the parameter names, and calculates the burn-in period. This data can then be used for visualization and parameter estimation, for example, using corner plots. ```python import corner chain = np.loadtxt('chains/mdc/open1/chain_1.txt') pars = sorted(xs.keys()) burn = int(0.25 * chain.shape[0]) truths = [1.0, 4.33, np.log10(5e-14)] corner.corner(chain[burn:,:-4], 30, truths=truths, labels=pars); ``` -------------------------------- ### Set up development environment with conda Source: https://github.com/nanograv/enterprise/blob/master/CONTRIBUTING.rst Creates a conda environment named 'ent_dev' with specified Python and development tools, then activates it. This environment is used for running tests and developing the enterprise project. ```shell $ conda create -n ent_dev -y -c conda-forge python=3.9 black=22.3.0 flake8 sphinx_rtd_theme pytest-cov $ conda activate ent_dev ``` -------------------------------- ### Set Up Enterprise Analysis Model Parameters (Python) Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/nano9.ipynb Configures the analysis model by setting white noise parameters to constant values derived from the noise files using `enterprise.signals.selections.Selection`. It also defines priors for red noise and GWB amplitude parameters using a `LinearExp` prior and fixes the GWB spectral index. Spatial correlations are omitted by using a single parameter instance for all pulsars. ```python # find the maximum time span to set GW frequency sampling tmin = [p.toas.min() for p in psrs] tmax = [p.toas.max() for p in psrs] Tspan = np.max(tmax) - np.min(tmin) # selection class to break white noise by backend selection = selections.Selection(selections.by_backend) ##### parameters and priors ##### # white noise parameters ``` -------------------------------- ### Configure PTMCMC Sampler Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/nano9.ipynb Sets up the PTMCMC sampler, defining the dimensionality of the parameter space, likelihood and prior functions, initial jump covariance matrix, and jump groups. The output directory for chains is also specified. ```python # dimension of parameter space ndim = len(xs) # initial jump covariance matrix cov = np.diag(np.ones(ndim) * 0.01**2) # set up jump groups by red noise groups ndim = len(xs) groups = [range(0, ndim)] groups.extend(map(list, zip(range(0,ndim,2), range(1,ndim,2)))) groups.extend([[36]]) sampler = ptmcmc(ndim, pta.get_lnlikelihood, pta.get_lnprior, cov, groups=groups, outDir='chains/nano_9_gwb/') ``` -------------------------------- ### Deterministic Signals - Physical Models Source: https://context7.com/nanograv/enterprise/llms.txt Implements deterministic signals, which are predictable waveforms subtracted from residuals. Examples include physical ephemeris corrections for solar system bodies and custom waveforms like continuous gravitational waves or sinusoidal signals. These signals can be defined using physical models or custom functions decorated with `@function`. ```python from enterprise.signals import deterministic_signals, parameter, utils from enterprise.signals.parameter import function import numpy as np # Physical ephemeris signal for solar system ephemeris corrections eph = deterministic_signals.PhysicalEphemerisSignal( frame_drift_rate=parameter.Uniform(-1e-9, 1e-9)('frame_drift_rate'), d_jupiter_mass=parameter.Normal(0, 1.55e-11)('d_jupiter_mass'), d_saturn_mass=parameter.Normal(0, 8.17e-12)('d_saturn_mass'), d_uranus_mass=parameter.Normal(0, 5.72e-11)('d_uranus_mass'), d_neptune_mass=parameter.Normal(0, 7.96e-11)('d_neptune_mass'), jup_orb_elements=parameter.Uniform(-0.05, 0.05, size=6)('jup_orb'), use_epoch_toas=True ) # Custom deterministic signal using @function decorator @function def sine_wave(toas, log10_A=-7, log10_f=-8): """Simple sinusoidal signal.""" return 10**log10_A * np.sin(2 * np.pi * toas * 10**log10_f) # Create signal with parameter priors sw = sine_wave( log10_A=parameter.Uniform(-10, -5), log10_f=parameter.Uniform(-9, -7) ) sine_signal = deterministic_signals.Deterministic(sw, name='sine') # Continuous gravitational wave (example custom waveform) @function def cw_delay(toas, pos, pdist, cos_gwtheta=0, gwphi=0, log10_fgw=-8, log10_h=-15, phase0=0, psi=0, cos_inc=0): """Simplified CW waveform (actual implementation is more complex).""" fgw = 10**log10_fgw h = 10**log10_h # Simplified - actual CW waveform includes antenna patterns, etc. return h * np.cos(2 * np.pi * fgw * toas + phase0) ``` -------------------------------- ### Set up Bayesian model parameters and signals (Python) Source: https://github.com/nanograv/enterprise/blob/master/docs/nano9.md This Python code configures parameters for a Bayesian analysis using the 'enterprise' package. It defines white noise parameters as constants, red noise parameters with LinearExp and Uniform priors, and gravitational wave (GW) parameters with LinearExp and Constant priors. It also initializes GW parameters to be common across all pulsars and sets the GW spectral index to a constant value. ```python # find the maximum time span to set GW frequency sampling tmin = [p.toas.min() for p in psrs] tmax = [p.toas.max() for p in psrs] Tspan = np.max(tmax) - np.min(tmin) # selection class to break white noise by backend selection = selections.Selection(selections.by_backend) ##### parameters and priors ##### # white noise parameters # since we are fixing these to values from the noise file we set # them as constant parameters efac = parameter.Constant() equاد = parameter.Constant() ecorr = parameter.Constant() # red noise parameters log10_A = parameter.LinearExp(-20,-12) gamma = parameter.Uniform(0,7) # GW parameters (initialize with names here to use parameters in common across pulsars) log10_A_gw = parameter.LinearExp(-18,-12)('log10_A_gw') gamma_gw = parameter.Constant(4.33)('gamma_gw') ##### Set up signals ##### ``` -------------------------------- ### Set Up Enterprise Signal Components for Noise Model Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/mdc.ipynb Configures the signal components for the noise model, including white noise (MeasurementNoise), red noise (FourierBasisGP with powerlaw spectrum), and a timing model. These components are then combined. ```python ##### Set up signals ##### # white noise ef = white_signals.MeasurementNoise(efac=efac) # red noise (powerlaw with 30 frequencies) pl = utils.powerlaw(log10_A=log10_A, gamma=gamma) rn = gp_signals.FourierBasisGP(spectrum=pl, components=30) # timing model tm = gp_signals.TimingModel() # full model is sum of components model = ef + rn + tm # initialize PTA pta = signal_base.PTA([model(psrs[0])]) ``` -------------------------------- ### Use Custom Backends and Apply Selection in Python Source: https://context7.com/nanograv/enterprise/llms.txt Shows how to utilize custom backends for selection and apply a specific selection method (by_backend) for measurement noise parameters like EFAC. This is useful for applying different noise properties to different backends. ```python from enterprise.signals import white_signals, parameter, selections from enterprise.signals.selections import Selection # Using custom backends custom_sel = Selection(selections.custom_backends(['GUPPI', 'PUPPI'])) # Apply selection to white noise efac_by_backend = white_signals.MeasurementNoise( efac=parameter.Uniform(0.5, 1.5), selection=Selection(selections.by_backend) ) ``` -------------------------------- ### Instantiate and Use Class Factory Objects in Python Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/data.ipynb Shows how to use the 'A' class factory. It first defines the factory with arguments, then instantiates two objects of the returned class with different arguments, and finally calls a method on these instances. ```python # define class A with arguments that can be seen within the class a = A('arg1', 'arg2') # instantiate 2 instances of class A with different arguments a1 = a('iarg1') a2 = a('iarg2') # call print_info method a1.print_info() a2.print_info() ``` -------------------------------- ### Set Up PTMCMCSampler for Enterprise PTA Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/mdc.ipynb Initializes the PTMCMCSampler for analyzing the enterprise PTA. It configures the sampler with the parameter space dimension, log-likelihood and log-prior functions, initial covariance matrix, and jump groups. ```python # dimension of parameter space ndim = len(xs) # initial jump covariance matrix cov = np.diag(np.ones(ndim) * 0.01**2) # set up jump groups by red noise groups ndim = len(xs) groups = [range(0, ndim)] groups.extend([[1,2]]) # intialize sampler sampler = ptmcmc(ndim, pta.get_lnlikelihood, pta.get_lnprior, cov, groups=groups, outDir='chains/mdc/open1/') ``` -------------------------------- ### Load and Access Pulsar Data with ENTERPRISE Source: https://context7.com/nanograv/enterprise/llms.txt Demonstrates loading pulsar data from par/tim files using tempo2 or PINT, and accessing various pulsar attributes. It also shows how to load multiple pulsars and save/load data using the feather format for efficient I/O. ```python import numpy as np from enterprise.pulsar import Pulsar # Load pulsar from par and tim files using tempo2 psr = Pulsar('path/to/pulsar.par', 'path/to/pulsar.tim') # Or specify timing package explicitly psr = Pulsar('pulsar.par', 'pulsar.tim', timing_package='pint') # Access pulsar attributes print(f"Pulsar name: {psr.name}") print(f"Number of TOAs: {len(psr.toas)}") print(f"Residuals (s): {psr.residuals}") print(f"TOA errors (s): {psr.toaerrs}") print(f"Frequencies (MHz): {psr.freqs}") print(f"Design matrix shape: {psr.Mmat.shape}") print(f"Sky position (theta, phi): {psr.theta}, {psr.phi}") print(f"Distance (kpc): {psr.pdist}") print(f"Backend flags: {psr.backend_flags}") # Load multiple pulsars import glob parfiles = sorted(glob.glob('datadir/*.par')) timfiles = sorted(glob.glob('datadir/*.tim')) psrs = [Pulsar(p, t) for p, t in zip(parfiles, timfiles)] # Save/load using feather format for fast I/O psr.to_feather('pulsar.feather', noisedict={'B1855+09_efac': 1.0}) psr_loaded = Pulsar('pulsar.feather') ``` -------------------------------- ### Create and Switch to a New Git Branch for Development Source: https://github.com/nanograv/enterprise/blob/master/docs/contributing.md This command creates a new Git branch for local development and immediately switches to it. This is a standard practice for isolating new features or bug fixes from the main codebase. ```shell # Create a new branch and switch to it $ git checkout -b name-of-your-bugfix-or-feature ``` -------------------------------- ### Run Enterprise Unit Tests with Python Source: https://github.com/nanograv/enterprise/blob/master/CONTRIBUTING.rst This command executes the unit tests for the enterprise module using Python's built-in unittest framework. Ensure you have the project structure set up correctly for the tests to be discovered and run. ```python python -m unittest tests.test_enterprise ``` -------------------------------- ### Create and Activate Conda Environment for Enterprise Development Source: https://github.com/nanograv/enterprise/blob/master/docs/contributing.md This snippet demonstrates how to create a new Conda environment named 'ent_dev' with specific Python and development dependencies, and then activate it. This environment is crucial for setting up enterprise for local development and running tests. ```shell # Create a virtual environment with development dependencies $ conda create -n ent_dev -y -c conda-forge python=3.9 black=22.3.0 flake8 sphinx_rtd_theme pytest-cov # Activate the environment $ conda activate ent_dev ``` -------------------------------- ### Build and Evaluate PTA Models in Python Source: https://context7.com/nanograv/enterprise/llms.txt Illustrates the process of constructing a Pulsar Timing Array (PTA) object by defining various signal components (white noise, red noise, timing model) and combining them. It covers loading pulsars, defining parameters, creating the model, initializing the PTA, and evaluating likelihood and prior. ```python from enterprise.signals import signal_base, gp_signals, white_signals, parameter, gp_priors from enterprise.pulsar import Pulsar import numpy as np # Load pulsars psrs = [Pulsar(f'psr{i}.par', f'psr{i}.tim') for i in range(3)] # Define signal components efac = parameter.Uniform(0.5, 1.5) log10_A = parameter.Uniform(-18, -12) gamma = parameter.Uniform(0, 7) ef = white_signals.MeasurementNoise(efac=efac) pl = gp_priors.powerlaw(log10_A=log10_A, gamma=gamma) rn = gp_signals.FourierBasisGP(spectrum=pl, components=30) tm = gp_signals.TimingModel() # Combine signals into model model = ef + rn + tm # Create PTA by initializing model with each pulsar pta = signal_base.PTA([model(psr) for psr in psrs]) # Access PTA properties print(f"Parameters: {pta.param_names}") print(f"Number of pulsars: {len(pta.pulsars)}") print(f"Pulsar names: {pta.pulsars}") # Generate parameter dictionary from array x0 = np.array([p.sample() for p in pta.params]) params = pta.map_params(x0) # Evaluate likelihood and prior lnlike = pta.get_lnlikelihood(params) lnprior = pta.get_lnprior(params) print(f"Log likelihood: {lnlike}") print(f"Log prior: {lnprior}") # Get model summary summary = pta.summary(include_params=True) print(summary) # Set constant/default parameters noise_dict = { 'B1855+09_efac': 1.0, 'B1937+21_efac': 1.1 } pta.set_default_params(noise_dict) # Access individual pulsar models for name, sc in pta.items(): print(f"Pulsar {name}: {len(sc.signals)} signals") # Get residuals and basis matrices residuals = pta.get_residuals() bases = pta.get_basis(params) delays = pta.get_delay(params) ``` -------------------------------- ### Run enterprise tests and documentation checks Source: https://github.com/nanograv/enterprise/blob/master/CONTRIBUTING.rst Executes the project's test suite and documentation formatting checks. This ensures that code changes are functional and documentation is correctly formatted before committing. ```shell $ make test $ make docs ``` -------------------------------- ### Load and Prepare Chain Data Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/nano9.ipynb Loads the MCMC chain data from a file, sorts the parameter names, and determines the burn-in period for analysis. Assumes the chain is stored in 'chain_1.txt' within the specified output directory. ```python chain = np.loadtxt('chains/nano_9_gwb/chain_1.txt) pars = sorted(xs.keys()) burn = int(0.25 * chain.shape[0]) ``` -------------------------------- ### Define Noise Model Parameters and Priors in Enterprise Source: https://github.com/nanograv/enterprise/blob/master/docs/_static/notebooks/mdc.ipynb Sets up parameters and their prior distributions for a noise model in enterprise. This includes EFAC for white noise and parameters for a power-law red noise process. ```python ##### parameters and priors ##### # Uniform prior on EFAC efac = parameter.Uniform(0.1, 5.0) # red noise parameters # Uniform in log10 Amplitude and in spectral index log10_A = parameter.Uniform(-18,-12) gamma = parameter.Uniform(0,7) ```