API Reference
FASTPT Class
- class fastpt.FASTPT(k, nu=None, to_do=None, param_mat=None, low_extrap=None, high_extrap=None, n_pad=None, verbose=False, simple=False, max_cache_size_mb=500, dump_cache=True)[source]
FASTPT is a numerical algorithm to calculate 1-loop contributions to the matter power spectrum and other integrals of a similar type. The method is presented in papers arXiv:1603.04826 and arXiv:1609.05978. Please cite these papers if you are using FASTPT in your research.
- Parameters:
- karray_like
The input k-grid (wavenumbers) in 1/Mpc. Must be logarithmically spaced with equal spacing in log(k) and contain an even number of elements.
- nufloat, optional
Deprecated. Previously used to specify power-law biasing for FFT calculations. Now determined automatically.
- to_dolist of str, optional
List of requirements for precalculation of matrices. Starting in v4, terms are calculated as needed without specifying them here, but pre-computing matrices remains an option and can save time on the initial run of functions. ‘All’ or ‘everything’ will initialize all terms.
- param_matarray_like, optional
Custom parameter matrix for extensions (advanced usage).
- low_extrapfloat, optional
If provided, extrapolate the power spectrum to lower k values down to 10^(low_extrap). Helps with edge effects. Typical value: -5.
- high_extrapfloat, optional
If provided, extrapolate the power spectrum to higher k values up to 10^(high_extrap). Helps with edge effects. Typical value: 3. Must be greater than low_extrap if both are provided.
- n_padint, optional
Number of zeros to pad the array with on both ends. Helps reduce edge effects in FFT calculations. If None, defaults to half the length of the input k array.
- verbosebool, optional
If True, prints additional information during calculations.
- simplebool, optional
If True, uses the older, simplified FASTPT interface. Will be deprecated.
- max_cache_size_mbint, optional
Maximum size of the internal cache in megabytes. Default is 500 MB.
- dump_cachebool, optional
If True, the cache is cleared when a new power spectrum is provided to a Fast-PT function to avoid building an unnecessarily large cache.
Notes
The input k array must be strictly increasing, equally logarithmically spaced, and contain an even number of elements.
Using extrapolation (low_extrap/high_extrap) and padding (n_pad) is recommended to reduce numerical artifacts from the FFT-based algorithm.
- IA_ct(P, P_window=None, C_window=None)[source]
Computes intrinsic alignment velocity-shear contributions.
- Returns:
tuple – (P_0tE, P_0EtE, P_E2tE, P_tEtE) where:
P_0tE (Density-velocity E-mode correlation)
P_0EtE (E-mode-velocity E-mode correlation)
P_E2tE (Second torquing-velocity E-mode correlation)
P_tEtE (Velocity E-mode auto-correlation)
- IA_der(P, P_window=None, C_window=None)[source]
Computes k^2 * P(k) derivative term for intrinsic alignment models.
- Returns:
P_der : Derivative term of the power spectrum
- Return type:
array_like
- IA_mix(P, P_window=None, C_window=None)[source]
Computes mixed intrinsic alignment contributions combining tidal alignment and tidal torque.
- Returns:
tuple – (P_A, P_Btype2, P_DEE, P_DBB) where:
P_A (Mixed tidal alignment/tidal torque term)
P_Btype2 (Second-type B-mode term)
P_DEE (Contribution to the E-mode power spectrum)
P_DBB (Contribution to the B-mode power spectrum)
- IA_ta(P, P_window=None, C_window=None)[source]
Computes intrinsic alignment tidal alignment contributions.
- Returns:
tuple – (P_deltaE1, P_deltaE2, P_0E0E, P_0B0B) where:
P_deltaE1 (First density-E mode correlation)
P_deltaE2 (Second density-E mode correlation)
P_0E0E (E-mode auto-correlation)
P_0B0B (B-mode auto-correlation)
- IA_tt(P, P_window=None, C_window=None)[source]
Computes intrinsic alignment tidal torque contributions.
- Returns:
tuple – (P_E, P_B) where:
P_E (E-mode (curl-free) tidal torque power spectrum)
P_B (B-mode (divergence-free) tidal torque power spectrum)
- IRres(P, L=0.2, h=0.67, rsdrag=135, P_window=None, C_window=None)[source]
Computes the IR-resummed power spectrum, which includes BAO damping.
- Parameters:
- Returns:
P_IRres : IR-resummed power spectrum with damped BAO features
- Return type:
array_like
- OV(P, P_window=None, C_window=None)[source]
Computes the Ostriker-Vishniac effect power spectrum.
- Returns:
P_OV : Ostriker-Vishniac effect power spectrum
- Return type:
array_like
- RSD_ABsum_components(P, f, P_window=None, C_window=None)[source]
Computes combined redshift-space distortion terms by powers of μ.
- Parameters:
f (float) – Logarithmic growth rate
- Returns:
tuple – (ABsum_mu2, ABsum_mu4, ABsum_mu6, ABsum_mu8) where:
ABsum_mu2 (Combined term with μ^2 dependence)
ABsum_mu4 (Combined term with μ^4 dependence)
ABsum_mu6 (Combined term with μ^6 dependence)
ABsum_mu8 (Combined term with μ^8 dependence)
- RSD_ABsum_mu(P, f, mu_n, P_window=None, C_window=None)[source]
Computes the total redshift-space distortion correction at a given μ.
- RSD_components(P, f, P_window=None, C_window=None)[source]
Computes redshift-space distortion component terms.
- Parameters:
f (float) – Logarithmic growth rate
- Returns:
tuple – (A1, A3, A5, B0, B2, B4, B6, P_Ap1, P_Ap3, P_Ap5) where:
A1, A3, A5 (A-type RSD components with different powers of μ)
B0, B2, B4, B6 (B-type RSD components with different powers of μ)
P_Ap1, P_Ap3, P_Ap5 (Additional RSD A-prime components)
- __init__(k, nu=None, to_do=None, param_mat=None, low_extrap=None, high_extrap=None, n_pad=None, verbose=False, simple=False, max_cache_size_mb=500, dump_cache=True)[source]
- compute_term(term, X, operation=None, P=None, P_window=None, C_window=None)[source]
Computes a Fast-PT term with caching support.
- Parameters:
term (str) – Name of the term to compute, used for cache identification
X (tuple) – Fast-PT coefficient matrices for the calculation
operation (callable, optional) – Function to apply to the result(s) after computation
P (array_like) – Input power spectrum
P_window (tuple, optional) – Window parameters for tapering the power spectrum at the endpoints
C_window (float, optional) – Window parameter for tapering the Fourier coefficients
- Returns:
The computed Fast-PT term
- Return type:
array_like
- gI_ct(P, P_window=None, C_window=None)[source]
Computes galaxy bias cross intrinsic alignment velocity-shear contributions.
- Returns:
tuple – (P_d2tE, P_s2tE) where:
P_d2tE (Second-order density-velocity E-mode correlation)
P_s2tE (Second-order tidal-velocity E-mode correlation)
- gI_ta(P, P_window=None, C_window=None)[source]
Computes intrinsic alignment 2nd-order density correlations.
- Returns:
tuple – (P_d2E, P_d20E, P_s2E, P_s20E) where:
P_d2E (2nd-order density-E-mode correlation)
P_d20E (2nd-order density-density-E-mode correlation)
P_s2E (2nd-order tidal-E-mode correlation)
P_s20E (2nd-order tidal-density-E-mode correlation)
- gI_tt(P, P_window=None, C_window=None)[source]
Computes intrinsic alignment 2nd-order tidal correlations.
- Returns:
tuple – (P_s2E2, P_d2E2) where:
P_s2E2 (2nd-order tidal-E-mode squared correlation)
P_d2E2 (2nd-order density-E-mode squared correlation)
- kPol(P, P_window=None, C_window=None)[source]
Computes k-dependent polarization power spectra.
- Returns:
tuple – (P1, P2, P3) where:
P1 (First k-dependent polarization power spectrum)
P2 (Second k-dependent polarization power spectrum)
P3 (Third k-dependent polarization power spectrum)
- one_loop_dd(P, P_window=None, C_window=None)[source]
Computes the standard 1-loop density-density corrections to the power spectrum.
- Returns:
tuple – (P_1loop, Ps) where:
P_1loop (1-loop correction (P_22 + P_13))
Ps (Smoothed input power spectrum)
- one_loop_dd_bias(P, P_window=None, C_window=None)[source]
Computes 1-loop corrections with standard bias terms.
- Returns:
tuple – (P_1loop, Ps, Pd1d2, Pd2d2, Pd1s2, Pd2s2, Ps2s2, sig4) where:
P_1loop (1-loop correction (P_22 + P_13))
Ps (Smoothed input power spectrum)
Pd1d2 (First order density-second order density correlation)
Pd2d2 (Second order density auto-correlation)
Pd1s2 (First order density-second order tidal correlation)
Pd2s2 (Second order density-second order tidal correlation)
Ps2s2 (Second order tidal auto-correlation)
sig4 (σ^4 integral for nonlinear bias)
- one_loop_dd_bias_b3nl(P, P_window=None, C_window=None)[source]
Computes 1-loop corrections with bias terms including third-order non-local bias.
- Returns:
tuple – (P_1loop, Ps, Pd1d2, Pd2d2, Pd1s2, Pd2s2, Ps2s2, sig4, sig3nl) where:
The first 8 terms are identical to those returned by one_loop_dd_bias
sig3nl (Third order non-local bias term)
- one_loop_dd_bias_lpt_NL(P, P_window=None, C_window=None)[source]
Computes bias corrections in Lagrangian Perturbation Theory (LPT).
- Returns:
tuple – (Ps, Pb1L, Pb1L_2, Pb1L_b2L, Pb2L, Pb2L_2, sig4) where:
Ps (Smoothed input power spectrum)
Pb1L (First-order Lagrangian bias correlation term)
Pb1L_2 (First-order Lagrangian bias squared correlation)
Pb1L_b2L (First-order and second-order Lagrangian bias cross-correlation)
Pb2L (Second-order Lagrangian bias correlation)
Pb2L_2 (Second-order Lagrangian bias squared correlation)
sig4 (σ^4 integral for nonlinear bias)
FPTHandler Class
- class fastpt.FPTHandler(fastpt_instance: FASTPT, save_all=None, save_dir=None, **params)[source]
Handler class for FAST-PT that simplifies function calls and provides various convenience features relevant to FAST-PT calculations.
This class provides a simplified interface for working with FAST-PT functions, with features including power spectra generation, saving/loading outputs, direct access to specific power spectrum terms, plotting, and more.
- Parameters:
fastpt_instance (FASTPT) – An initialized FASTPT instance.
save_all (str, optional) – File format to save all results (‘txt’, ‘csv’, or ‘json’). If one is provided, all outputs of the run function will be saved. Default is None.
save_dir (str, optional) – Directory to save results. Default is ‘outputs’ directory in package location.
**params (dict) – Default parameters to use for all function calls.
Examples
>>> from fastpt import FASTPT, FPTHandler >>> import numpy as np >>> k = np.logspace(-3, 1, 200) >>> fpt = FASTPT(k) >>> handler = FPTHandler(fpt, C_window=0.75) >>> P = handler.generate_power_spectra() >>> handler.update_default_params(P=P) >>> P_1loop = handler.get('P_E') # Direct access to the P_E term of fpt.IA_tt
- bulk_run(func_names, power_spectra, verbose=False, **override_kwargs)[source]
Run multiple functions with multiple power spectra.
This method provides a convenient way to run multiple FAST-PT functions with different power spectra and collect all the results.
- Parameters:
- Returns:
Results keyed by (function_name, power_spectrum_index)
- Return type:
Examples
>>> k = np.logspace(-3, 1, 200) >>> fpt = FASTPT(k, low_extrap=-5, high_extrap=3) >>> handler = FPTHandler(fpt, C_window=0.75) >>> P1 = handler.generate_power_spectra(method='class') # Example power spectrum 1 >>> P2 = handler.generate_power_spectra(method='camb') # Example power spectrum 2 >>> results = handler.bulk_run(['one_loop_dd', 'IA_tt'], [P1, P2]) >>> one_loop_P1 = results[('one_loop_dd', 0)]
- clear_default_params()[source]
Clear all default parameters.
Removes all stored default parameters so they must be specified in subsequent function calls.
Examples
>>> handler = FPTHandler(fpt, P=P_linear, C_window=0.75) >>> handler.clear_default_params() >>> # Now P must be provided in each subsequent function call
- property fastpt
Get the underlying FASTPT instance.
- Returns:
The FASTPT instance used by this handler.
- Return type:
- generate_power_spectra(method='class', mode='single', store=True, **kwargs)[source]
Generate power spectra using the specified mode and method.
- Parameters:
method (str) – Either ‘class’ or ‘camb’
mode (str) – ‘single’, ‘bulk’, or ‘diff’
store (bool, optional) –
If True, the generated power spectra will be stored in the handler’s default_params. Note: this can only be done for single power spectrum generation.
single: generate one power spectra with the given params, which should be passed as floats or bools
bulk: generate multiple power spectra with the given params, which should be passed as lists or np arrays. If any of the params lists are shorter than the longest, they will be padded with the last value.
diff: generate multiple power spectra with the given params, which should be passed as lists or np arrays. The length of the params lists must be 1 or 3, and a power spectrum will be generated varrying each of the parameters individually while holding the central column of values constant.
**kwargs – Cosmological parameters to pass to the appropriate method
- Returns:
Power spectrum or collection of power spectra based on the mode
- Return type:
- Raises:
ValueError – If invalid method or mode is specified, or if parameters are incompatible with the selected method
Notes
For an example on how to use ‘diff’ mode, see the v4_example.py file on GitHub.
Any non specified parameters will use the default values provided by CAMB or CLASS.
- get(*terms, **override_kwargs)[source]
Get specific power spectrum terms directly.
This method provides direct access to specific power spectrum components without needing to know which FAST-PT function calculates them.
- Parameters:
- Returns:
If a single term is requested, returns that term directly. If multiple terms are requested, returns a dictionary mapping term names to their values.
- Return type:
np.array or dict
- Raises:
ValueError – If a requested term is not found or parameters are invalid
Examples
>>> handler = FPTHandler(fpt, P=P_linear, C_window=0.75) >>> P_1loop = handler.get('P_1loop') >>> ia_terms = handler.get('P_E', 'P_B')
- get_tracer(tracer_name, **override_kwargs)[source]
Get Fast-PT terms relevant to a specific tracer in CCL.
- Parameters:
- Returns:
Returns a dictionary of key-value pairs where the key is the term name and the value is the calculated term from Fast-PT.
- Return type:
- Raises:
ValueError – If a requested tracer is not found or parameters are invalid
Notes
Some terms have different names in FAST-PT than in CCL, see the “aliases” dictionary.
Examples
>>> handler = FPTHandler(fpt, P=P, C_window=0.75) >>> P_1loop = handler.get_tracer('pgm') >>> #returns Pd1d2, Pd1s2, Pd1p3 (sig3nl)
- list_available_functions()[source]
List all callable FAST-PT functions.
Prints a list of all public functions available in the FAST-PT instance.
Examples
>>> handler = FPTHandler(fpt) >>> handler.list_available_functions() ['OV', 'IA_ct', 'gI_ct', 'gI_tt', 'IA_der', ...]
- list_available_terms()[source]
List all available power spectrum terms that can be requested via get().
Prints available terms organized by the FAST-PT function that calculates them, along with any special parameter requirements.
Examples
>>> handler = FPTHandler(fpt) >>> handler.list_available_terms()
- load(file_path, load_dir=None)[source]
Load a saved output file and return it in the same format as FASTPT outputs (tuple of numpy arrays)
- Parameters:
- Returns:
A tuple of numpy arrays matching the original FASTPT function output format
- Return type:
Examples
>>> handler = FPTHandler(fpt) >>> result = handler.run('one_loop_dd', P=P_linear, save_type='txt') >>> loaded_data = handler.load('one_loop_dd_output.txt')
- static load_instance(filename, load_dir=None)[source]
Load parameters and recreate Handler and Fast-PT instances from a saved .npz file.
Loads both array and non-array parameters from a file created with save_params(). Arrays are loaded directly, while scalar values are extracted from the metadata.
- Parameters:
- Returns:
Dictionary containing all loaded parameters.
- Return type:
Notes
This is a static method and is meant to be used to create an instance of the Handler and Fast-PT.
Examples
>>> # This method is static and is meant to be called without an instance >>> newHandler = FPTHandler.load_instance('stored_params.npz') >>> # Load from specific directory >>> newHandler = FPTHandler.load_instance('custom_params', load_dir='/path/to/load') >>> # Now you can use newHandler as equivalent to the original handler that stored the parameters >>> newHandler.run('one_loop_dd')
- plot(data=None, terms=None, k=None, ax=None, title=None, log_scale=True, legend_loc='best', grid=True, style=None, colors=None, linewidth=1.5, label_map=None, fig_size=(10, 7), save_path=None, dpi=300, xlim=None, ylim=None, scale_factors=None, return_fig=False, show=True, plot_negatives=True, **override_kwargs)[source]
Create a plot of power spectrum terms.
- Parameters:
data (dict or array-like, optional) – Data to plot. Can be: - Dictionary mapping labels to arrays (direct plotting) - Result from FAST-PT function call (will be plotted directly) - None (requires ‘terms’ parameter to get data)
terms (str or list, optional) – Term name(s) to plot if data is not provided
k (array-like, optional) – k values for x-axis. If None, uses handler’s FASTPT k values
ax (matplotlib.axes.Axes, optional) – Axes to plot on. If None, creates a new figure
title (str, optional) – Plot title
log_scale (bool or tuple, optional) – Whether to use log scale. If True, both axes are log. Can provide (x_log, y_log) tuple to specify each axis
legend_loc (str, optional) – Location of legend. Default is ‘best’
grid (bool, optional) – Whether to display grid lines
style (dict or list of dict, optional) – Plotting style(s) to apply to lines. Each dict can contain matplotlib line properties (color, linestyle, marker, alpha, etc.)
colors (str or list, optional) – Color(s) for plots. If a list, cycles through colors
linewidth (float, optional) – Line width for plots
label_map (dict, optional) – Mapping from term names to display labels
fig_size (tuple, optional) – Figure size (width, height) in inches
save_path (str, optional) – Path to save figure. If None, figure is not saved
dpi (int, optional) – DPI for saved figure
xlim (tuple, optional) – (min, max) for x-axis
ylim (tuple, optional) – (min, max) for y-axis
scale_factors (dict or float, optional) – Scaling factor(s) for plotted quantities
return_fig (bool, optional) – Whether to return the figure object
show (bool, optional) – Whether to show the plot immediately
plot_negatives (bool, optional) – Whether to plot negative values with dashed lines for visibility
**override_kwargs (dict) – Additional parameters for FAST-PT function calls
- Returns:
fig – Figure object if return_fig is True
- Return type:
matplotlib.figure.Figure, optional
Examples
>>> handler = FPTHandler(fpt, P=P_linear, C_window=0.75) >>> # Basic plot from terms >>> handler.plot(terms=['P_1loop', 'P_E', 'P_B']) >>> # Plot with custom styling >>> handler.plot(terms='P_1loop', colors='red', title='1-loop SPT') >>> # Plot with style dictionaries for fine control >>> handler.plot(terms=['P_1loop', 'P_E'], style=[ ... {'color': 'red', 'linestyle': '--', 'marker': 'o', 'alpha': 0.8}, ... {'color': 'blue', 'linestyle': '-', 'linewidth': 2} ... ])
- run(function_name, save_type=None, save_dir=None, **override_kwargs)[source]
Run a FAST-PT function with validated parameters.
This method calls the specified FAST-PT function, handles parameter validation, and optionally saves the output to a file.
- Parameters:
function_name (str) – Name of the FAST-PT function to run
save_type (str, optional) – File format to save results (‘txt’, ‘csv’, or ‘json’)
save_dir (str, optional) – Directory to save results. Defaults to the class’s save_dir (self.output_dir).
**override_kwargs (dict) – Additional parameters to pass to the FAST-PT function
- Returns:
result – Result from the FAST-PT function call, typically a tuple of numpy arrays
- Return type:
- Raises:
ValueError – If the function is not found or parameter validation fails
Examples
>>> handler = FPTHandler(fpt, P=P, C_window=0.75) >>> P_1loop_result = handler.run('one_loop_dd') >>> ia_result = handler.run('IA_tt', save_type='csv')
- save_instance(filename, output_dir=None)[source]
Save parameters of this handler and Fast-PT instance to a compressed numpy .npz file.
This method saves both numpy arrays and other Python objects (strings, floats, ints, etc.) in a single file. Arrays are stored directly, while non-array values are collected in a metadata dictionary and stored as a special array.
- Parameters:
filename (str) – Path where parameters will be saved. If the path doesn’t end with ‘.npz’, the extension will be added automatically.
output_dir (str, optional) – Directory to save parameters. If None, uses default output directory. If filename already contains a directory path, output_dir is ignored.
Notes
Non-array values are stored in a special array with key ‘__metadata__’. Arrays and scalars can be freely mixed in the parameters.
Examples
>>> handler = FPTHandler(fpt, P=P_linear, C_window=0.75) >>> # Save default parameters >>> handler.save_instance('stored_params') >>> # Save to specific directory >>> handler.save_instance('stored_params', output_dir='/path/to/save')
- save_output(result, func_name, type='txt', output_dir=None)[source]
Save calculation results to a file.
- Parameters:
- Raises:
ValueError – If an invalid file type is specified
Examples
>>> handler = FPTHandler(fpt) >>> result = handler.run('one_loop_dd', P=P_linear) >>> handler.save_output(result, 'one_loop_dd', type='csv')
- update_default_params(**params)[source]
Update the default parameters used for all function calls.
- Parameters:
**params (dict) – Parameters to set as defaults
- Raises:
ValueError – If any parameters are invalid or inconsistent
Examples
>>> handler = FPTHandler(fpt) >>> handler.update_default_params(P=P_linear, C_window=0.75) >>> # Now these parameters will be used by default
- update_fastpt_instance(fastpt_instance: FASTPT)[source]
Update the FAST-PT instance used by this handler.
This method replaces the current FASTPT instance.
- Parameters:
fastpt_instance (FASTPT) – New FASTPT instance to use
- Raises:
ValueError – If the provided instance is not a valid FASTPT instance or if the k range does not match the current P parameter.
Examples
>>> k_new = np.logspace(-4, 2, 300) # Different k range >>> fpt_new = FASTPT(k_new) >>> handler.update_fastpt_instance(fpt_new)