PastraStack
Python tools for aligning astronomical FITS cubes, with one exposure per layer. PastraStack is a working name.
The stack() pipeline aligns and ranks exposures, saves the best 5% and all
accepted exposures, and supports arbitrary percentile selections afterwards.
The lower-level align() API remains available.
Stack, plot, and access FITS files
from pastrastack import stack, pastraPlot, StackResult
result = stack("observation.fits")
pastraPlot(result.lucky_image) # Best 5% of accepted exposures
pastraPlot(result.group["43"]) # Best 43%, using the existing aligned cache
pastraPlot(result.group["10-20"]) # Only ranks between 10% and 20%
pastraPlot(result.all_image) # All accepted exposures
pixels = result.lucky_image.data # NumPy array
fits_path = result.lucky_image.path
print(result.output_dir)
print(result.diagnostics) # Includes rejected frames and reasons
# In a later session; the original cube is no longer needed:
result = StackResult.open("path/to/saved_output_folder")
pastraPlot(result.group["43"])
Use the lowercase import name pastrastack. result.group["luckyimage"] is
also an alias for result.lucky_image. Every requested stack is saved as FITS
and reused on subsequent access. Percentage boundaries are ceil(N*p/100),
where N is the number of accepted exposures: the best 5% includes at least one
frame, adjacent ranges never overlap, and an empty range raises ValueError.
An all-frame result includes every accepted exposure; it does not force
uncertain alignments into the mean. Original zero-based indices are preserved.
stack() defaults to translation-only local-core registration:
- Pick a sharp, usable reference from up to 32 evenly spaced preview frames.
reference_index=overrides that choice using an original cube index. - Use median-filtered whole-image correlation to track the reference star.
- In a small region around its predicted position, correlate with a narrow Gaussian template and refine the response maximum to subpixel precision.
- Reject low signal, ambiguous competing cores, isolated spikes, incomplete photometry apertures, and weak coarse correlations. Keep rejection reasons.
- Rank accepted frames by background-subtracted peak divided by aperture flux.
- Interpolate each accepted original exposure once, then average selected exposures with equal input exposure weights. Pixel validity weights exclude missing data. The optional Drizzle method replaces bilinear interpolation with direct pixel-drop overlap weighting. All selections share the full union canvas; there is no trimming.
The registration Gaussian is a matching kernel, not a theoretical telescope
PSF. Its width, search radius, aperture radius, and confidence thresholds are
configurable starting values, not instrument calibrations. Quality and alignment
confidence are separate diagnostic columns. No automatic rotation fit is attempted
from speckles within one star. For a field with enough distinct stars, explicitly
use AlignmentConfig(model="rigid") to fit rotation and translation instead.
That model uses the multi-star centroid fit described below.
from pastrastack import AlignmentConfig, CoreConfig
result = stack(
"observation.fits",
config=AlignmentConfig(
model="core",
core=CoreConfig(search_radius=8, aperture_radius=20, template_sigma=1),
),
)
CoreConfig.reference_xy=(x, y) can identify the intended star in reference
coordinates. The default uses the brightest detected source. Apertures should
contain that star's light without including companions; inspect/tune them for
crowded or binary fields. A known detector saturation threshold can be supplied
as CoreConfig(saturation=...); saturation is not inferred from a file dtype.
The current quality measurement uses the sampled, unfiltered local peak and can
be affected by noise and pixel phase. This is an initial implementation, not a
validated precision photometry or astrometry reduction.
Optional Drizzle stacking
from pastrastack import stack, pastraPlot
result = stack(
"observation.fits",
method="drizzle",
output_scale=0.5, # Output pixel width / input pixel width
pixfrac=0.8, # Drop width / input pixel width
)
pastraPlot(result.lucky_image)
pastraPlot(result.group["43"])
print(result.lucky_image.path)
The default method="mean" remains the native-scale bilinear mean. Drizzle uses
STScI's optional drizzle package
with its square kernel. Install the extra with
pip install 'pastrastack[drizzle]'.
Original detector pixels are mapped directly through the fitted translation or
rigid transform: there is no bilinear pre-shifting. Alignment, quality scores,
rejections and ranked order do not change when switching the combination method.
output_scale=0.5 makes twice as many output pixels along each axis, with the
same full field coverage. More output samples do not guarantee more resolved
physical detail; that depends on the observations and subpixel sampling.
pixfrac accepts values in (0, 1]; smaller drops reduce spreading, but can leave
holes when the shifts do not sample the field sufficiently. Uncovered pixels
remain NaN, with zero weight and zero coverage.
The pipeline assumes counts per input pixel per exposure, and multiplies input
values by output_scale**2 for Drizzle. At half-size output pixels, a uniform
input of 100 counts/pixel becomes 25 counts/output pixel. This preserves the
integrated-flux convention over the four output pixels. It is not an exposure-time
conversion or a surface-brightness input mode. Inadequate coverage or very small
drops can prevent accurate integrated photometry; inspect WEIGHT and COVERAGE.
Input exposures have equal statistical weights; output weights include fractional
pixel/drop overlap. Background, bias, and flat-field calibration are not added by
choosing Drizzle.
The lower-level API also supports
alignment.stack(method="drizzle", output_scale=0.5, pixfrac=0.8).
Both interfaces use the same resampler. FITS products record COMBINE, OUTSCALE,
PIXFRAC, KERNEL, FLXSCALE, and the Drizzle version. ORIGINX/Y locate the
centre of output pixel (0, 0) in reference/input pixel coordinates, and
image.pixel_scale gives its width in those coordinates. Plot axes therefore
cover the same physical field when comparing native and oversampled grids.
These are relative pixel coordinates, not an angular/WCS calibration.
Each run fixes its method, output scale, and pixfrac. New percentage groups use the cached Drizzle contributions without rereading the cube or rerunning Drizzle; completed caches can even be reopened without the optional dependency installed. Changing method/scale/pixfrac requires a new run from the original pixels. Earlier mean-stack caches remain readable. At half-size pixels, the two caches use approximately four times the native-grid disk space; the pipeline checks available space before allocating them.
Sharpness versus Strehl
Without instrument calibration, quality_method == "peak_fraction". The pipeline
emits a warning and does not call these values Strehl ratios. The observation
headers currently available do not provide enough information to construct an
ideal optical PSF.
To use a finite-aperture Strehl estimate, supply ideal_psf= as a background-free,
nonnegative 2-D theoretical PSF with the correct telescope pupil, filter/wavelength
and detector pixel sampling. Its array must contain the same photometry aperture:
from astropy.io import fits
result = stack("observation.fits", ideal_psf=fits.getdata("ideal_psf.fits"))
# quality_method == "strehl_estimate"
# score = (observed_peak / observed_aperture_flux)
# / (ideal_peak / ideal_aperture_flux)
The ideal PSF is saved with the run. Estimates are not clipped to [0, 1]; values above 1 can expose noise, sampling, or calibration problems. Supplying one fixed ideal PSF rescales scores and does not change their ordering. Accurate absolute Strehl requires appropriate sampling and aperture/flux calibration.
Saved files and resource use
With just stack(input_file), a new uniquely named output folder is created
beside the input cube. output_dir= selects a location; an existing nonempty
folder is never overwritten. The data/ subfolder contains:
stack_0_5.fitsandstack_0_100.fits, plus any later requested ranges. Each contains the mean,COVERAGE,WEIGHT, and aFRAMEStable with indices, scores, confidence measurements and forward transformation matrices.ranking.fits: diagnostics for every processed exposure, including rejections.processing.jsonandsource_header.txt: settings and original metadata.aligned_values.npyandaligned_weights.npy: reusable, memory-mapped caches in ranked order. Keep these to create additional groups after reopening a run.
These caches use about 8 * N * height * width bytes, where height/width describe
the expanded canvas and N is the accepted count. Inputs are read in bounded
batches; cached samples are float32 and sums are accumulated in float64. Creating
a new range sums cached exposures; it never repeats alignment or interpolation.
Background subtraction is only used for alignment and quality measurement.
Science images retain the background; Drizzle additionally scales counts by the
output/input pixel area ratio, as described above. Output grids use reference
pixel coordinates and do not copy potentially invalid source sky WCS.
Installation
Requires Python 3.10 or newer:
pip install pastrastack
For plotting and Drizzle stacking:
pip install 'pastrastack[plot,drizzle]'
This first release is experimental research software. See the scientific limitations and calibration requirements below. Distributed under the BSD 3-Clause license.
For development from this repository:
python3 -m pip install -e '.[plot,test,drizzle]'
Alignment
from pastrastack import align
alignment = align("observation.fits", frame_indices=[0, 10, 20, 30])
image = alignment.stack()
data = image.data # Mean on the full, uncropped union canvas
coverage = image.coverage # Number of exposures contributing per pixel
print(alignment.reference_index) # Original zero-based cube index
for frame in alignment.diagnostics:
print(frame.frame_index, frame.accepted, frame.shift_xy, frame.rotation_deg)
align() estimates transforms; .stack() resamples the original selected frames
once and combines them (bilinear mean by default, optionally Drizzle). This diagnostic stack has no quality selection or ranking.
There is no automatic file writing in this low-level API. The demo below saves
both results and diagnostics.
The default rigid model fits translation and rotation, preserving scale. It detects background-subtracted stellar centroids, generates geometric pair matches, scores their one-to-one consensus, rejects inconsistent matches, and refits the accepted matches. Each exposure is matched directly to one common reference. The default reference prefers more detected stars, then higher peak signal-to-noise. No exposure-to-exposure drift is accumulated.
By default, three matched stars are required. Known two-star fields can use:
from pastrastack import AlignmentConfig
alignment = align("observation.fits", config=AlignmentConfig(min_matches=2))
Two-star fits are flagged as lacking an independent third-star check. Similar
stars can be confused, including a 180-degree permutation; inspect detections
and use max_rotation_deg to constrain rotation only when justified by the data.
Sources must be distinct stars: atmospheric speckles within one stellar image
do not independently constrain field rotation. Detection smoothing, separation,
threshold, and optional saturation cutoff are configurable via DetectionConfig.
Defaults are starting values in pixels, not a universal instrument calibration.
For the lower-level align() API, request translation explicitly when only
one usable source exists:
alignment = align(
"observation.fits",
config=AlignmentConfig(model="translation"),
)
That mode uses linear image cross-correlation with subpixel peak refinement. It assumes zero rotation; it does not measure or validate rotation. There is no automatic fallback from rigid to translation. Unreliable exposures retain their original indices and rejection reasons and are excluded from the stack.
Coordinates, edges, and memory
- Cube layout:
(exposure, row, column). Positions: zero-based(x, y). - Each 3x3 matrix maps input coordinates to reference coordinates. Reported translation is the matrix offset about the coordinate origin, not the motion of the image centre when rotation is present.
- The output canvas contains every accepted exposure's transformed pixel footprint. No common-overlap crop is made. Linear interpolation uses a validity weight so absent pixels and NaNs do not darken the mean. Uncovered pixels are NaN.
image.origin_xygives the reference coordinate of output pixel(0, 0).- Frame rejection and invalid-pixel masking are distinct from trimming the canvas.
- Requested FITS layers are read through Astropy sections, including scaled
unsigned FITS data. Selected layers are held in memory as float64; select a
subset for large cubes with
align(). The publicstack()pipeline instead processes full observations in bounded batches and caches results on disk. - This is an initial registration implementation, tested on simulated star fields and a real translation-only sample. It is not yet a validated scientific reduction pipeline for changing speckle patterns, photometry, or astrometry.
Compare eight Drizzle settings
Open Markus_project/Test_scripts/compare_drizzle.py in VS Code and click
Run Python File. A 2×4 Matplotlib window compares:
| Row | Output pixel width / original width | Footprints, left to right |
|---|---|---|
| Top | 0.5 | 0.2, 0.4, 0.6, 0.8 |
| Bottom | 0.25 | 0.2, 0.4, 0.6, 0.8 |
All eight use the same selected exposures and saved subpixel transforms. Half-size and quarter-size refer to linear pixel width, giving 2× and 4× the sampling along each axis. Each image is drizzled directly from the original pixels. The axes remain in original/reference pixel coordinates, with linked pan/zoom and the full field retained. One shared display stretch and pixel-area normalization make brightness comparable; FITS files retain the actual counts per output pixel. More sampling does not itself guarantee higher resolution.
The launcher defaults to all 6,422 accepted exposures. Set PERCENTAGE = 5 for
the best 5%, or change INPUT_FILE and ALIGNMENT_RUN together to use another
observation. The retained output is organized as:
Test_scripts/
compare_drizzle.py
output/
drizzle_comparison/
comparison.png
data/
footprint*.fits # Eight stacked images, weights and coverage
alignment_diagnostics.fits
processing.json
alignment/
processing.json # Full ranked index list and alignment settings
ranking.fits # All frames, transforms and rejection reasons
source_header.txt
data/alignment/ replaces the old large stack cache for this comparison. Keep
these small support files and the original FITS cube to regenerate any percentage
selection. This folder contains alignment diagnostics only, not a complete
StackResult cache. To create an alignment for a new observation, use
result = stack(input_file) and set ALIGNMENT_RUN = result.output_dir.
compare_drizzle.py is the only remaining diagnostic script. The workspace copy
launches the repository's PastraStack/Test_scripts/compare_drizzle.py.
The script streams exposures and creates no per-exposure cache. Each new run
creates a separate Test_scripts/output/compare_drizzle_*/ folder, with its
preview at the top and scientific data/settings in data/.
--view Test_scripts/output/drizzle_comparison reopens the retained comparison
without recomputing it. All eight FITS products retain frame IDs and applied
transforms. Pan/zoom is linked across all panels.
Tests
python3 -m pytest -q
Tests use known synthetic rotations/translations, missing and unrelated stars, explicit single/two-star handling, invalid frames, expanded footprints, weighted edges, scaled FITS reads, local-core confidence, brightness-normalized ranking, Strehl normalization, persistent percentile selections and cached FITS products. Drizzle tests check independent pixel-overlap calculations, flux and sampling conventions, rotated footprints, missing coverage and reusable percentile caches. They require the optional Drizzle dependency; otherwise that module is skipped.
Metadata
Release files for pastrastack 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pastrastack-0.1.0.tar.gz | 48.4 kB | With provenance | Details for pastrastack-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pastrastack-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for pastrastack-0.1.0-py3-none-any.whl |
Total release size: 87.1 kB
Release files / pastrastack-0.1.0.tar.gz
| Download URL | pastrastack-0.1.0.tar.gz |
|---|---|
| Size | 48.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
db5ab2ada9c8eab000b45b0adb825e95b5f7c3c32df119d277c03144a06bbcb6
|
|
BLAKE2b-256 checksum How to use checksums |
d86fcacd507879687484f7e3c7e8595c018401f3556bdbe8c104964eced491ef
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.
Transparency logRelease files / pastrastack-0.1.0-py3-none-any.whl
| Download URL | pastrastack-0.1.0-py3-none-any.whl |
|---|---|
| Size | 38.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a772dd18de7febfb47d8c116482bc30e3e1246f29109e0328819ceec6ea9b635
|
|
BLAKE2b-256 checksum How to use checksums |
48ba794e4fa461be8ca3b06f00f579851f4140451a64d62495d12448443bae1e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.
Transparency logSecurity for pastrastack 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for pastrastack-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.