pastrastack 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,29 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Nikolas Valsamidis
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its contributors
17
+ may be used to endorse or promote products derived from this software
18
+ without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,380 @@
1
+ Metadata-Version: 2.4
2
+ Name: pastrastack
3
+ Version: 0.1.0
4
+ Summary: Alignment and ranked lucky-image stacking for astronomical FITS exposure cubes
5
+ Author: Nikolas Valsamidis
6
+ License-Expression: BSD-3-Clause
7
+ Keywords: astronomy,fits,lucky imaging,image stacking,drizzle
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: numpy>=1.24
16
+ Requires-Dist: scipy>=1.10
17
+ Requires-Dist: astropy>=5.3
18
+ Provides-Extra: plot
19
+ Requires-Dist: matplotlib>=3.7; extra == "plot"
20
+ Provides-Extra: drizzle
21
+ Requires-Dist: drizzle<4,>=2.2; extra == "drizzle"
22
+ Provides-Extra: test
23
+ Requires-Dist: pytest>=7; extra == "test"
24
+ Dynamic: license-file
25
+
26
+ # PastraStack
27
+
28
+ Python tools for aligning astronomical FITS cubes, with one exposure per layer.
29
+ PastraStack is a working name.
30
+
31
+ The `stack()` pipeline aligns and ranks exposures, saves the best 5% and all
32
+ accepted exposures, and supports arbitrary percentile selections afterwards.
33
+ The lower-level `align()` API remains available.
34
+
35
+ ## Stack, plot, and access FITS files
36
+
37
+ ```python
38
+ from pastrastack import stack, pastraPlot, StackResult
39
+
40
+ result = stack("observation.fits")
41
+ pastraPlot(result.lucky_image) # Best 5% of accepted exposures
42
+ pastraPlot(result.group["43"]) # Best 43%, using the existing aligned cache
43
+ pastraPlot(result.group["10-20"]) # Only ranks between 10% and 20%
44
+ pastraPlot(result.all_image) # All accepted exposures
45
+
46
+ pixels = result.lucky_image.data # NumPy array
47
+ fits_path = result.lucky_image.path
48
+ print(result.output_dir)
49
+ print(result.diagnostics) # Includes rejected frames and reasons
50
+
51
+ # In a later session; the original cube is no longer needed:
52
+ result = StackResult.open("path/to/saved_output_folder")
53
+ pastraPlot(result.group["43"])
54
+ ```
55
+
56
+ Use the lowercase import name `pastrastack`. `result.group["luckyimage"]` is
57
+ also an alias for `result.lucky_image`. Every requested stack is saved as FITS
58
+ and reused on subsequent access. Percentage boundaries are `ceil(N*p/100)`,
59
+ where N is the number of accepted exposures: the best 5% includes at least one
60
+ frame, adjacent ranges never overlap, and an empty range raises `ValueError`.
61
+ An all-frame result includes every **accepted** exposure; it does not force
62
+ uncertain alignments into the mean. Original zero-based indices are preserved.
63
+
64
+ `stack()` defaults to translation-only **local-core registration**:
65
+
66
+ 1. Pick a sharp, usable reference from up to 32 evenly spaced preview frames.
67
+ `reference_index=` overrides that choice using an original cube index.
68
+ 2. Use median-filtered whole-image correlation to track the reference star.
69
+ 3. In a small region around its predicted position, correlate with a narrow
70
+ Gaussian template and refine the response maximum to subpixel precision.
71
+ 4. Reject low signal, ambiguous competing cores, isolated spikes, incomplete
72
+ photometry apertures, and weak coarse correlations. Keep rejection reasons.
73
+ 5. Rank accepted frames by background-subtracted peak divided by aperture flux.
74
+ 6. Interpolate each accepted original exposure once, then average selected
75
+ exposures with equal input exposure weights. Pixel validity weights exclude
76
+ missing data. The optional Drizzle method replaces bilinear interpolation with
77
+ direct pixel-drop overlap weighting. All selections share the full union canvas; there is no trimming.
78
+
79
+ The registration Gaussian is a matching kernel, **not a theoretical telescope
80
+ PSF**. Its width, search radius, aperture radius, and confidence thresholds are
81
+ configurable starting values, not instrument calibrations. Quality and alignment
82
+ confidence are separate diagnostic columns. No automatic rotation fit is attempted
83
+ from speckles within one star. For a field with enough distinct stars, explicitly
84
+ use `AlignmentConfig(model="rigid")` to fit rotation and translation instead.
85
+ That model uses the multi-star centroid fit described below.
86
+
87
+ ```python
88
+ from pastrastack import AlignmentConfig, CoreConfig
89
+
90
+ result = stack(
91
+ "observation.fits",
92
+ config=AlignmentConfig(
93
+ model="core",
94
+ core=CoreConfig(search_radius=8, aperture_radius=20, template_sigma=1),
95
+ ),
96
+ )
97
+ ```
98
+
99
+ `CoreConfig.reference_xy=(x, y)` can identify the intended star in reference
100
+ coordinates. The default uses the brightest detected source. Apertures should
101
+ contain that star's light without including companions; inspect/tune them for
102
+ crowded or binary fields. A known detector saturation threshold can be supplied
103
+ as `CoreConfig(saturation=...)`; saturation is not inferred from a file dtype.
104
+ The current quality measurement uses the sampled, unfiltered local peak and can
105
+ be affected by noise and pixel phase. This is an initial implementation, not a
106
+ validated precision photometry or astrometry reduction.
107
+
108
+ ### Optional Drizzle stacking
109
+
110
+ ```python
111
+ from pastrastack import stack, pastraPlot
112
+
113
+ result = stack(
114
+ "observation.fits",
115
+ method="drizzle",
116
+ output_scale=0.5, # Output pixel width / input pixel width
117
+ pixfrac=0.8, # Drop width / input pixel width
118
+ )
119
+ pastraPlot(result.lucky_image)
120
+ pastraPlot(result.group["43"])
121
+ print(result.lucky_image.path)
122
+ ```
123
+
124
+ The default `method="mean"` remains the native-scale bilinear mean. Drizzle uses
125
+ STScI's optional [`drizzle` package](https://spacetelescope-drizzle.readthedocs.io/en/stable/api/drizzle.resample.Drizzle.html)
126
+ with its square kernel. Install the extra with
127
+ `pip install 'pastrastack[drizzle]'`.
128
+
129
+ Original detector pixels are mapped directly through the fitted translation or
130
+ rigid transform: there is **no bilinear pre-shifting**. Alignment, quality scores,
131
+ rejections and ranked order do not change when switching the combination method.
132
+ `output_scale=0.5` makes twice as many output pixels along each axis, with the
133
+ same full field coverage. More output samples do not guarantee more resolved
134
+ physical detail; that depends on the observations and subpixel sampling.
135
+ `pixfrac` accepts values in `(0, 1]`; smaller drops reduce spreading, but can leave
136
+ holes when the shifts do not sample the field sufficiently. Uncovered pixels
137
+ remain NaN, with zero weight and zero coverage.
138
+
139
+ The pipeline assumes **counts per input pixel per exposure**, and multiplies input
140
+ values by `output_scale**2` for Drizzle. At half-size output pixels, a uniform
141
+ input of 100 counts/pixel becomes 25 counts/output pixel. This preserves the
142
+ integrated-flux convention over the four output pixels. It is not an exposure-time
143
+ conversion or a surface-brightness input mode. Inadequate coverage or very small
144
+ drops can prevent accurate integrated photometry; inspect `WEIGHT` and `COVERAGE`.
145
+ Input exposures have equal statistical weights; output weights include fractional
146
+ pixel/drop overlap. Background, bias, and flat-field calibration are not added by
147
+ choosing Drizzle.
148
+
149
+ The lower-level API also supports
150
+ `alignment.stack(method="drizzle", output_scale=0.5, pixfrac=0.8)`.
151
+ Both interfaces use the same resampler. FITS products record `COMBINE`, `OUTSCALE`,
152
+ `PIXFRAC`, `KERNEL`, `FLXSCALE`, and the Drizzle version. `ORIGINX/Y` locate the
153
+ **centre** of output pixel `(0, 0)` in reference/input pixel coordinates, and
154
+ `image.pixel_scale` gives its width in those coordinates. Plot axes therefore
155
+ cover the same physical field when comparing native and oversampled grids.
156
+ These are relative pixel coordinates, not an angular/WCS calibration.
157
+
158
+ Each run fixes its method, output scale, and pixfrac. New percentage groups use
159
+ the cached Drizzle contributions without rereading the cube or rerunning Drizzle;
160
+ completed caches can even be reopened without the optional dependency installed.
161
+ Changing method/scale/pixfrac requires a new run from the original pixels.
162
+ Earlier mean-stack caches remain readable. At half-size pixels, the two caches
163
+ use approximately **four times** the native-grid disk space; the pipeline checks
164
+ available space before allocating them.
165
+
166
+ ### Sharpness versus Strehl
167
+
168
+ Without instrument calibration, `quality_method == "peak_fraction"`. The pipeline
169
+ emits a warning and does **not** call these values Strehl ratios. The observation
170
+ headers currently available do not provide enough information to construct an
171
+ ideal optical PSF.
172
+
173
+ To use a finite-aperture Strehl estimate, supply `ideal_psf=` as a background-free,
174
+ nonnegative 2-D theoretical PSF with the correct telescope pupil, filter/wavelength
175
+ and detector pixel sampling. Its array must contain the same photometry aperture:
176
+
177
+ ```python
178
+ from astropy.io import fits
179
+
180
+ result = stack("observation.fits", ideal_psf=fits.getdata("ideal_psf.fits"))
181
+ # quality_method == "strehl_estimate"
182
+ # score = (observed_peak / observed_aperture_flux)
183
+ # / (ideal_peak / ideal_aperture_flux)
184
+ ```
185
+
186
+ The ideal PSF is saved with the run. Estimates are not clipped to [0, 1]; values
187
+ above 1 can expose noise, sampling, or calibration problems. Supplying one fixed
188
+ ideal PSF rescales scores and does not change their ordering. Accurate absolute
189
+ Strehl requires appropriate sampling and aperture/flux calibration.
190
+
191
+ ### Saved files and resource use
192
+
193
+ With just `stack(input_file)`, a new uniquely named output folder is created
194
+ beside the input cube. `output_dir=` selects a location; an existing nonempty
195
+ folder is never overwritten. The `data/` subfolder contains:
196
+
197
+ - `stack_0_5.fits` and `stack_0_100.fits`, plus any later requested ranges.
198
+ Each contains the mean, `COVERAGE`, `WEIGHT`, and a `FRAMES` table with indices,
199
+ scores, confidence measurements and forward transformation matrices.
200
+ - `ranking.fits`: diagnostics for every processed exposure, including rejections.
201
+ - `processing.json` and `source_header.txt`: settings and original metadata.
202
+ - `aligned_values.npy` and `aligned_weights.npy`: reusable, memory-mapped caches
203
+ in ranked order. Keep these to create additional groups after reopening a run.
204
+
205
+ These caches use about `8 * N * height * width` bytes, where height/width describe
206
+ the expanded canvas and N is the accepted count. Inputs are read in bounded
207
+ batches; cached samples are float32 and sums are accumulated in float64. Creating
208
+ a new range sums cached exposures; it never repeats alignment or interpolation.
209
+ Background subtraction is only used for alignment and quality measurement.
210
+ Science images retain the background; Drizzle additionally scales counts by the
211
+ output/input pixel area ratio, as described above. Output grids use reference
212
+ pixel coordinates and do not copy potentially invalid source sky WCS.
213
+
214
+ ## Installation
215
+
216
+ Requires Python 3.10 or newer:
217
+
218
+ ```bash
219
+ pip install pastrastack
220
+ ```
221
+
222
+ For plotting and Drizzle stacking:
223
+
224
+ ```bash
225
+ pip install 'pastrastack[plot,drizzle]'
226
+ ```
227
+
228
+ This first release is experimental research software. See the scientific
229
+ limitations and calibration requirements below. Distributed under the
230
+ BSD 3-Clause license.
231
+
232
+ For development from this repository:
233
+
234
+ ```bash
235
+ python3 -m pip install -e '.[plot,test,drizzle]'
236
+ ```
237
+
238
+ ## Alignment
239
+
240
+ ```python
241
+ from pastrastack import align
242
+
243
+ alignment = align("observation.fits", frame_indices=[0, 10, 20, 30])
244
+ image = alignment.stack()
245
+
246
+ data = image.data # Mean on the full, uncropped union canvas
247
+ coverage = image.coverage # Number of exposures contributing per pixel
248
+ print(alignment.reference_index) # Original zero-based cube index
249
+ for frame in alignment.diagnostics:
250
+ print(frame.frame_index, frame.accepted, frame.shift_xy, frame.rotation_deg)
251
+ ```
252
+
253
+ `align()` estimates transforms; `.stack()` resamples the original selected frames
254
+ once and combines them (bilinear mean by default, optionally Drizzle). This diagnostic stack has no quality selection or ranking.
255
+ There is no automatic file writing in this low-level API. The demo below saves
256
+ both results and diagnostics.
257
+
258
+ The default **rigid** model fits translation and rotation, preserving scale.
259
+ It detects background-subtracted stellar centroids, generates geometric pair
260
+ matches, scores their one-to-one consensus, rejects inconsistent matches, and
261
+ refits the accepted matches. Each exposure is matched directly to one common
262
+ reference. The default reference prefers more detected stars, then higher peak
263
+ signal-to-noise. No exposure-to-exposure drift is accumulated.
264
+
265
+ By default, three matched stars are required. Known two-star fields can use:
266
+
267
+ ```python
268
+ from pastrastack import AlignmentConfig
269
+
270
+ alignment = align("observation.fits", config=AlignmentConfig(min_matches=2))
271
+ ```
272
+
273
+ Two-star fits are flagged as lacking an independent third-star check. Similar
274
+ stars can be confused, including a 180-degree permutation; inspect detections
275
+ and use `max_rotation_deg` to constrain rotation only when justified by the data.
276
+ Sources must be distinct stars: atmospheric speckles within one stellar image
277
+ do not independently constrain field rotation. Detection smoothing, separation,
278
+ threshold, and optional saturation cutoff are configurable via `DetectionConfig`.
279
+ Defaults are starting values in pixels, not a universal instrument calibration.
280
+
281
+ For the lower-level `align()` API, request translation explicitly when only
282
+ one usable source exists:
283
+
284
+ ```python
285
+ alignment = align(
286
+ "observation.fits",
287
+ config=AlignmentConfig(model="translation"),
288
+ )
289
+ ```
290
+
291
+ That mode uses linear image cross-correlation with subpixel peak refinement.
292
+ **It assumes zero rotation; it does not measure or validate rotation.** There
293
+ is no automatic fallback from rigid to translation. Unreliable exposures retain
294
+ their original indices and rejection reasons and are excluded from the stack.
295
+
296
+ ### Coordinates, edges, and memory
297
+
298
+ - Cube layout: `(exposure, row, column)`. Positions: zero-based `(x, y)`.
299
+ - Each 3x3 matrix maps input coordinates to reference coordinates. Reported
300
+ translation is the matrix offset about the coordinate origin, not the motion
301
+ of the image centre when rotation is present.
302
+ - The output canvas contains every accepted exposure's transformed pixel
303
+ footprint. No common-overlap crop is made. Linear interpolation uses a validity
304
+ weight so absent pixels and NaNs do not darken the mean. Uncovered pixels are NaN.
305
+ - `image.origin_xy` gives the reference coordinate of output pixel `(0, 0)`.
306
+ - Frame rejection and invalid-pixel masking are distinct from trimming the canvas.
307
+ - Requested FITS layers are read through Astropy sections, including scaled
308
+ unsigned FITS data. Selected layers are held in memory as float64; select a
309
+ subset for large cubes with `align()`. The public `stack()` pipeline instead
310
+ processes full observations in bounded batches and caches results on disk.
311
+ - This is an initial registration implementation, tested on simulated star fields
312
+ and a real translation-only sample. It is not yet a validated scientific
313
+ reduction pipeline for changing speckle patterns, photometry, or astrometry.
314
+
315
+ ## Compare eight Drizzle settings
316
+
317
+ Open `Markus_project/Test_scripts/compare_drizzle.py` in VS Code and click
318
+ **Run Python File**. A 2×4 Matplotlib window compares:
319
+
320
+ | Row | Output pixel width / original width | Footprints, left to right |
321
+ |---|---:|---|
322
+ | Top | 0.5 | 0.2, 0.4, 0.6, 0.8 |
323
+ | Bottom | 0.25 | 0.2, 0.4, 0.6, 0.8 |
324
+
325
+ All eight use the same selected exposures and saved subpixel transforms. Half-size
326
+ and quarter-size refer to **linear pixel width**, giving 2× and 4× the sampling
327
+ along each axis. Each image is drizzled directly from the original pixels.
328
+ The axes remain in original/reference pixel coordinates, with linked pan/zoom
329
+ and the full field retained. One shared display stretch and pixel-area
330
+ normalization make brightness comparable; FITS files retain the actual counts
331
+ per output pixel. More sampling does not itself guarantee higher resolution.
332
+
333
+ The launcher defaults to all 6,422 accepted exposures. Set `PERCENTAGE = 5` for
334
+ the best 5%, or change `INPUT_FILE` and `ALIGNMENT_RUN` together to use another
335
+ observation. The retained output is organized as:
336
+
337
+ ```text
338
+ Test_scripts/
339
+ compare_drizzle.py
340
+ output/
341
+ drizzle_comparison/
342
+ comparison.png
343
+ data/
344
+ footprint*.fits # Eight stacked images, weights and coverage
345
+ alignment_diagnostics.fits
346
+ processing.json
347
+ alignment/
348
+ processing.json # Full ranked index list and alignment settings
349
+ ranking.fits # All frames, transforms and rejection reasons
350
+ source_header.txt
351
+ ```
352
+
353
+ `data/alignment/` replaces the old large stack cache for this comparison. Keep
354
+ these small support files and the original FITS cube to regenerate any percentage
355
+ selection. This folder contains alignment diagnostics only, not a complete
356
+ `StackResult` cache. To create an alignment for a new observation, use
357
+ `result = stack(input_file)` and set `ALIGNMENT_RUN = result.output_dir`.
358
+
359
+ `compare_drizzle.py` is the only remaining diagnostic script. The workspace copy
360
+ launches the repository's `PastraStack/Test_scripts/compare_drizzle.py`.
361
+ The script streams exposures and creates no per-exposure cache. Each new run
362
+ creates a separate `Test_scripts/output/compare_drizzle_*/` folder, with its
363
+ preview at the top and scientific data/settings in `data/`.
364
+ `--view Test_scripts/output/drizzle_comparison` reopens the retained comparison
365
+ without recomputing it. All eight FITS products retain frame IDs and applied
366
+ transforms. Pan/zoom is linked across all panels.
367
+
368
+ ## Tests
369
+
370
+ ```bash
371
+ python3 -m pytest -q
372
+ ```
373
+
374
+ Tests use known synthetic rotations/translations, missing and unrelated stars,
375
+ explicit single/two-star handling, invalid frames, expanded footprints, weighted
376
+ edges, scaled FITS reads, local-core confidence, brightness-normalized ranking,
377
+ Strehl normalization, persistent percentile selections and cached FITS products.
378
+ Drizzle tests check independent pixel-overlap calculations, flux and sampling
379
+ conventions, rotated footprints, missing coverage and reusable percentile caches.
380
+ They require the optional Drizzle dependency; otherwise that module is skipped.