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: object

IXPE 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.

detector_stokes

Mapping from plugin name to (detector_unit, stokes_parameter) tuple

Type:

dict

plugins

List of ixpeOGIPSpectrumPlugin instances

Type:

list

use_poisson

Whether to use Poisson statistics for Stokes I spectra

Type:

bool

energy_range

Energy range for analysis (format: ‘emin-emax’ in keV)

Type:

str

caldb

Path to IXPE calibration database

Type:

str or None

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:
  • datadir (str) – Directory containing the IXPE data files

  • basename (str) – Base name of the observation files (without detector/Stokes suffix)

  • suffix (str, optional) – Separator between basename and ‘pha1’. Default is ‘_’

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:
  • file_list (list of str) – List of source spectrum file paths

  • bkg_file_list (list of str, optional) – List of background spectrum file paths. Must match length of file_list if provided. Default is None (no background)

  • name (str, optional) – Base name for plugin identification. Default is ‘ixpe’

Returns:

Plugins are added to self.plugins

Return type:

None

get_pha_spectrum(file_path, name='ixpe')[source]
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

get_number_of_data_points()[source]

Get the total number of data points across all plugins.

Returns:

Total number of active energy bins summed over all plugins

Return type:

int

get_irfs(hdr)[source]
get_simulated_dataset(model)[source]
class ixpepy.ixpeOGIPSpectrumLike.ixpeOGIPSpectrumPlugin(name, observation, background=None, response=None, arf_file=None, spectrum_number=None, verbose=True, stokes=None, du=None)[source]

Bases: OGIPLike

IXPE-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)

_stokes

Stokes parameter (‘I’, ‘Q’, ‘U’, or ‘V’)

Type:

str

_du

Detector unit identifier (e.g., ‘DU1’, ‘DU2’, ‘DU3’)

Type:

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’

get_simulated_dataset(name)[source]

Generate a simulated dataset based on the current model.

Parameters:

name (str) – Name for the simulated dataset

Returns:

New plugin instance with simulated data

Return type:

ixpeOGIPSpectrumPlugin

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:
  • url (str) – Base URL where the files are located (should end with /)

  • destination (str) – Local directory path where files will be saved

  • filenames (list of str) – List of filenames to download from the URL

  • chunk_size (int, optional) – Size of chunks for streaming download (default: 10KB)

Returns:

List of local file paths for the downloaded files

Return type:

list of str

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:

list of str

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:
  • url (str) – URL of the database to download

  • file_path (str) – Local file path where the database should be saved

  • update (bool, optional) – If True, download even if file exists. If False, only download if file doesn’t exist. Default is True.

Returns:

Path to the downloaded database file

Return type:

str

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:
  • file_path (str, optional) – Custom path to save the database. If None, saves to the default location in the ixpepy package directory. Default is None.

  • update (bool, optional) – If True, download even if file exists. If False, only download if file doesn’t exist. Default is True.

Returns:

Path to the downloaded database file

Return type:

str

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:
  • file_path (str, optional) – Custom path to save the database. If None, saves to the default location in the ixpepy package directory. Default is None.

  • update (bool, optional) – If True, download even if file exists. If False, only download if file doesn’t exist. Default is True.

Returns:

Path to the downloaded database file

Return type:

str

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:
  • q (float or array-like) – Stokes Q parameter (normalized by I)

  • u (float or array-like) – Stokes U parameter (normalized by I)

Returns:

Polarization angle in degrees, ranging from -90 to +90 degrees

Return type:

float or numpy.ndarray

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:
  • q (float or array-like) – Stokes Q parameter (normalized by I)

  • u (float or array-like) – Stokes U parameter (normalized by I)

Returns:

Polarization degree (fractional), ranging from 0 to 1

Return type:

float or numpy.ndarray

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:

matplotlib.figure.Figure

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:

tuple of matplotlib.figure.Figure

ixpepy.io.plotting.cdf_2d(sigma)[source]

Convert sigma confidence level to 2D cumulative distribution function value.

Parameters:

sigma (float) – Confidence level in sigmas (e.g., 1, 2, 3)

Returns:

CDF value corresponding to the sigma level

Return type:

float

ixpepy.io.plotting.fmt(x)[source]

Format contour level value as sigma string.

Parameters:

x (float) – CDF value

Returns:

Formatted string with sigma symbol

Return type:

str

ixpepy.io.plotting.fmt_s(x)[source]

Format contour level value as sigma string (alternative).

Parameters:

x (float) – CDF value

Returns:

Formatted string with sigma symbol

Return type:

str

ixpepy.io.plotting.fmt_p(x)[source]

Format contour level value as percentage string.

Parameters:

x (float) – CDF value (between 0 and 1)

Returns:

Formatted percentage string

Return type:

str

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:

matplotlib.contour.QuadContourSet

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:

matplotlib.figure.Figure

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:

matplotlib.figure.Figure

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