API Reference
This page contains the API reference for ixpepy’s main modules.
Core Analysis
OGIP Spectrum Analysis
IXPE OGIP Spectrum Plugin Module.
This module provides classes to load and analyze IXPE spectral data using the OGIP format. It supports Stokes I, Q, and U spectra from all three IXPE detector units (DU1, DU2, DU3) and interfaces with the 3ML analysis framework.
- class ixpepy.ixpeOGIPSpectrumLike.ixpeOGIPSpectrumLike(energy_range='2-8', caldb=None, use_poisson=True)[source]
Bases:
objectIXPE OGIP Spectrum Likelihood Manager.
This class manages multiple IXPE spectral plugins (one for each detector unit and Stokes parameter) and provides methods to load data, apply rebinning, set energy ranges, and perform joint spectral analysis.
Examples
Load IXPE data files for spectral analysis:
>>> ixpe = ixpeOGIPSpectrumLike(energy_range='2-8') >>> file_list = ['obs_det1_pha1.fits', 'obs_det1_pha1q.fits', ...] >>> ixpe.load_file_list(file_list) >>> datalist = ixpe.get_datalist()
- __init__(energy_range='2-8', caldb=None, use_poisson=True)[source]
Initialize IXPE OGIP spectrum manager.
- Parameters:
energy_range (str, optional) – Energy range for analysis (format: ‘emin-emax’ in keV). Default is ‘2-8’
caldb (str, optional) – Path to IXPE calibration database. If None, uses paths from FITS headers. Default is None
use_poisson (bool, optional) – If True, use Poisson statistics for Stokes I spectra and Gaussian for Q/U. If False, use Gaussian for all. Default is True
- from_basename(datadir, basename, suffix='_')[source]
Load IXPE data files using a basename pattern (ixpeobssim format).
Automatically constructs file paths for all 9 files (3 detector units × 3 Stokes parameters) based on a common basename. This assumes the naming convention used by ixpeobssim simulations with ‘du’ prefix.
- Parameters:
- Returns:
Plugins are added to self.plugins
- Return type:
None
Notes
This method is designed for ixpeobssim simulated data which uses ‘du’ (detector unit) naming. For real IXPE data using a different naming convention, or to specify background files, use load_file_list() directly.
Examples
For simulated files like ‘source_obs_du1_pha1.fits’, ‘source_obs_du1_pha1q.fits’:
>>> ixpe.from_basename(datadir='/data', basename='source_obs')
- load_file_list(file_list, bkg_file_list=None, name='ixpe')[source]
Load a list of IXPE PHA1 FITS files with optional background files.
- Parameters:
- Returns:
Plugins are added to self.plugins
- Return type:
None
- set_energy_range(energy_range)[source]
Set the energy range for all loaded plugins.
- Parameters:
energy_range (str) – Energy range string (format: ‘emin-emax’ in keV, e.g., ‘2-8’)
- rebin_on_source(min_number_of_counts)[source]
Rebin all spectra to have minimum counts per bin.
Uses Stokes I spectrum to determine binning, then applies the same binning to Q and U spectra for each detector unit. This ensures consistent energy bins across all Stokes parameters.
- Parameters:
min_number_of_counts (int) – Minimum number of source counts required per energy bin
- Return type:
None
Notes
The rebinning is done in two passes: 1. Rebin Stokes I spectra and save the binning scheme 2. Apply the same binning to Q and U spectra for each detector
- apply_area_correction(area_corrections)[source]
Apply effective area corrections to all detector units.
Applies detector-specific multiplicative corrections to the effective area to account for calibration uncertainties or systematic effects.
- Parameters:
area_corrections (dict) – Dictionary mapping detector unit names to correction factors. Example: {‘DU1’: 0.850, ‘DU2’: 0.800, ‘DU3’: 0.782}
Notes
The corrections are fixed (not fitted) and typically derived from calibration observations or cross-calibration with other instruments.
- fit_area_correction(model, min_value=0.5, max_value=1.2, name='ixpe', quiet=False, sim_name='')[source]
Enable fitting of effective area corrections for each detector unit.
Creates correction parameters that allow detector effective areas to be adjusted during the fit. DU1 is fixed as reference, Q/U are linked to I.
- Parameters:
model (Model) – Astromodels Model object
min_value (float, optional) – Minimum correction value. Default is 0.5
max_value (float, optional) – Maximum correction value. Default is 1.2
name (str, optional) – Base name for plugins. Default is ‘ixpe’
quiet (bool, optional) – Suppress messages. Default is False
sim_name (str, optional) – Suffix for parameter names. Default is ‘’
Notes
Must be called AFTER creating the JointLikelihood to associate model and data. The corrections are multiplicative: 1.0 = nominal area.
Examples
>>> jl = JointLikelihood(model, ixpe.get_datalist()) >>> ixpe.fit_area_correction(model, min_value=0.8, max_value=1.2) >>> jl.fit()
- get_datalist()[source]
Get a 3ML DataList containing all loaded plugins.
- Returns:
3ML DataList object with all IXPE plugins for joint analysis
- Return type:
DataList
- class ixpepy.ixpeOGIPSpectrumLike.ixpeOGIPSpectrumPlugin(name, observation, background=None, response=None, arf_file=None, spectrum_number=None, verbose=True, stokes=None, du=None)[source]
Bases:
OGIPLikeIXPE-specific OGIP spectrum plugin.
Extends the 3ML OGIPLike plugin to handle IXPE-specific features including Stokes parameter tracking and detector unit identification.
- Parameters:
name (str)
- __init__(name, observation, background=None, response=None, arf_file=None, spectrum_number=None, verbose=True, stokes=None, du=None)[source]
Initialize IXPE OGIP spectrum plugin.
- Parameters:
name (str) – Plugin name (usually format: ‘{basename}_{du}_{stokes}’)
observation (PHASpectrum) – Observation spectrum object
background (PHASpectrum, optional) – Background spectrum object. Default is None
response (str, optional) – Path to response file. Default is None
arf_file (str, optional) – Path to auxiliary response file. Default is None
spectrum_number (int, optional) – Spectrum number for PHAII files. Default is None
verbose (bool, optional) – Enable verbose output. Default is True
stokes (str) – Stokes parameter (‘I’, ‘Q’, ‘U’, or ‘V’)
du (str) – Detector unit identifier (e.g., ‘DU1’)
- Raises:
AssertionError – If stokes is not one of ‘I’, ‘Q’, ‘U’, ‘V’
Data Download
IXPE Data Download
IXPE Data Download Module.
This module provides functions to download IXPE observation data files from remote servers. It supports both XPQLT-processed files and original compressed files from the IXPE archive.
- ixpepy.io.download_ixpe_data.download_files_from_url(url, destination, filenames, chunk_size=10240)[source]
Download multiple files from a URL to a destination directory.
- Parameters:
- Returns:
List of local file paths for the downloaded files
- Return type:
- ixpepy.io.download_ixpe_data.download_obsid(obs_id, destination=None, xpqlt=True, update_db=True)[source]
Download IXPE observation data files for a given observation ID.
This function retrieves event files for all three IXPE detector units (DU1, DU2, DU3) from the XPQLT server or the original IXPE archive.
- Parameters:
obs_id (str or int) – IXPE observation ID (e.g., “01001099” or 1001099)
destination (str, optional) – Local directory where files should be saved. If None, saves to IXPE_DATA/0{obs_id}. Default is None.
xpqlt (bool, optional) – If True, download XPQLT-processed FITS files. If False, download original compressed files from the IXPE archive. Default is True.
update_db (bool, optional) – If True, update the observation database before downloading. If False, use cached database. Default is True.
- Return type:
None
- Raises:
RuntimeError – If the observation ID is not found in the database
Notes
XPQLT-processed files are recommended for most analyses as they include calibrated data products. Original files may be needed for specialized reprocessing.
Examples
Download XPQLT-processed files for observation 01001099:
>>> download_obsid("01001099")
Download original compressed files to a custom directory:
>>> download_obsid("01001099", destination="/path/to/data", xpqlt=False)
- ixpepy.io.download_ixpe_data.download_source(source_name, destination=None, xpqlt=True, update_db=True)[source]
Download IXPE observation data files for all observations of a given source.
This function retrieves event files for all observations of a specified source from the XPQLT server or the original IXPE archive. It downloads data for all three IXPE detector units (DU1, DU2, DU3) for each observation ID associated with the source.
- Parameters:
source_name (str) – Name of the astronomical source (e.g., “Crab”, “Her X-1”, “Cyg X-1”)
destination (str, optional) – Base directory where files should be saved. If None, saves each obsid to IXPE_DATA/{source_name}/0{obs_id}. Default is None.
xpqlt (bool, optional) – If True, download XPQLT-processed FITS files. If False, download original compressed files from the IXPE archive. Default is True.
update_db (bool, optional) – If True, update the source observation database before downloading. If False, use cached database. Default is True.
- Returns:
List of observation IDs that were downloaded
- Return type:
- Raises:
RuntimeError – If the source name is not found in the database
Notes
Files are organized in subdirectories by observation ID. If multiple observations exist for the same source, all will be downloaded.
Examples
Download all XPQLT-processed observations for the Crab Nebula:
>>> from ixpepy.io.download_ixpe_data import download_source >>> obsids = download_source("Crab") Found 2 observation(s) for source 'Crab' Source type: PWN RA: 83.633, Dec: 22.015 Extended: True >>> print(f"Downloaded {len(obsids)} observations: {obsids}") Downloaded 2 observations: ['1001099', '1001199']
Download original compressed files for Her X-1 to a custom directory:
>>> obsids = download_source("Her X-1", destination="/data/ixpe", xpqlt=False)
Download without updating the database (faster if recently updated):
>>> obsids = download_source("Cyg X-1", update_db=False)
XPQLT Database
XPQLT Database Download Utilities.
This module provides functions to download and cache observation databases from the XPQLT web service (https://xpqlt.com). The databases contain metadata for IXPE observations including file locations and observation parameters.
- ixpepy.utils.download_xpqlt_db.download_db(url, file_path, update=True)[source]
Download a database file from a URL if needed.
- Parameters:
- Returns:
Path to the downloaded database file
- Return type:
Notes
This function will create the directory structure if it doesn’t exist.
- ixpepy.utils.download_xpqlt_db.download_obsid_db(file_path=None, update=True)[source]
Download the IXPE observation ID database from XPQLT.
This database contains metadata for all IXPE observations including observation IDs, target names, file URLs, and observation parameters.
- Parameters:
- Returns:
Path to the downloaded database file
- Return type:
Examples
>>> db_file = download_obsid_db() >>> import json >>> with open(db_file) as f: ... obsid_db = json.load(f)
- ixpepy.utils.download_xpqlt_db.download_source_obsid_db(file_path=None, update=True)[source]
Download the IXPE source-obsid mapping database from XPQLT.
This database maps astronomical source names to their corresponding IXPE observation IDs, making it easy to find observations of specific sources.
- Parameters:
- Returns:
Path to the downloaded database file
- Return type:
Examples
>>> db_file = download_source_obsid_db() >>> import json >>> with open(db_file) as f: ... source_db = json.load(f)
Utilities
Stokes Parameters
Utility functions for Stokes parameter calculations.
This module provides functions to compute polarization properties from Stokes Q and U parameters.
- ixpepy.utils.stokes.get_polarization_angle(q, u)[source]
Calculate the polarization angle from Stokes Q and U parameters.
The polarization angle is defined as: PA = 0.5 * arctan2(U, Q)
- Parameters:
- Returns:
Polarization angle in degrees, ranging from -90 to +90 degrees
- Return type:
Notes
The polarization angle is measured from north through east (IAU convention). The factor of 0.5 comes from the fact that Stokes parameters are quadratic in the electric field components.
Examples
>>> get_polarization_angle(0.1, 0.0) 0.0 >>> get_polarization_angle(0.0, 0.1) 45.0
- ixpepy.utils.stokes.get_polarization_degree(q, u)[source]
Calculate the polarization degree from Stokes Q and U parameters.
The polarization degree is defined as: PD = sqrt(Q^2 + U^2)
- Parameters:
- Returns:
Polarization degree (fractional), ranging from 0 to 1
- Return type:
Notes
The polarization degree represents the fraction of polarized intensity relative to the total intensity. For completely unpolarized radiation, PD = 0, while for completely polarized radiation, PD = 1.
Examples
>>> get_polarization_degree(0.3, 0.4) 0.5 >>> get_polarization_degree(0.0, 0.0) 0.0
Plotting
Visualization Tools
IXPE Data Visualization Module.
This module provides plotting functions for IXPE spectral and polarimetric data, including Stokes I/Q/U spectra and Q-U plane visualizations with confidence contours.
- ixpepy.io.plotting.plot_I_spectrum(like, emin=2.0, emax=8.0, ymin=None, ymax=None, basename='ixpe')[source]
Plot the Stokes I (total intensity) spectrum for all three IXPE detector units.
- Parameters:
like (JointLikelihood or similar) – Likelihood object containing the fitted model and data
emin (float) – Minimum energy for x-axis (keV)
emax (float) – Maximum energy for x-axis (keV)
ymin (float, optional) – Minimum count rate for y-axis. Default is None (auto-scale)
ymax (float, optional) – Maximum count rate for y-axis. Default is None (auto-scale)
basename (str, optional) – Base name for the IXPE plugins. Default is ‘ixpe’
- Returns:
Figure object containing the Stokes I spectrum plot
- Return type:
- ixpepy.io.plotting.plot_QU_spectra(like, emin=2.0, emax=8.0, ymin=None, ymax=None, basename='ixpe')[source]
Plot the Stokes Q and U spectra for all three IXPE detector units.
- Parameters:
like (JointLikelihood or similar) – Likelihood object containing the fitted model and data
emin (float) – Minimum energy for x-axis (keV)
emax (float) – Maximum energy for x-axis (keV)
ymin (float, optional) – Minimum count rate for y-axis. Default is None (auto-scale)
ymax (float, optional) – Maximum count rate for y-axis. Default is None (auto-scale)
basename (str, optional) – Base name for the IXPE plugins. Default is ‘ixpe’
- Returns:
(figQ, figU) - Figure objects for Stokes Q and U spectra
- Return type:
- ixpepy.io.plotting.cdf_2d(sigma)[source]
Convert sigma confidence level to 2D cumulative distribution function value.
- ixpepy.io.plotting.plot_pdf_2d(x, y, sigma=False, ax=None)[source]
Plot 2D probability density function contours for Q-U samples.
Uses kernel density estimation to create smooth confidence contours from discrete samples.
- Parameters:
x (array-like) – X-axis values (e.g., Q samples)
y (array-like) – Y-axis values (e.g., U samples)
sigma (bool, optional) – If True, use sigma levels (1, 2, 3σ). If False, use percentage levels (50%, 90%, 99%). Default is False.
ax (matplotlib.axes.Axes, optional) – Axes object to plot on. If None, uses current axes. Default is None.
- Returns:
Contour set object
- Return type:
- ixpepy.io.plotting.plot_QU_polar(q, u, rmax=None, nbins=50, mdp_99=0, sigma=False, manual_locations=False)[source]
Create a polar plot of polarization degree vs. polarization angle.
Visualizes the posterior distribution in polar coordinates with 2D histogram and confidence contours.
- Parameters:
q (RandomVariate or similar) – Stokes Q parameter samples (normalized)
u (RandomVariate or similar) – Stokes U parameter samples (normalized)
rmax (float, optional) – Maximum radius (polarization degree) for plot. If None, auto-scales. Default is None.
nbins (int, optional) – Number of bins for 2D histogram. Default is 50.
mdp_99 (float, optional) – Minimum Detectable Polarization at 99% confidence to overlay. Default is 0 (no MDP line).
sigma (bool, optional) – If True, label contours with sigma levels. If False, use percentages. Default is False.
manual_locations (bool, optional) – If True, allows manual positioning of contour labels. Default is False.
- Returns:
Figure object containing the polar plot
- Return type:
- ixpepy.io.plotting.plot_QU(q, u, nbins=40, mdp_99=0, sigma=False, pcube=False, manual_locations=False)[source]
Create a Cartesian Q-U plane plot with confidence contours.
Visualizes the posterior distribution of Stokes Q and U parameters with 2D histogram, confidence contours, and polarization degree circles.
- Parameters:
q (RandomVariate or similar) – Stokes Q parameter samples (normalized by I)
u (RandomVariate or similar) – Stokes U parameter samples (normalized by I)
nbins (int, optional) – Number of bins for 2D histogram. Default is 40.
mdp_99 (float, optional) – Minimum Detectable Polarization at 99% confidence to overlay as a circle. Default is 0 (no MDP circle).
sigma (bool, optional) – If True, label contours with sigma levels. If False, use percentages. Default is False.
pcube (dict or False, optional) – If dict, overlay PCUBE results with keys ‘i’, ‘q’, ‘u’, ‘err’. If False, no PCUBE overlay. Default is False.
manual_locations (bool, optional) – If True, allows manual positioning of contour labels. Default is False.
- Returns:
Figure object containing the Q-U plane plot
- Return type:
Notes
The plot includes: - 2D histogram of Q-U samples (orange colormap) - Best-fit value marked with a cross - Confidence contours (50%, 90%, 99% or 1σ, 2σ, 3σ) - Polarization degree circles at 5%, 10%, 15%, … intervals - Polarization angle lines at 30° intervals - Optional MDP circle and PCUBE comparison