leakagelib API documentation¶
- class leakagelib.DataSpectrum(bin_centers, counts, weights=None)¶
Bases:
object- from_data(binning=1)¶
- from_power_law_index()¶
Load the spectrum assuming power law-distributed 2-8 keV counts. Unweighted. Useful for demonstration purposes only. In practice, use a more accurate simulation for an IXPE observation.
- get_avg_mu(use_nn)¶
Get the average of 1 over the modulation factor.
- get_avg_one_over_mu(use_nn)¶
Get the average of 1 over the modulation factor.
- get_avg_one_over_mu_squared(use_nn)¶
Get the average of 1 over the modulation factor squared.
- load()¶
Load from a file
- save(f)¶
Save to a file
- weighted_average(array)¶
Get the event fractions in each energy bin
- class leakagelib.EnergyDependence(energies, sigma_parallel2, sigma_perp2, kurtosis4, mu)¶
Bases:
objectA class that holds interpolators for the leakage parameters sigma_parallel, sigma_perp, and mu as a function of energy. Differences between detectors is not accounted for.
- constant(use_nn)¶
Assume no sigma_perp, no kurtosis, and constant energy dependence.
- Parameters:
use_mu (bool, optional) – Set to False to ignore the modulation factor. Only use this if you plan to handle the modulation factor event-by-event.
- default(use_mu=True)¶
Use the default energy dependence, depending on whether the analysis method is NN or Mom.
- Parameters:
use_nn (bool) – Set to True to use the neural net Leakage parameters and modulation factor, False for Moments.
use_mu (bool, optional) – Set to False to ignore the modulation factor. Only use this if you plan to handle the modulation factor event-by-event.
- evaluate(energies)¶
Get the leakage parameters for an array of event energies.
- Parameters:
energies (array-like) – Array of event energies in keV.
- Returns:
A tuple containing (sigma_parallels, sigma_perps, kurts).
- Return type:
tuple of (ndarray, ndarray, ndarray)
- get_params(spectrum)¶
In some cases, one really wants spectrum-weighted quantities, such as a spectrum-weighted mu, sigma_parallel, mu*sigma_parallel, etc. This function returns these quantities.
- Parameters:
spectrum (DataSpectrum) – DataSpectrum object for the data in question. Either create one directly or use the spectrum attribute of an IXPEData object.
- Returns:
Dictionary of all leakage parameters: sigma_plus, sigma_minus, k_plus, k_minus, k_cross, and mu_*.
- Return type:
dict
- lawrence_mom()¶
Get the energy-dependent functions for Moments data.
- Parameters:
use_mu (bool, optional) – Set to False to ignore the modulation factor. Only use this if you plan to handle the modulation factor event-by-event.
- lawrence_nn()¶
Get the energy-dependent functions for Neural Net data.
- Parameters:
use_mu (bool, optional) – Set to False to ignore the modulation factor. Only use this if you plan to handle the modulation factor event-by-event.
- class leakagelib.FitData(fit_settings)¶
Bases:
objectA class that handles converting between parameter values and an array that can be fed into a minimizer.
- index_to_param(index)¶
Returns the parameter name and the index of the data set it belongs to. If the parameter is global, the index will be None
- Parameters:
index (int) – The index of the parameter
- Returns:
A tuple where the first element is the parameter type and the second is the source name. None if the parameter is not associated with a source.
- Return type:
tuple of (str, str)
- length()¶
- param_to_index(param, source_name=None)¶
Return the array index of a parameter.
- Parameters:
param ({'q', 'u', 'f', 'sigma'}) – The parameter whose index will be returned.
source_name (str) – Name of the source for which the parameter index is requested. This is required for some parameters.
- Returns:
The index of the parameter in the array if it exists; otherwise, None.
- Return type:
int or None
- param_to_value(params, param, source_name=None)¶
Return the value of a parameter.
- Parameters:
params (list) – List of parameter values.
param ({'q', 'u', 'f', 'sigma'}) – The parameter whose value will be returned.
source_name (str) – Name of the source for which the parameter value is requested.
- Returns:
The value of the requested parameter.
- Return type:
float
- class leakagelib.FitResult(best_params, best_like, message, cov, fit_data, fit_props)¶
Bases:
object- burnin(burnin)¶
Remove the first few samples of an MCMC fit. This function can be called multiple times. Each new call, the previously removed samples will be added back in.
- display_corner()¶
Show a corner plot of the MCMC results
- display_samples()¶
Display the samples from an MCMC fit. This is useful for working out the appropriate burnin length to remove
- from_samples(log_likes, fit_data, fit_props)¶
Create an MCMC from MCMC samples
- Parameters:
samples (array) – Array of samples from the MCMC
log_likes (array) – Sample log likelihoods
fit_data (FitData) – FitData object used to run the fit
fit_props (FitProperties) – Fit properties
- Return type:
Returns a normal FitResult, but with samples and log likelihoods stored in the samples and log_likes fields. These can be manipulated with the burnin function and displayed with the display_corner and display_samples functions.
- get_constrained_samples(constraint, n_samples, n_iterations=100)¶
Gets samples that satisfy some constraint
- Parameters:
constraint (callable) – A function which is zero-valued along the constraint. It should receive a FitData object and array of parameters as arguments, and output a value which is zero-valued along the constraint surface. To enforce multiple constraints, have the function output an array. The function must be numpy compatible; i.e. if an array of shape (P, N) is passed, representing N parameters of dimension P, then f must return an array of size N for 1 constraint, or (C, N) where C is the number of constraints. A uniform prior is automatically enforced.
n_samples (int) – Number of samples to use
- Return type:
array
The constrained samples
- get_pd_pa(tag='src')¶
Get the polarization degree and polarization angle for a source
- Parameters:
tag (str, optional) – Name of the source
- Returns:
The PD, EVPA, PD uncertainty, and EVPA uncertainty. Angles are in radians.
- Return type:
tuple (float, float, float, float)
- get_pdfs(params, constraint, bins=50, frac_err=0.01)¶
Gets the PDFs of some parameters given constraints.
- Parameters:
params (callable or list of callable) – A function which takes in the Stokes coefficients and returns the parameter for which a PDF is desired. If a list is provided, multiple PDFs will be returned. Each function should receive a FitData object and array of parameters as arguments, and output a scalar.
constraint (callable or list of callable) – A function which is zero-valued along the constraint. It should receive a FitData object and array of parameters as arguments, and output a value which is zero-valued along the constraint surface. To enforce multiple constraints, have the function output an array. The function must be numpy compatible; i.e. if an array of shape (P, N) is passed, representing N parameters of dimension P, then f must return an array of size N for 1 constraint, or (C, N) where C is the number of constraints. A uniform prior is automatically enforced.
bins (int, list of int, array, or list of array.) – If an integer, number of bins to use in the parameter PDF. If an array, edges of the bins for each PDF. Provide a list to set the bins for each variable.
frac_err (int) – Anticipated fractional error in the average bin. (To be specific, the algorithm will use 1/frac_err**2 samples per bin on average)
- Return type:
(array, array) or (list of array, list of array)
Returns the bin edges and PDF values of each parameter.
- get_statistics(params, constraint, frac_err=0.005)¶
Gets the PDFs of some parameters given constraints.
- Parameters:
params (callable or list of callable) – A function which takes in the Stokes coefficients and returns the parameter for which a PDF is desired. If a list is provided, multiple PDFs will be returned. Each function should receive a FitData object and array of parameters as arguments, and output a scalar.
constraint (callable or list of callable) – A function which is zero-valued along the constraint. It should receive a FitData object and array of parameters as arguments, and output a value which is zero-valued along the constraint surface. To enforce multiple constraints, have the function output an array. The function must be numpy compatible; i.e. if an array of shape (P, N) is passed, representing N parameters of dimension P, then f must return an array of size N for 1 constraint, or (C, N) where C is the number of constraints. A uniform prior is automatically enforced.
frac_err (int) – Anticipated fractional error of the results (To be specific, the algorithm will use 1/frac_err**2 samples)
- Return type:
array, matrix
The parameter means and covariance matrix subject to the constraint
- get_uncertainty_information(best_params, cov)¶
- sample(n_samples)¶
Generate samples from this fit
- Parameters:
n_samples (int) – Number of samples to generate
- Return type:
array
Array of shape (P, n_samples) where P is the dimensionality of the fit. The samples are stored in the same order as the fit_result.parameter_names array.
- class leakagelib.FitSettings(datas)¶
Bases:
objectAn object that keeps track of the meta-parameters of a fit.
- add_background(name='bkg', det=None, obs_ids=None)¶
Add a uniform, polarized background to the fit.
- Parameters:
name (str, optional) – Name of the source. Default is “bkg”.
det (tuple of int, optional) – Detectors the source should apply to. Default is None (all detectors)
obs_ids (tuple of int, optional) – Observation IDs the source should apply to. Default is None (all observations).
Notes
To add an independent background to each detector, add three background sources and pass det=1, det=2, det=3 for each, with different names.
The shape of the background image is set to the same shape as the first source object added to the fit settings. If no source exists, pixel width is set to the PSF native size of 2.9729 arcsec and number of pixels is the largest radius of events in the data set.
- add_param(name, initial_value=0, bounds=(None, None), num_diff_step=0.001)¶
Add a parameter for the fitter. Only use after set_model_fn has been called.
- Parameters:
name (str) – Parameter name.
initial_value (float, optional) – Initial value for the fitter. Default is 0.
bounds (tuple of (float, float) or None, optional) – Bounds for the parameter. Default is no bounds.
num_diff_step (float, optional) – Step size used for numerical computation of uncertainties.
- add_particle_background(name='pbkg', det=None, obs_ids=None)¶
Add a uniform particle background component to the fit.
- Parameters:
name (str, optional) – Name of the source. Default is “pbkg”.
det (tuple of int, optional) – Detectors the source should apply to. Default is None (all detectors)
obs_ids (tuple of int, optional) – Observation IDs the source should apply to. Default is None (all observations).
- add_point_source(name='src', det=None, obs_ids=None)¶
Add a point source to the fit.
- Parameters:
name (str, optional) – Name of the source. Default is “src”.
det (tuple of int, optional) – Detectors the source should apply to. Default is None (all detectors)
obs_ids (tuple of int, optional) – Observation IDs the source should apply to. Default is None (all observations).
- add_source(source, name, det=None, obs_ids=None)¶
Add an extended source to the fit.
- Parameters:
source (Source) – Source object containing the flux map.
name (str) – Name of the source.
det (tuple of int, optional) – Detectors the source should apply to. Default is None (all detectors)
obs_ids (tuple of int, optional) – Observation IDs the source should apply to. Default is None (all observations).
- apply_circular_roi(radius)¶
Provide a circular ROI centered on the origin (radius in arcseconds).
- apply_roi(roi_image)¶
Provide the region of interest (ROI) to the fitter after data has been cut.
Notes
The roi_image must have the same dimensions as source objects. If a source with a different size is already added to the fit, an error will be thrown. If those pre-loaded sources are point sources or background, solve this problem by simply applying the ROI first. If they are sources you created, then you need to make sure your sources and background have the same shape and pixel sizes.
- apply_roi_cut(region, exclude=False)¶
Apply a region to the ROI. If the ROI is already created, this region will be and-ed with the existing ROI (that is, the final ROI will be the pixels which were already inside the previous ROI AND satisfy this region constraint).
- Parameters:
region (str) – Path to the region file
exclude (bool, optional) – Set to False to limit the ROI to this region. Set to True to exclude this region from the ROI. Default: false.
- fit_psf_sigma()¶
Fit a blur parameter, which is a Gaussian with sigma equal to blur convolved with the PSF to better match the image.
- fix_flux(source_name, flux)¶
Fix the flux of a source. Flux units are arbitrary.
- Parameters:
source_name (str) – Name of the source.
flux (float) – Flux of the source.
Notes
Fixing a single source is necessary to set the flux scale. Fixing multiple sources fixes relative luminosities. The fitter assumes the true flux is between 0 and 100, so you should set your fluxes accordingly.
- fix_psf_sigma(psf_sigma)¶
Fix the psf blur sigma
- fix_qu(source_name, qu)¶
Fix the Q and U values of a source.
- Parameters:
source_name (str) – Name of the source.
qu (tuple of float or None) – Tuple of Stokes coefficients to fix. Pass None to free the polarization.
- get_n_sources()¶
Returns the number of sources that have been added to the fitter.
- set_initial_flux(source_name, flux)¶
Set the initial guess for the flux of a source.
- Parameters:
source_name (str) – Name of the source.
flux (float) – Initial flux value.
- set_initial_qu(source_name, qu)¶
Set the initial guess for Q and U of a source.
- Parameters:
source_name (str) – Name of the source.
qu (tuple of float or None) – Initial guess of Stokes coefficients. Pass None to leave free.
- set_lightcurve(source_name, lightcurve, duty_cycle=None)¶
Set a light curve for a source. Weights are assigned by running the light curve function on all event times.
- Parameters:
source_name (str) – Name of the source to assign time weights.
lightcurve (callable) – Function taking a time scalar or array and returning a weight scalar or array.
duty_cycle (callable, optional) – Fraction of data to distribute over time. Default is uniform over the data range. If a contiguous or no time cut was applied, the default may be used.
- set_model_fn(source_name, model_fn)¶
Set a polarization model for a source with fittable parameters.
- Parameters:
source_name (str) – Name of the source to apply the polarization model.
model_fn (callable) – Function returning (q, u) from a polarization model. It takes three arguments: event time, FitData object, and parameter array. Use FitData.param_to_value to access parameter values. Additional parameters can be added with FitSettings.add_param.
- set_spectrum(source_name, spectrum, use_arf=True, use_rmf=True, use_vignetting=False, duty_cycle=None, irf_name=None)¶
Set a spectrum for a source. Weights are assigned by running the spectrum function on all event energies.
- Parameters:
source_name (str) – Name of the source to assign spectral weights.
spectrum (callable) – Function taking an energy scalar or array and returning a weight scalar or array.
use_arf (bool) – Set to False to not apply IXPE’s ARF. When applied, the ARF of detector 1 is used (the ARF difference is quite small between detectors) Default: True. The ARF is loaded by IXPEobssim.
use_rmf (bool) – Set to False to not apply IXPE’s RMF.
irf_name (str, optional) – IXPEobssim’s name for the ARF to be used. IXPEobssim’s default will be used when not provided.
duty_cycle (callable, optional) – Fraction of data to distribute over energy. Default is uniform over the data range. If a contiguous energy cut was applied, the default may be used.
use_vignetting (bool) – Set to True to use IXPEobssim’s vignetting function to model vignetting across the detector. Default: False
- set_sweep(source_name, sweep)¶
Set a polarization sweep model for a source.
- Parameters:
source_name (str) – Name of the source to apply the sweep model.
sweep (callable) – Function taking event time(s) and returning (q, u) for a normalized polarization model. A fit will determine a global PA offset and PD.
- class leakagelib.Fitter(fit_settings, psfs=None)¶
Bases:
objectPrepare the fitter.
- Parameters:
fit_settings (FitSettings) – FitSettings object containing the sources to be fitted.
psfs (list of PSF, optional) – List of three PSF objects (ordered DU 1, 2, 3) if you wish to alter the PSFs. Default is None, which uses the Dinsmore & Romani 2023 PSFs.
- Returns:
A Fitter object.
- Return type:
Notes
It is advisable to first center your data and retain it to a large circular aperture.
- display_sources(data_pixel_size=None)¶
Display the sources for debugging purposes
- Parameters:
fig_name (str, optional) – Filename of the figure to be saved. Leave blank to return the figure object instead.
data_pixel_size (float, optional) – Size of the spatial bins in arcseconds to use when displaying the data. Leave blank to use the native PSF pixel size.
- Return type:
Returns the figure object if fig_name was None, otherwise returns None.
- fit(method='nelder-mead')¶
Fit analytically
- Parameters:
method (str, optional) – scipy.optimize.minimize method fit method. Default is Nelder-Mead.
- fit_mcmc(n_walkers=16, n_iter=5000, save_samples=None, progress=True)¶
Fit using an MCMC (via the emcee package). You must install emcee and corner to use this package.
- Parameters:
n_walkers (int, optional) – Number of walkers to use for the MCMC. Default is 16.
n_iter (int, optional) – Number of iterations to run the MCMC for. Default is 5000.
save_samples (str or None, optional) – File path to save the MCMC samples in h5 format. Recommended for advanced analysis. Default is None. WARNING: emcee appends to the file if it exists; delete first if you wish to redo a run.
progress (bool, optional) – Whether to show the MCMC progress bar. Default is True.
- Returns:
Object containing the results of the fit. The covariance matrix in FitData is set to the covariance of the parameters.
- Return type:
Notes
For detailed manipulation or custom corner plots, use save_samples. You can then discard the FitData object and operate on the saved samples.
- log_prob(params, prior=True, return_array=False)¶
Get the log posterior of the Fitter (log_like + log_prior).
- Parameters:
params (array_like) – List of parameters. If you are calling this function manually, you should order the parameters in the same order as the :attr:`leakagelib.FitResult.parameter_names` attribute of the fit result.
prior (bool) – set to True to include the priors, which are all finite uniform.
return_array (bool) – set to True to return the log posteriors of each event as an array, instead of the summed log posterior.
- plot(params=None, n_bins=100)¶
Plot the image predicted by the fitter vs the data
- Parameters:
params (array-like, optional) – Parameter array to plot. Default: the starting values
n_bins (int, optional) – Number of spatial bins to use
- Return type:
The matplotlib Figure
- class leakagelib.IXPEData(file_names)¶
Bases:
objectA class containing the data of a single pointing and a single detector.
Notes
To construct an :class:`leakagelib.IXPEData`, you should use the :meth:`leakagelib.IXPEData.load_all_detectors` or :meth:`leakagelib.IXPEData.load_all_detectors_with_path` functions, or this constructor.
Event fields¶
- evt_xs, evt_ys, evt_qs, evt_us, evt_energies, evt_pis, evt_times, evt_ws, evt_mus, evt_bg_chars, evt_exposuresarray-like
Properties of the individual events. Positions are measured in arcseconds. q and u are the IXPE-standard 2cos(psi) and 2sin(psi). Energies are measured in keV. Times are measured in seconds since MJDREF. To retain events, use the :meth:`leakagelib.IXPEData.retain` or :meth:`leakagelib.IXPEData.retain_region` methods.
- offsetstuple of float
Location of the current origin in physical coordinates. Defaults to (0, 0).
Notes
Do not manually edit the evt_xs, evt_ys, evt_qs, evt_us, evt_pis, or evt_energies fields. IXPEData stores them to increase computational speed and editing them may cause the IXPEData object to go out of sync.
- centroid_center()¶
Recenter the dataset such that the event centroid is at (0, 0)
- explicit_center(x, y)¶
Recenter the dataset by offsets x, y in pixels
- get_antirotation_matrix()¶
Get a 2D rotation matrix which reverses the detector’s rotation
- get_particle_flux_estimate()¶
Estimate the fraction of events in the dataset that are particles. This works by performing a mini-fit, neglecting all spatial and polarization information and just maximizing the likelihood for the particle flux given the observed particle characters.
- get_stokes_antirotation_matrix()¶
Get a 2D rotation matrix which reverses the stokes’s rotation
- iterative_centroid_center()¶
Recenter the dataset such that the centroid of the core events is in the center. Do this by iteratively zooming in, so that the final center is set by the core of the PSF, not events in the wings. Yields more accurate results.
- load_all_detectors(event_dir='event_l2')¶
Load all detectors corresponding to a specific observation ID.
- Parameters:
obs_id (str or None, optional) – The observation ID to load. If None, loads whatever data is pointed to by prepath.
event_dir (str or None, optional) – Name of the directory containing the event files. Default is event_l2
energy_cut (tuple of float, optional) – Event energy range in keV. Default is (2, 8).
- Returns:
A list of IXPEData objects for all three detectors.
- Return type:
List[IXPEData]
- load_all_detectors_with_path(obs_id=None, event_dir='event_l2')¶
Load all detectors from a specific directory, without using the default directories stored in the LeakageLib settings file.
- Parameters:
prepath (str, optional) – If obs_id is not specified, prepath points to the folder containing the data for this observation. If obs_id is specified, prepath should point to the superfolder containing the observation folder, which is assumed to be named obs_id.
obs_id (str or None, optional) – Observation ID to load. If None, loads data pointed to by prepath.
event_dir (str or None, optional) – Directory containing event files. Default (None) is interpreted as event_l2 for Moments data, or event_nn for NN results, based on source.
energy_cut (tuple of float, optional) – Event energy range in keV. Default is (2, 8).
- Returns:
Returns a list of IXPEData objects for all three detectors.
- Return type:
List[IXPEData]
- load_expmap(filename=None, offset=(0, 0))¶
Load the exposure map and evaluate it for every pixel in the image.
- Parameters:
filename (str, optional) – Path to the exposure map. If None, the map is assumed to lie in the auxil folder, which is expected to be in the same directory as the hk and event_l2 folders.
offset (tuple of float, optional) – Exposure map offset in arcseconds.
Notes
This function should not be run after the image has been centered.
- retain(mask)¶
Retain all events according to a boolean mask, removing the rest.
- Parameters:
mask (array-like of bool) – Mask where True indicates the event should be kept.
- retain_region(regfile, exclude=False)¶
Cut all events according to a region file.
- Parameters:
regfile (str) – Region file containing a single region, CIAO formatted, in physical coordinates.
exclude (bool, optional) – If True, all events in the region will be removed. Otherwise, they will be kept.
- Returns:
The resulting region object.
- Return type:
Notes
Uses an approximate conversion between xy and RA/Dec, which may be slightly inaccurate off-axis.
- class leakagelib.PSF(image, current_pixel_width, blur_width, source, rotation, detector, clip=False)¶
Bases:
objectStores the PSF of the telescope for a given detector. Don’t use this constructor; use the :meth:`leakagelib.PSF.sky_cal`, :meth:`leakagelib.PSF.ground_cal`, and :meth:`leakagelib.PSF.obssim` functions to load specific PSFs.
- blur(sigma)¶
Blur the PSF by a Gaussian
- Parameters:
sigma (float) – Standard deviation (arcsec).
- blur_custom_kernel(kernel)¶
Blur the PSF by custom kernel
- Parameters:
kernel (array-like) – The kernel should be a 2d array with pixels assumed to be the same size as this PSF’s pixels. The width of the sky calibrated pixels is 2.9729
- clip(new_width)¶
Clip the PSF to a new width
- Parameters:
new_width (int) – Width of new image in pixels
- ground_cal(source, rotation, ground_blur=2, clip=True)¶
Load the ground-calibrated PSFs.
- Parameters:
detector_index ({1, 2, 3}) – Detector number: 1 for DU1, 2 for DU2, 3 for DU3.
source (Source) – Source object used to set the width of the PSF.
rotation (float) – Angle in radians to rotate the PSF into the detector’s frame.
ground_blur (float, optional) – Amount to blur the ground PSFs. Default is a manually tuned value to match leakage patterns.
- Returns:
PSF – The PSF of the specified detector.
- Return type:
leakagelib.PSF
Notes
The ground calibrated PSFs do not perform as well as the sky-calibrated one.
- obssim(source, rotation, obssim_blur=0, clip=True)¶
Load the IXPEobssim PSFs, which are symmetric. Requires IXPEobssim to be installed.
- Parameters:
detector_index ({1, 2, 3}) – Detector number: 1 for DU1, 2 for DU2, 3 for DU3.
source (Source) – Source object used to set the width of the PSF.
rotation (float) – Angle in radians to rotate the PSF into the detector’s frame.
ground_blur (float, optional) – Amount to blur the ground PSFs. Default is a manually tuned value to match leakage patterns.
- Returns:
PSF – The PSF of the specified detector.
- Return type:
leakagelib.PSF
Notes
These circular PSFs do not perform as well as the sky-calibrated one.
- save(directory, header=None)¶
Save this PSF to a new file. The filename will be PSF_MMA{det}
- sky_cal(source, rotation, psf_origin='merge-nn', clip=True)¶
Load the sky-calibrated PSFs.
- Parameters:
detector ({1, 2, 3}) – Detector number: 1 for DU1, 2 for DU2, 3 for DU3.
source (Source) – Source object used to set the width of the PSF.
rotation (float) – Angle in radians to rotate the PSF into the detector’s frame.
psf_origin (str) – Name of the sky-calibrated PSF to use.
- Returns:
The PSF of the specified detector.
- Return type:
- class leakagelib.PSFSourceCombo(source, psf, use_nn=False)¶
Bases:
objectCarries preprocessed data for a specific psf, source, and data set
- blur_psf(sigma)¶
- compute_leakage(spectrum, normalize=False)¶
Get the Q and U maps for this source (unnormalized by default), given the PSF and spectrum.
- Parameters:
spectrum (DataSpectrum) – Spectrum of the data. You can create this from an IXPEData object with DataSpectrum.from_data.
normalize (bool, optional) – If True, return normalized Stokes q and u maps. Default is False.
- Returns:
Three images, i, q, u, of leakage patterns.
- Return type:
tuple (array-like, array-like, array-like)
- get_log_prob(q, u)¶
- polarize_net(qu)¶
- class leakagelib.Region(filename, assert_format=None)¶
Bases:
objectClass to store CIAO-format regions. Either fk5 or physical coordinates are allowed.
- Parameters:
filename (str) – Name of the region file
assert_format (str, optional) – Either “fk5” or “image”. If this variable is set, any region which is not of format assert_format will throw an error. Default: None.
- area()¶
- contains(x, y)¶
Check if the coordinate x, y is contained in the region. If the region is physical-format, x and y should be in units of pixels. If it’s in fk5 format, the units should be degrees.
- class leakagelib.Source(image, pixel_size, is_point_source=False, is_uniform=False)¶
Bases:
objectLoad a Source object from a 2D array. If you want to load a point source, use :meth:`leakagelib.Source.delta`. To load a Gaussian-shaped source, use :meth:`leakagelib.Source.gaussian`. To load a uniform source, use :meth:`leakagelib.Source.uniform`.
- Parameters:
image (ndarray) – Input flux image.
source_size (int) – Number of pixels in the output Source object.
pixel_size (float) – Width of each pixel in arcseconds.
hduis (int) – HDU index to take the source out of. (Default: 0)
- convolve_psf(psf)¶
Convolve this source image with the PSF and return the image. The provided PSF must be constructed with this source object.
- delta(pixel_size)¶
Create a Source object representing a point source.
- Parameters:
num_pixels (int) – Number of pixels in the output image. Odd integer recommended.
pixel_size (float) – Width of each pixel in arcseconds.
- gaussian(pixel_size, sigma)¶
Create a Gaussian-shaped Source object.
- Parameters:
num_pixels (int) – Number of pixels in the output image. Odd integer recommended.
pixel_size (float) – Width of each pixel in arcseconds.
sigma (float) – Standard deviation of the Gaussian in arcseconds.
- load_file(num_pixels=None, target_pixel_size=None, hdui=0)¶
Load a FITS file, zoom to the correct scale, and return the resulting image with the number of p ixels and pixel size in arcseconds.
- Parameters:
file_name (str) – Name of the file to load.
num_pixels (int, optional) – Number of pixels to use in the output image. If not provided, the number will be loaded from the file
target_pixel_size (float, optional) – Width of each pixel in arcseconds for the returned image. If not provided, the number will be loaded from the file
hduis (list of int) – HDU indices of the images to load.
- Returns:
images: list of loaded and scaled images
num_pixels: width of the image(s)
target_pixel_size: width of each pixel in arcseconds
- Return type:
tuple of (list of ndarray, int, float)
- polarize_array(qu_map)¶
Add a source polarization to the incoming photons. The provided array must have shape (2 ,i, j), where the last axis contains the q and u coordinates of the polarization. This automatically calls invalidate_source_polarization
- polarize_file(file_names)¶
Add a source polarization to the incoming photons.
- Parameters:
filenames ((str, str)) – A list of files containing normalized q and u maps.
- polarize_net(stokes)¶
Add uniform polarization to the entire image. This automatically calls invalidate_source_polarization
- uniform(pixel_size)¶
Create a Source object representing a uniform background.
- Parameters:
num_pixels (int) – Number of pixels in the output image. Odd integer recommended.
pixel_size (float) – Width of each pixel in arcseconds.
- leakagelib.get_mom_modf(energies)¶
Get the modulation factor at certain energies for Moments data
- Parameters:
energies (array-like) – Array of energies in keV
- Returns:
Modulation factors from the IXPEobssim load_modf function with ixpe:obssim:v12 calibration, averaged over all three detectors.
- Return type:
array-like
- leakagelib.get_nn_modf(energies)¶
Get the modulation factor at certain energies for NN data
- Parameters:
energies (array-like) – Array of energies in keV
- Returns:
Modulation factors measured by Jack Dinsmore from simulations generated by A. Lawrence Peirson in 2022 and analyzed with his neural net
- Return type:
array-like
Notes
Energy dependent modulation factors do not take full advantage of the NN analysis. It is better to use the per-event modulation factors, W_NN, if at all possible. Use the leakagelib.IXPEData.weight_nn function to use these weights.
ps_fit subpackage¶
leakagelib.extended module¶
- leakagelib.extended.fit_extended(combos, spectrum, is_obs, qs_obs, us_obs, initial_source_pol=None, inertia=None, num_iter=5000, max_rate=0.01, report_frequency=50, regularize_coeff=1, energy_dependence=None)¶
Fit for the source Q and U given an observed Q and U. The resulting source Q and U are stored in self.q_map and self.u_map.
- Parameters:
source (Source) – The Source object containing the resolved I flux. Any source polarization stored in the object is ignored.
psf (list of PSF) – List of PSFs for each detector.
spectrum (Spectrum) – The Spectrum object of the source.
is_obs (list of ndarray) – Observed I maps for each detector.
qs_obs (list of ndarray) – Observed q (normalized) maps for each detector.
us_obs (list of ndarray) – Observed u (normalized) maps for each detector.
initial_source_pol (ndarray, optional) – Array to initialize the gradient descent method. If None, the observed polarization in DU1 is used.
inertia (ndarray, optional) – Inertia map for gradient descent. High inertia reduces the step size in a pixel. If None, inertia is set to the square root of the number of counts.
num_iter (int) – Number of iterations to perform.
max_rate (float) – Maximum gradient descent rate at the beginning.
report_frequency (int or None, optional) – Frequency at which to save a snapshot of the algorithm’s state. None for no snapshots.
regularize_coeff (float, optional) – Strength of the regularization term. Zero disables regularization.
- Returns:
Tuple containing (q_map, u_map, animation). If report_frequency was None, animation is None.
- Return type:
tuple of (ndarray, ndarray, matplotlib.animation.Animation or None)
leakagelib.funcs module¶
- leakagelib.funcs.integrate_zoom(image, frac, force_odd=False)¶
Zoom by integrating over the original pixels. Most suitable for zooming out.
- Parameters:
frac (float) – Zoom fraction.
force_odd (bool, optional) – If True, round the image dimensions to an odd number of pixels.
- leakagelib.funcs.integrate_zoom_unvectorized(image, frac, force_odd=False)¶
Zoom by integrating over the original pixels. Not vectorized and very slow. Use integrate_zoom instead for efficiency.
- Parameters:
frac (float) – Zoom fraction.
force_odd (bool, optional) – If True, round the image dimensions to an odd number of pixels.
- leakagelib.funcs.interpolate_zoom(image, frac, force_odd=False)¶
Zoom by linearly interpolating between known pixels to compute new pixels. Most suitable for zooming in.
- Parameters:
frac (float) – Zoom fraction.
force_odd (bool, optional) – If True, round the image dimensions to an odd number of pixels.
- leakagelib.funcs.super_zoom(image, frac, force_odd=False)¶
Interpolate zoom when zooming in, integrate zoom when zooming out. Zooming is centered and recommended for general use.
- Parameters:
frac (float) – Zoom fraction.
force_odd (bool, optional) – If True, round the image dimensions to an odd number of pixels.