leakagelib API documentation#
- 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 (Spectrum) – Spectrum 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.FitSettings(datas)#
Bases:
objectAn object that keeps track of the meta-parameters of a fit.
- add_background(name='bkg', det=(1, 2, 3), 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 (1, 2, 3).
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=(1, 2, 3), 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 (1, 2, 3).
obs_ids (tuple of int, optional) – Observation IDs the source should apply to. Default is None (all observations).
- add_particle_source(source, name, det=(1, 2, 3), obs_ids=None)#
Add a particle source component 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.
obs_ids (tuple of int, optional) – Observation IDs the source should apply to. Default is None (all observations).
- add_point_source(name='src', det=(1, 2, 3), 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.
obs_ids (tuple of int, optional) – Observation IDs the source should apply to. Default is (1, 2, 3).
- add_source(source, name, det=(1, 2, 3), 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.
obs_ids (tuple of int, optional) – Observation IDs the source should apply to. Default is (1, 2, 3).
- apply_circular_roi(radius)#
Provide a circular ROI centered on the origin (radius in arcseconds).
This function does NOT cut events; it only tells the fitter to expect events cut to this radius. You should cut the events yourself.
- apply_roi(roi_image)#
Provide the region of interest (ROI) to the fitter after data has been cut.
This function does NOT cut events; it only tells the fitter to expect events cut to this ROI. You should cut the events yourself.
Notes
The roi_image must have the same dimensions as source objects.
- 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_rmf=True, duty_cycle=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.
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.
- 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(datas, fit_settings, psfs=None)#
Bases:
objectPrepare the fitter.
- Parameters:
datas (list of IXPEData) – List of
IXPEDataobjects. Does not need to be binned; only the events will be used.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(fig_name=None, 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, burnin=1000, save_corner='corner.png', save_samples=None, progress=True)#
Fit using an MCMC (via the emcee 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.
burnin (int, optional) – Number of points to discard. Default is 1000.
save_corner (str or None, optional) – File path to save the corner plot. Default is “corner.png”. Set to None to skip saving. Requires the corner package.
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:
FitData
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
FitResults.parameter_namesattribute 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=101)#
Plot the image predicted by the fitter vs the data
- Parameters:
filename (string) – Name of the file to save the image to
params (array-like, optional) – Parameter array to plot. Default: the starting values
n_bins (int, optional) – Number of spatial bins to use
- class leakagelib.IXPEData(source, file_names, energy_cut=(2, 8), weight_image=False, bin=False)#
Bases:
objectA class containing the data of a single pointing and a single detector.
- det#
The detector number (1, 2, or 3).
- Type:
int
- filename#
The FITS file representing this data set.
- Type:
str
- obs_id#
The observation ID.
- Type:
str
Notes
To construct an
IXPEData, you should use theIXPEData.load_all_detectors()orIXPEData.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). To retain events, use the
IXPEData.retain()orIXPEData.retain_region()methods. Do not manually edit these fields; IXPEData stores them to increase computational speed and editing them may cause the IXPEData object to go out of sync. Exceptions are evt_times, evt_ws, evt_mus, evt_bg_chars, and evt_exposures.- offsetstuple of float
Location of the current origin in physical coordinates. Defaults to (0, 0).
Image fields#
- i, q, u, n, w2, cov_invarray-like
Images of the observation, constructed with the same pixels as the source provided upon initialization. These fields exist only if IXPEData was constructed with bin=True. To recreate these images, call the
IXPEData._bin_data()method.- pixel_centers, pixel_edgesarray-like
Centers and edges of pixels in the image.
- antirotate_events()#
Aligns the events so that up is in detector coords rather than north and saves them as evt_xs_antirot, evt_ys_antirot, evt_qs_antirot, evt_us_antirot. The original evt_xs and evt_ys and the image are unaffected.
- 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_detector_polarization()#
Get the polarization of a single IXPEdata by averaging over the entire image
- get_net_polarization()#
Get the net polarization of all the Q and U in all three detectors image.
- 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(obs_id, event_dir=None, energy_cut=(2, 8), weight_image=False, bin=False)#
Load all detectors corresponding to a specific observation ID.
- Parameters:
source (Source) – A Source object used to set the size of the IXPEData images. The actual source flux is not read, only whether the source is NN or Mom and the shape of the image. If you do not wish to bin the data, you can pass Source.no_image.
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 (None) is interpreted as event_l2 if source indicates Moments data, and event_nn if it indicates NN results.
energy_cut (tuple of float, optional) – Event energy range in keV. Default is (2, 8).
weight_image (bool, optional) – If True, weight the Q and U images by event weights.
bin (bool, optional) – If False, do not bin the data. Ignored if source was created with Source.no_image.
- Returns:
A list of IXPEData objects for all three detectors.
- Return type:
List[IXPEData]
- load_all_detectors_with_path(prepath, obs_id=None, event_dir=None, energy_cut=(2, 8), weight_image=False, bin=False)#
Load all detectors from a specific directory, without using the default directories stored in the LeakageLib settings file.
- Parameters:
source (Source) – A Source object used to set the size of the IXPEData images. The actual source flux is not read; only whether the source is NN or Mom and the shape of the image. To skip binning, pass Source.no_image.
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).
weight_image (bool, optional) – If True, weight the Q and U images by event weights.
bin (bool, optional) – If False, do not bin the data. Ignored if source was created with Source.no_image.
- 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.
- weight_nn()#
If this is an NN data set, scrap the energy-dependent modulation factor and instead treat the event-by-event weights as the modulation factor. This function will then set all the weights to one to avoid double counting them. If this is a Mom data set, this function will do nothing.
- 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
PSF.sky_cal(),PSF.ground_cal(), andPSF.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.Region(filename)#
Bases:
objectClass to store DS9 regions.
Notes
All regions are assumed to be stored in ciao format.
All coordinates must be physical
- area()#
Get the area of the region. Area is only defined for circular, elliptical, and box regions
- check_inside_absolute(x, y)#
Return True if (x, y) is inside the region
- class leakagelib.Source(image, use_nn, source_size, pixel_size, store_info=False, 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
Source.delta(). To load a Gaussian-shaped source, useSource.gaussian(). To load a uniform source, useSource.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.
store_info (bool, optional) – If True, stores source and PSF info to speed up computations. Requires manual calls to invalidate_psf and invalidate_source_polarization. Default is False.
- compute_leakage(psf, spectrum, energy_dependence=None, normalize=False)#
Get the Q and U maps for this source (unnormalized by default), given the PSF and spectrum.
- Parameters:
psf (PSF) – PSF for the detector. Sky-calibrated PSFs are recommended.
spectrum (Spectrum) – Spectrum of the data, obtainable from an IXPEData object.
energy_dependence (callable, optional) – Function specifying the energy dependence of sigma_perp and sigma_parallel. Defaults to simulation-measured dependences for NN or Mom depending on this Source.
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)
- 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(num_pixels, pixel_size, store_info=False)#
Create a Source object representing a point source.
- Parameters:
use_nn (bool) – True to use NN-reconstructed data, False for moments-reconstructed data.
num_pixels (int) – Number of pixels in the output image. Odd integer recommended.
pixel_size (float) – Width of each pixel in arcseconds.
store_info (bool, optional) – If True, stores source and PSF info to speed up computations. Requires manual calls to invalidate_psf and invalidate_source_polarization. Default is False.
- divide_by_mu(q, u, spectrum)#
Divide by the detector modulation factor to get the “true” Q and U images. You can pass in either normalized or unnormalized q and u. The spectrum is used to compute the average polarization weight.
- gaussian(num_pixels, pixel_size, sigma, store_info=False)#
Create a Gaussian-shaped Source object.
- Parameters:
use_nn (bool) – True to use NN-reconstructed data, False for moments-reconstructed data.
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.
store_info (bool, optional) – If True, stores source and PSF info to speed up computations. Requires manual calls to invalidate_psf and invalidate_source_polarization. Default is False.
- get_event_p_r_given_phi(psf, data, overwrite_mus=None, energy_dependence=None)#
Get the probability for an array of events to have their positions given their polarization.
- Parameters:
psf (PSF) – PSF for the detector. Sky-calibrated PSFs recommended.
data (IXPEData) – IXPEData object containing events. Reads evt_xs, evt_ys, evt_qs, evt_us, evt_energies. If the PSF rotation angle is < 1e-5, the antirotated versions will be read.
energy_dependence (callable, optional) – Function specifying the energy dependence of sigma_perp and sigma_parallel. Defaults to simulation-measured dependences for NN or Mom depending on this Source.
- Returns:
Probabilities for each event.
- Return type:
array-like
- invalidate_event_data()#
Invalidate the stored data concerning the events. This should be done whenever you change the event positions or the number of events
- invalidate_psf()#
Invalidate the stored data concerning the source flux. This should be done whenever you change the PSF, e.g. by blurring it
- invalidate_source_polarization()#
Invalidate the stored data concerning the source polarization. This should be done whenever you change the source polarization map
- load_file(use_nn, num_pixels=None, target_pixel_size=None, source_pixel_size=None, hduis=[1])#
Load a file (FITS or NPY), zoom to the correct scale, and return the resulting image with the number of pixels and pixel size in arcseconds.
- Parameters:
file_name (str) – Name of the file to load.
num_pixels (int) – Number of pixels to use in the output image.
target_pixel_size (float or None) – Width of each pixel in arcseconds for the returned image. None implies use the source pixel size.
source_pixel_size (float or None) – Width of each pixel in arcseconds in the current image. None implies read 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)
- no_image()#
Create an empty source for use in initializing a dataset which will not be binned
- 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_name)#
Add a source polarization to the incoming photons. The provided file must either be a fits file with Q in hdul[1] and U in hdul[2], or a numpy array of shape (i, j, 2), where the last axis contains the q and u coordinates of the polarization. This automatically calls invalidate_source_polarization
- polarize_net(stokes)#
Add uniform polarization to the entire image. This automatically calls invalidate_source_polarization
- uniform(num_pixels, pixel_size, store_info=False)#
Create a Source object representing a uniform background.
- Parameters:
use_nn (bool) – True to use NN-reconstructed data, False for moments-reconstructed data.
num_pixels (int) – Number of pixels in the output image. Odd integer recommended.
pixel_size (float) – Width of each pixel in arcseconds.
store_info (bool, optional) – If True, stores source and PSF info to speed up computations. Requires manual calls to invalidate_psf and invalidate_source_polarization. Default is False.
- class leakagelib.Spectrum(bin_centers, counts, weights)#
Bases:
object- 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.
- load()#
Load from a file
- save(f)#
Save to a file
- weighted_average(array)#
Get the event fractions in each energy bin
- 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(source, psfs, 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.