Metadata-Version: 2.4
Name: pastrastack
Version: 0.1.0
Summary: Alignment and ranked lucky-image stacking for astronomical FITS exposure cubes
Author: Nikolas Valsamidis
License-Expression: BSD-3-Clause
Keywords: astronomy,fits,lucky imaging,image stacking,drizzle
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Astronomy
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24
Requires-Dist: scipy>=1.10
Requires-Dist: astropy>=5.3
Provides-Extra: plot
Requires-Dist: matplotlib>=3.7; extra == "plot"
Provides-Extra: drizzle
Requires-Dist: drizzle<4,>=2.2; extra == "drizzle"
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Dynamic: license-file

# 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

```python
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**:

1. Pick a sharp, usable reference from up to 32 evenly spaced preview frames.
   `reference_index=` overrides that choice using an original cube index.
2. Use median-filtered whole-image correlation to track the reference star.
3. In a small region around its predicted position, correlate with a narrow
   Gaussian template and refine the response maximum to subpixel precision.
4. Reject low signal, ambiguous competing cores, isolated spikes, incomplete
   photometry apertures, and weak coarse correlations. Keep rejection reasons.
5. Rank accepted frames by background-subtracted peak divided by aperture flux.
6. 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.

```python
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

```python
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](https://spacetelescope-drizzle.readthedocs.io/en/stable/api/drizzle.resample.Drizzle.html)
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:

```python
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.fits` and `stack_0_100.fits`, plus any later requested ranges.
  Each contains the mean, `COVERAGE`, `WEIGHT`, and a `FRAMES` table with indices,
  scores, confidence measurements and forward transformation matrices.
- `ranking.fits`: diagnostics for every processed exposure, including rejections.
- `processing.json` and `source_header.txt`: settings and original metadata.
- `aligned_values.npy` and `aligned_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:

```bash
pip install pastrastack
```

For plotting and Drizzle stacking:

```bash
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:

```bash
python3 -m pip install -e '.[plot,test,drizzle]'
```

## Alignment

```python
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:

```python
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:

```python
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_xy` gives 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 public `stack()` 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:

```text
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

```bash
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.
