pastrastack 0.1.0__py3-none-any.whl
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.
- pastrastack/__init__.py +13 -0
- pastrastack/alignment.py +193 -0
- pastrastack/core.py +173 -0
- pastrastack/detection.py +88 -0
- pastrastack/drizzling.py +47 -0
- pastrastack/io.py +42 -0
- pastrastack/pipeline.py +398 -0
- pastrastack/registration.py +120 -0
- pastrastack/resampling.py +155 -0
- pastrastack/selection.py +41 -0
- pastrastack/single_image.py +267 -0
- pastrastack/visualization.py +119 -0
- pastrastack-0.1.0.dist-info/METADATA +380 -0
- pastrastack-0.1.0.dist-info/RECORD +17 -0
- pastrastack-0.1.0.dist-info/WHEEL +5 -0
- pastrastack-0.1.0.dist-info/licenses/LICENSE +29 -0
- pastrastack-0.1.0.dist-info/top_level.txt +1 -0
pastrastack/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""PastraStack: alignment and ranked stacking for FITS exposure cubes."""
|
|
2
|
+
|
|
3
|
+
from .alignment import AlignmentConfig, AlignmentResult, FrameAlignment, align
|
|
4
|
+
from .detection import DetectionConfig, detect_stars
|
|
5
|
+
from .resampling import AlignedStack
|
|
6
|
+
from .core import CoreConfig
|
|
7
|
+
from .pipeline import StackImage, StackResult, pastraPlot, stack
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"align", "AlignmentConfig", "AlignmentResult", "FrameAlignment",
|
|
11
|
+
"DetectionConfig", "detect_stars", "AlignedStack",
|
|
12
|
+
"CoreConfig", "StackImage", "StackResult", "stack", "pastraPlot",
|
|
13
|
+
]
|
pastrastack/alignment.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Public alignment API; estimates transforms without modifying the input."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from .detection import DetectionConfig, detect_stars
|
|
8
|
+
from .io import read_cube
|
|
9
|
+
from .registration import match_rigid, match_translation, rotation_degrees
|
|
10
|
+
from .resampling import combine
|
|
11
|
+
from .core import CoreConfig, core_translation, locate_core
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class AlignmentConfig:
|
|
16
|
+
model: str = "rigid"
|
|
17
|
+
detection: DetectionConfig = field(default_factory=DetectionConfig)
|
|
18
|
+
min_matches: int = 3
|
|
19
|
+
match_tolerance: float = 2.0
|
|
20
|
+
max_rms: float = 1.0
|
|
21
|
+
max_rotation_deg: float = 180.0
|
|
22
|
+
min_correlation: float = 0.2
|
|
23
|
+
core: CoreConfig = field(default_factory=CoreConfig)
|
|
24
|
+
|
|
25
|
+
def __post_init__(self):
|
|
26
|
+
if self.model not in ("rigid", "translation", "core"):
|
|
27
|
+
raise ValueError("model must be 'rigid', 'translation', or 'core'")
|
|
28
|
+
if not isinstance(self.min_matches, (int, np.integer)) or self.min_matches < 2:
|
|
29
|
+
raise ValueError("min_matches must be an integer >= 2")
|
|
30
|
+
for name in ("match_tolerance", "max_rms"):
|
|
31
|
+
if not np.isfinite(getattr(self, name)) or getattr(self, name) <= 0:
|
|
32
|
+
raise ValueError(f"{name} must be positive and finite")
|
|
33
|
+
if not 0 < self.max_rotation_deg <= 180:
|
|
34
|
+
raise ValueError("max_rotation_deg must be in (0, 180]")
|
|
35
|
+
if not 0 < self.min_correlation <= 1:
|
|
36
|
+
raise ValueError("min_correlation must be in (0, 1]")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class FrameAlignment:
|
|
41
|
+
frame_index: int
|
|
42
|
+
accepted: bool
|
|
43
|
+
method: str
|
|
44
|
+
matrix: np.ndarray | None
|
|
45
|
+
n_detected: int
|
|
46
|
+
n_matched: int = 0
|
|
47
|
+
rms_pixels: float = np.nan
|
|
48
|
+
correlation: float = np.nan
|
|
49
|
+
reason: str = ""
|
|
50
|
+
matched_xy: np.ndarray = field(default_factory=lambda: np.empty((0, 2)))
|
|
51
|
+
reference_xy: np.ndarray = field(default_factory=lambda: np.empty((0, 2)))
|
|
52
|
+
core_snr: float = np.nan
|
|
53
|
+
peak_ratio: float = np.nan
|
|
54
|
+
quality: float = np.nan
|
|
55
|
+
peak: float = np.nan
|
|
56
|
+
flux: float = np.nan
|
|
57
|
+
background: float = np.nan
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def rotation_deg(self):
|
|
61
|
+
return rotation_degrees(self.matrix) if self.matrix is not None else np.nan
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def shift_xy(self):
|
|
65
|
+
return self.matrix[:2, 2].copy() if self.matrix is not None else np.full(2, np.nan)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass
|
|
69
|
+
class AlignmentResult:
|
|
70
|
+
frames: np.ndarray
|
|
71
|
+
frame_indices: np.ndarray
|
|
72
|
+
reference_index: int
|
|
73
|
+
diagnostics: list[FrameAlignment]
|
|
74
|
+
catalogs: list
|
|
75
|
+
config: AlignmentConfig
|
|
76
|
+
|
|
77
|
+
@property
|
|
78
|
+
def accepted(self):
|
|
79
|
+
return np.array([d.accepted for d in self.diagnostics])
|
|
80
|
+
|
|
81
|
+
def stack(self, *, max_output_pixels=100_000_000, method='mean',
|
|
82
|
+
output_scale=None, pixfrac=None):
|
|
83
|
+
"""Mean of accepted exposures on their full union canvas; no trimming.
|
|
84
|
+
|
|
85
|
+
This diagnostic combination performs no Strehl ranking or selection.
|
|
86
|
+
Uncovered pixels are NaN, and partial edges have validity weights.
|
|
87
|
+
"""
|
|
88
|
+
return combine(self.frames, self.diagnostics, max_output_pixels=max_output_pixels,
|
|
89
|
+
method=method, output_scale=output_scale, pixfrac=pixfrac)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def align(source, *, frame_indices=None, reference_index=None, config=None, hdu=0):
|
|
93
|
+
"""Estimate exposure-to-reference rotation/translation transforms.
|
|
94
|
+
|
|
95
|
+
Parameters
|
|
96
|
+
----------
|
|
97
|
+
source : path or ndarray
|
|
98
|
+
FITS cube or array shaped (exposures, height, width). Selected frames
|
|
99
|
+
are held in memory. Use frame_indices for large cubes.
|
|
100
|
+
frame_indices : sequence of int, optional
|
|
101
|
+
Original zero-based cube indices to process, preserving supplied order.
|
|
102
|
+
reference_index : int, optional
|
|
103
|
+
Original cube index, which must be among selected frames. By default
|
|
104
|
+
prefer the frame with the most detected stars, then highest peak S/N.
|
|
105
|
+
config : AlignmentConfig, optional
|
|
106
|
+
Default fits rotation plus translation using >=3 matched stars.
|
|
107
|
+
Set min_matches=2 for known two-star fields (less independently
|
|
108
|
+
constrained). model='translation' explicitly assumes zero rotation.
|
|
109
|
+
model='core' uses coarse correlation followed by local sharp-template
|
|
110
|
+
registration, with core-confidence checks; it also assumes zero rotation.
|
|
111
|
+
|
|
112
|
+
Returns
|
|
113
|
+
-------
|
|
114
|
+
AlignmentResult
|
|
115
|
+
Forward 3x3 matrices in zero-based (x,y), masks and per-frame diagnostics.
|
|
116
|
+
Failed fits are retained with accepted=False; no silent model fallback.
|
|
117
|
+
"""
|
|
118
|
+
config = config or AlignmentConfig()
|
|
119
|
+
frames, indices = read_cube(source, frame_indices, hdu)
|
|
120
|
+
catalogs = [detect_stars(frame, config.detection) for frame in frames]
|
|
121
|
+
required = config.min_matches if config.model == "rigid" else 1
|
|
122
|
+
if reference_index is not None:
|
|
123
|
+
if not isinstance(reference_index, (int, np.integer)):
|
|
124
|
+
raise ValueError("reference_index must be an original integer cube index")
|
|
125
|
+
matches = np.flatnonzero(indices == reference_index)
|
|
126
|
+
if not len(matches):
|
|
127
|
+
raise ValueError("reference_index must be one of the selected frame_indices")
|
|
128
|
+
ref = int(matches[0])
|
|
129
|
+
else:
|
|
130
|
+
candidates = [i for i, cat in enumerate(catalogs) if len(cat) >= required]
|
|
131
|
+
if not candidates:
|
|
132
|
+
raise ValueError(
|
|
133
|
+
f"No reference has {required} usable stars for {config.model} alignment. "
|
|
134
|
+
"Inspect detections; use model='translation' explicitly only if rotation can be ignored."
|
|
135
|
+
)
|
|
136
|
+
ref = max(candidates, key=lambda i: (
|
|
137
|
+
len(catalogs[i]),
|
|
138
|
+
(np.nanmax(frames[i]) - catalogs[i].background) / max(catalogs[i].noise, 1e-12),
|
|
139
|
+
))
|
|
140
|
+
reference = catalogs[ref]
|
|
141
|
+
if len(reference) < required:
|
|
142
|
+
raise ValueError(f"Selected reference needs at least {required} usable stars")
|
|
143
|
+
reference_core = None
|
|
144
|
+
if config.model == "core":
|
|
145
|
+
anchor = config.core.reference_xy
|
|
146
|
+
if anchor is None:
|
|
147
|
+
anchor = reference.xy[0]
|
|
148
|
+
reference_core = locate_core(frames[ref], anchor, config.core)
|
|
149
|
+
diagnostics = []
|
|
150
|
+
for i, (frame, cat) in enumerate(zip(frames, catalogs)):
|
|
151
|
+
d = FrameAlignment(int(indices[i]), False, config.model, None, len(cat))
|
|
152
|
+
try:
|
|
153
|
+
if i == ref:
|
|
154
|
+
d.matrix, d.n_matched, d.rms_pixels = np.eye(3), len(cat), 0.0
|
|
155
|
+
d.method, d.reason = "reference", "Reference exposure"
|
|
156
|
+
d.matched_xy = cat.xy.copy()
|
|
157
|
+
d.reference_xy = cat.xy.copy()
|
|
158
|
+
elif config.model == "core":
|
|
159
|
+
d.matrix, d.correlation, measured = core_translation(
|
|
160
|
+
frame, frames[ref], reference_core, config.core, config.min_correlation,
|
|
161
|
+
)
|
|
162
|
+
d.n_matched = 1
|
|
163
|
+
d.matched_xy = measured.xy[None, :]
|
|
164
|
+
d.reference_xy = reference_core.xy[None, :]
|
|
165
|
+
d.reason = "Local core translation: rotation was not measured"
|
|
166
|
+
elif config.model == "rigid":
|
|
167
|
+
matrix, si, ri, rms = match_rigid(
|
|
168
|
+
cat, reference, min_matches=config.min_matches,
|
|
169
|
+
tolerance=config.match_tolerance, max_rms=config.max_rms,
|
|
170
|
+
max_rotation=config.max_rotation_deg,
|
|
171
|
+
)
|
|
172
|
+
d.matrix, d.n_matched, d.rms_pixels = matrix, len(si), rms
|
|
173
|
+
d.matched_xy, d.reference_xy = cat.xy[si], reference.xy[ri]
|
|
174
|
+
if len(si) == 2:
|
|
175
|
+
d.reason = "Two-star fit: no third-star cross-check; identity may be ambiguous"
|
|
176
|
+
else:
|
|
177
|
+
if not len(cat):
|
|
178
|
+
raise ValueError("No usable star detected")
|
|
179
|
+
d.matrix, d.correlation = match_translation(
|
|
180
|
+
frame, frames[ref], cat.background, reference.background,
|
|
181
|
+
config.min_correlation,
|
|
182
|
+
)
|
|
183
|
+
d.reason = "Translation only: rotation was not measured"
|
|
184
|
+
if config.model == "core":
|
|
185
|
+
measured = reference_core if i == ref else measured
|
|
186
|
+
d.core_snr, d.peak_ratio = measured.snr, measured.peak_ratio
|
|
187
|
+
d.quality, d.peak, d.flux = measured.quality, measured.peak, measured.flux
|
|
188
|
+
d.background = measured.background
|
|
189
|
+
d.accepted = True
|
|
190
|
+
except ValueError as exc:
|
|
191
|
+
d.reason = str(exc)
|
|
192
|
+
diagnostics.append(d)
|
|
193
|
+
return AlignmentResult(frames, indices, int(indices[ref]), diagnostics, catalogs, config)
|
pastrastack/core.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Local sharp-core registration, kept separate from image-quality ranking."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from astropy.stats import sigma_clipped_stats
|
|
7
|
+
from scipy.ndimage import median_filter
|
|
8
|
+
from scipy.signal import fftconvolve
|
|
9
|
+
|
|
10
|
+
from .registration import match_translation
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True)
|
|
14
|
+
class CoreConfig:
|
|
15
|
+
search_radius: float = 8.0
|
|
16
|
+
aperture_radius: float = 20.0
|
|
17
|
+
template_sigma: float = 1.0
|
|
18
|
+
min_snr: float = 5.0
|
|
19
|
+
min_peak_ratio: float = 1.05
|
|
20
|
+
saturation: float | None = None
|
|
21
|
+
reference_xy: tuple[float, float] | None = None
|
|
22
|
+
|
|
23
|
+
def __post_init__(self):
|
|
24
|
+
for name in ('search_radius', 'aperture_radius', 'template_sigma', 'min_snr'):
|
|
25
|
+
if not np.isfinite(getattr(self, name)) or getattr(self, name) <= 0:
|
|
26
|
+
raise ValueError(f'{name} must be positive and finite')
|
|
27
|
+
if not np.isfinite(self.min_peak_ratio) or self.min_peak_ratio < 1:
|
|
28
|
+
raise ValueError('min_peak_ratio must be finite and >= 1')
|
|
29
|
+
if self.saturation is not None and not np.isfinite(self.saturation):
|
|
30
|
+
raise ValueError('saturation must be finite')
|
|
31
|
+
if self.reference_xy is not None:
|
|
32
|
+
xy = np.asarray(self.reference_xy)
|
|
33
|
+
if xy.shape != (2,) or not np.isfinite(xy).all():
|
|
34
|
+
raise ValueError('reference_xy must contain finite (x, y) coordinates')
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class CoreMeasurement:
|
|
39
|
+
xy: np.ndarray
|
|
40
|
+
snr: float
|
|
41
|
+
peak_ratio: float
|
|
42
|
+
peak: float
|
|
43
|
+
flux: float
|
|
44
|
+
background: float
|
|
45
|
+
|
|
46
|
+
@property
|
|
47
|
+
def quality(self):
|
|
48
|
+
return self.peak / self.flux
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def background_stats(frame):
|
|
52
|
+
finite = frame[np.isfinite(frame)]
|
|
53
|
+
if not finite.size:
|
|
54
|
+
raise ValueError('No finite pixels')
|
|
55
|
+
_, background, noise = sigma_clipped_stats(finite, sigma=3)
|
|
56
|
+
return float(background), float(noise)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def locate_core(frame, predicted_xy, config, *, background=None, noise=None):
|
|
60
|
+
"""Match a narrow Gaussian kernel locally, then refine its peak subpixel.
|
|
61
|
+
|
|
62
|
+
The Gaussian is a registration template, not a diffraction/ideal PSF.
|
|
63
|
+
Confidence measures are diagnostics, not calibrated probabilities.
|
|
64
|
+
Quality uses the unfiltered sampled peak / background-subtracted aperture
|
|
65
|
+
flux. It is deliberately independent of the matching amplitude/SNR.
|
|
66
|
+
"""
|
|
67
|
+
frame = np.asarray(frame, dtype=float)
|
|
68
|
+
if background is None or noise is None:
|
|
69
|
+
background, noise = background_stats(frame)
|
|
70
|
+
x, y = np.asarray(predicted_xy, dtype=float)
|
|
71
|
+
if not (0 <= x < frame.shape[1] and 0 <= y < frame.shape[0]):
|
|
72
|
+
raise ValueError('Predicted reference star is outside the exposure')
|
|
73
|
+
radius = int(np.ceil(4 * config.template_sigma))
|
|
74
|
+
ky, kx = np.mgrid[-radius:radius+1, -radius:radius+1]
|
|
75
|
+
kernel = np.exp(-(kx*kx + ky*ky) / (2 * config.template_sigma**2))
|
|
76
|
+
kernel /= kernel.sum()
|
|
77
|
+
margin = int(np.ceil(config.search_radius)) + radius + 2
|
|
78
|
+
x0, x1 = max(0, int(x)-margin), min(frame.shape[1], int(x)+margin+2)
|
|
79
|
+
y0, y1 = max(0, int(y)-margin), min(frame.shape[0], int(y)+margin+2)
|
|
80
|
+
patch = frame[y0:y1, x0:x1]
|
|
81
|
+
valid = np.isfinite(patch)
|
|
82
|
+
clean = np.where(valid, patch-background, 0.)
|
|
83
|
+
response = fftconvolve(clean, kernel, mode='same')
|
|
84
|
+
yy, xx = np.mgrid[y0:y1, x0:x1]
|
|
85
|
+
search = (xx-x)**2 + (yy-y)**2 <= config.search_radius**2
|
|
86
|
+
support = fftconvolve(valid.astype(float), kernel, mode='same')
|
|
87
|
+
search &= support > .999
|
|
88
|
+
if not search.any():
|
|
89
|
+
raise ValueError('No fully supported core within search region')
|
|
90
|
+
candidates = np.where(search, response, -np.inf)
|
|
91
|
+
iy, ix = np.unravel_index(np.argmax(candidates), candidates.shape)
|
|
92
|
+
best = float(response[iy, ix])
|
|
93
|
+
if best <= 0:
|
|
94
|
+
raise ValueError('No positive core signal')
|
|
95
|
+
xy = np.array([ix+x0, iy+y0], dtype=float)
|
|
96
|
+
# A peak at the search boundary may mean the tracked object escaped it.
|
|
97
|
+
if np.linalg.norm(xy-[x, y]) >= config.search_radius-1:
|
|
98
|
+
raise ValueError('Core lies at search boundary')
|
|
99
|
+
for axis, coord in enumerate((ix, iy)):
|
|
100
|
+
line = response[iy, :] if axis == 0 else response[:, ix]
|
|
101
|
+
if 0 < coord < len(line)-1:
|
|
102
|
+
l, c, r = line[coord-1:coord+2]
|
|
103
|
+
curvature = l-2*c+r
|
|
104
|
+
if curvature < 0:
|
|
105
|
+
xy[axis] += np.clip(.5*(l-r)/curvature, -.5, .5)
|
|
106
|
+
exclusion = max(3., 3 * config.template_sigma)
|
|
107
|
+
competitors = search & ((xx-(ix+x0))**2 + (yy-(iy+y0))**2 > exclusion**2)
|
|
108
|
+
second = float(np.max(response[competitors])) if competitors.any() else 0.
|
|
109
|
+
ratio = best / second if second > 0 else np.inf
|
|
110
|
+
snr = best / max(noise * np.sqrt(np.sum(kernel**2)), np.finfo(float).eps)
|
|
111
|
+
if snr < config.min_snr:
|
|
112
|
+
raise ValueError(f'Weak core S/N ({snr:.2f})')
|
|
113
|
+
if ratio < config.min_peak_ratio:
|
|
114
|
+
raise ValueError(f'Ambiguous competing cores (peak ratio {ratio:.3f})')
|
|
115
|
+
|
|
116
|
+
# Keep a fixed aperture size in every frame. Reject clipped/invalid apertures
|
|
117
|
+
# rather than mistakenly rewarding lost flux with a higher sharpness score.
|
|
118
|
+
ar = config.aperture_radius
|
|
119
|
+
if min(xy[0], xy[1], frame.shape[1]-1-xy[0], frame.shape[0]-1-xy[1]) < ar:
|
|
120
|
+
raise ValueError('Quality aperture extends outside exposure')
|
|
121
|
+
ax0, ax1 = int(np.floor(xy[0]-ar)), int(np.ceil(xy[0]+ar))+1
|
|
122
|
+
ay0, ay1 = int(np.floor(xy[1]-ar)), int(np.ceil(xy[1]+ar))+1
|
|
123
|
+
ay, ax = np.mgrid[ay0:ay1, ax0:ax1]
|
|
124
|
+
mask = (ax-xy[0])**2 + (ay-xy[1])**2 <= ar**2
|
|
125
|
+
values = frame[ay0:ay1, ax0:ax1][mask]
|
|
126
|
+
if not np.isfinite(values).all():
|
|
127
|
+
raise ValueError('Nonfinite pixels in quality aperture')
|
|
128
|
+
if config.saturation is not None and np.any(values >= config.saturation):
|
|
129
|
+
raise ValueError('Saturated reference-star aperture')
|
|
130
|
+
flux = float(np.sum(values-background))
|
|
131
|
+
cx, cy = int(round(xy[0])), int(round(xy[1]))
|
|
132
|
+
core = frame[cy-1:cy+2, cx-1:cx+2]-background
|
|
133
|
+
peak = float(core.max())
|
|
134
|
+
if flux <= 0 or peak <= 0:
|
|
135
|
+
raise ValueError('Nonpositive reference-star flux or peak')
|
|
136
|
+
# A concentrated single detector spike is not a resolved stellar core.
|
|
137
|
+
if np.clip(core, 0, None).sum() / peak < 2.0:
|
|
138
|
+
raise ValueError('Core is dominated by an isolated pixel spike')
|
|
139
|
+
return CoreMeasurement(xy, float(snr), float(ratio), peak, flux, background)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def core_translation(frame, reference, reference_core, config, min_correlation):
|
|
143
|
+
background, noise = background_stats(frame)
|
|
144
|
+
# Median filtering is used only for coarse tracking, never for final data.
|
|
145
|
+
moving = median_filter(np.where(np.isfinite(frame), frame, background), size=3)
|
|
146
|
+
fixed = median_filter(np.where(np.isfinite(reference), reference,
|
|
147
|
+
reference_core.background), size=3)
|
|
148
|
+
coarse, correlation = match_translation(
|
|
149
|
+
moving, fixed, background, reference_core.background, min_correlation,
|
|
150
|
+
)
|
|
151
|
+
predicted = reference_core.xy - coarse[:2, 2]
|
|
152
|
+
measured = locate_core(frame, predicted, config, background=background, noise=noise)
|
|
153
|
+
matrix = np.eye(3)
|
|
154
|
+
matrix[:2, 2] = reference_core.xy - measured.xy
|
|
155
|
+
return matrix, correlation, measured
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def ideal_peak_fraction(ideal_psf, aperture_radius):
|
|
159
|
+
"""Ideal sampled peak / flux in the same circular aperture as observations.
|
|
160
|
+
|
|
161
|
+
Caller supplies a background-free theoretical PSF sampled at the detector
|
|
162
|
+
pixel scale and appropriate to its wavelength and pupil. No optical model
|
|
163
|
+
is inferred from uncalibrated FITS headers.
|
|
164
|
+
"""
|
|
165
|
+
psf = np.asarray(ideal_psf, dtype=float)
|
|
166
|
+
if psf.ndim != 2 or not np.isfinite(psf).all() or np.any(psf < 0) or psf.max() <= 0:
|
|
167
|
+
raise ValueError('ideal_psf must be a finite nonnegative 2-D PSF with positive flux')
|
|
168
|
+
y, x = np.unravel_index(np.argmax(psf), psf.shape)
|
|
169
|
+
if min(x, y, psf.shape[1]-1-x, psf.shape[0]-1-y) < aperture_radius:
|
|
170
|
+
raise ValueError('ideal_psf must contain the full quality aperture around its peak')
|
|
171
|
+
yy, xx = np.indices(psf.shape)
|
|
172
|
+
flux = psf[(xx-x)**2+(yy-y)**2 <= aperture_radius**2].sum()
|
|
173
|
+
return float(psf.max()/flux)
|
pastrastack/detection.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Conservative source detection and background-subtracted centroids."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from astropy.stats import sigma_clipped_stats
|
|
7
|
+
from scipy.ndimage import gaussian_filter, maximum_filter
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class DetectionConfig:
|
|
12
|
+
smoothing_sigma: float = 2.5
|
|
13
|
+
threshold_sigma: float = 5.0
|
|
14
|
+
min_separation: int = 12
|
|
15
|
+
centroid_radius: int = 5
|
|
16
|
+
max_stars: int = 20
|
|
17
|
+
saturation: float | None = None
|
|
18
|
+
|
|
19
|
+
def __post_init__(self):
|
|
20
|
+
if not np.isfinite(self.smoothing_sigma) or self.smoothing_sigma <= 0:
|
|
21
|
+
raise ValueError("smoothing_sigma must be positive and finite")
|
|
22
|
+
if not np.isfinite(self.threshold_sigma) or self.threshold_sigma <= 0:
|
|
23
|
+
raise ValueError("threshold_sigma must be positive and finite")
|
|
24
|
+
for name in ("min_separation", "centroid_radius", "max_stars"):
|
|
25
|
+
value = getattr(self, name)
|
|
26
|
+
if not isinstance(value, (int, np.integer)) or value < 1:
|
|
27
|
+
raise ValueError(f"{name} must be a positive integer")
|
|
28
|
+
if self.saturation is not None and not np.isfinite(self.saturation):
|
|
29
|
+
raise ValueError("saturation must be finite")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class StarCatalog:
|
|
34
|
+
xy: np.ndarray
|
|
35
|
+
flux: np.ndarray
|
|
36
|
+
background: float
|
|
37
|
+
noise: float
|
|
38
|
+
|
|
39
|
+
def __len__(self):
|
|
40
|
+
return len(self.xy)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def detect_stars(image, config=None):
|
|
44
|
+
"""Return sources in descending flux order, with zero-based (x, y) positions.
|
|
45
|
+
|
|
46
|
+
Smoothing suppresses isolated noise peaks. Shape/area checks reject single
|
|
47
|
+
hot pixels, but speckles and blends can still require user-tuned settings.
|
|
48
|
+
"""
|
|
49
|
+
config = config or DetectionConfig()
|
|
50
|
+
image = np.asarray(image, dtype=float)
|
|
51
|
+
if image.ndim != 2:
|
|
52
|
+
raise ValueError("detect_stars expects a 2-D image")
|
|
53
|
+
valid = np.isfinite(image)
|
|
54
|
+
if not valid.any():
|
|
55
|
+
return StarCatalog(np.empty((0, 2)), np.empty(0), np.nan, np.nan)
|
|
56
|
+
_, background, noise = sigma_clipped_stats(image[valid], sigma=3)
|
|
57
|
+
clean = np.where(valid, image - background, 0.0)
|
|
58
|
+
smooth = gaussian_filter(clean, config.smoothing_sigma)
|
|
59
|
+
threshold = max(config.threshold_sigma * noise, np.finfo(float).eps)
|
|
60
|
+
peaks = (smooth == maximum_filter(smooth, size=2 * config.min_separation + 1))
|
|
61
|
+
yy, xx = np.where(peaks & (smooth > threshold))
|
|
62
|
+
positions, fluxes = [], []
|
|
63
|
+
radius = config.centroid_radius
|
|
64
|
+
for y, x in sorted(zip(yy, xx), key=lambda p: smooth[p], reverse=True):
|
|
65
|
+
if min(x, y, image.shape[1] - 1 - x, image.shape[0] - 1 - y) < radius:
|
|
66
|
+
continue
|
|
67
|
+
raw = image[y-radius:y+radius+1, x-radius:x+radius+1]
|
|
68
|
+
if not np.isfinite(raw).all():
|
|
69
|
+
continue
|
|
70
|
+
if config.saturation is not None and np.any(raw >= config.saturation):
|
|
71
|
+
continue
|
|
72
|
+
weights = np.clip(raw - background, 0, None)
|
|
73
|
+
flux = weights.sum()
|
|
74
|
+
if flux <= 0 or np.count_nonzero(weights > 3 * noise) < 3:
|
|
75
|
+
continue
|
|
76
|
+
if flux / max(weights.max(), np.finfo(float).eps) < 2.5:
|
|
77
|
+
continue
|
|
78
|
+
gy, gx = np.mgrid[y-radius:y+radius+1, x-radius:x+radius+1]
|
|
79
|
+
xy = np.array([(gx * weights).sum(), (gy * weights).sum()]) / flux
|
|
80
|
+
if any(np.linalg.norm(xy - previous) < config.min_separation for previous in positions):
|
|
81
|
+
continue
|
|
82
|
+
positions.append(xy)
|
|
83
|
+
fluxes.append(flux)
|
|
84
|
+
order = np.argsort(fluxes)[::-1][:config.max_stars]
|
|
85
|
+
return StarCatalog(
|
|
86
|
+
np.asarray(positions).reshape(-1, 2)[order], np.asarray(fluxes)[order],
|
|
87
|
+
float(background), float(noise),
|
|
88
|
+
)
|
pastrastack/drizzling.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Square-drop Drizzle of original detector pixels using STScI's implementation.
|
|
2
|
+
|
|
3
|
+
No bilinear pre-shifting is performed. Matrices map input pixel centres into
|
|
4
|
+
reference coordinates; the pixmap maps those centres directly to the output
|
|
5
|
+
array. Counts are scaled by output_scale**2, preserving the flux convention
|
|
6
|
+
when changing pixel area. Missing input pixels carry zero statistical weight.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def drizzle_backend():
|
|
13
|
+
try:
|
|
14
|
+
import drizzle
|
|
15
|
+
from drizzle.resample import Drizzle
|
|
16
|
+
except ImportError as exc:
|
|
17
|
+
raise ImportError(
|
|
18
|
+
"Drizzle stacking requires the optional dependency: "
|
|
19
|
+
"install pastrastack[drizzle] (or install this checkout with '.[drizzle]')."
|
|
20
|
+
) from exc
|
|
21
|
+
return Drizzle, drizzle.__version__
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def drizzle_frame(frame, matrix, output_shape, origin_xy, output_scale, pixfrac):
|
|
25
|
+
"""Return weighted numerator and overlap weights for one original exposure.
|
|
26
|
+
|
|
27
|
+
Multiplying Drizzle's mean by its weights preserves the sufficient statistics
|
|
28
|
+
needed to combine any later selection without drizzling that frame again.
|
|
29
|
+
Coverage is obtained from weight > 0, not from the values of science pixels.
|
|
30
|
+
The library operates in float32; subsequent pipeline sums use float64.
|
|
31
|
+
"""
|
|
32
|
+
Drizzle, _ = drizzle_backend()
|
|
33
|
+
yy, xx = np.indices(frame.shape, dtype=np.float64)
|
|
34
|
+
pixmap = np.empty((*frame.shape, 2), dtype=np.float64)
|
|
35
|
+
pixmap[..., 0] = (matrix[0, 0]*xx + matrix[0, 1]*yy + matrix[0, 2] - origin_xy[0]) / output_scale
|
|
36
|
+
pixmap[..., 1] = (matrix[1, 0]*xx + matrix[1, 1]*yy + matrix[1, 2] - origin_xy[1]) / output_scale
|
|
37
|
+
valid = np.isfinite(frame)
|
|
38
|
+
drizzled = Drizzle(kernel='square', out_shape=output_shape, fillval=0., disable_ctx=True)
|
|
39
|
+
drizzled.add_image(
|
|
40
|
+
data=np.where(valid, frame, 0.).astype(np.float32),
|
|
41
|
+
exptime=1., in_units='cps', pixmap=pixmap,
|
|
42
|
+
weight_map=valid.astype(np.float32), wht_scale=1.,
|
|
43
|
+
pixfrac=pixfrac, pixel_scale_ratio=output_scale, iscale=output_scale**2,
|
|
44
|
+
)
|
|
45
|
+
weight = drizzled.out_wht
|
|
46
|
+
numerator = np.where(weight > 0, drizzled.out_img, 0.) * weight
|
|
47
|
+
return numerator, weight
|
pastrastack/io.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Read selected cube layers without loading an entire scaled FITS cube."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from astropy.io import fits
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def validate_indices(indices, length):
|
|
10
|
+
if indices is None:
|
|
11
|
+
return np.arange(length, dtype=int)
|
|
12
|
+
values = np.asarray(indices)
|
|
13
|
+
if values.ndim != 1 or not len(values) or values.dtype.kind not in "iu":
|
|
14
|
+
raise ValueError("frame_indices must be a nonempty sequence of integers")
|
|
15
|
+
if np.any(values < 0) or np.any(values >= length):
|
|
16
|
+
raise ValueError("frame_indices are outside the cube")
|
|
17
|
+
if len(np.unique(values)) != len(values):
|
|
18
|
+
raise ValueError("frame_indices must not contain duplicates")
|
|
19
|
+
return values.astype(int)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def read_cube(source, frame_indices=None, hdu=0):
|
|
23
|
+
if isinstance(source, (str, Path)):
|
|
24
|
+
with fits.open(source, memmap=False) as hdus:
|
|
25
|
+
image = hdus[hdu]
|
|
26
|
+
if image.shape is None or len(image.shape) != 3:
|
|
27
|
+
raise ValueError("Expected a FITS cube with shape (exposures, height, width)")
|
|
28
|
+
indices = validate_indices(frame_indices, image.shape[0])
|
|
29
|
+
# .section handles BZERO/BSCALE and avoids loading unrequested layers.
|
|
30
|
+
frames = np.stack([
|
|
31
|
+
np.asarray(image.section[int(i), :, :], dtype=np.float64)
|
|
32
|
+
for i in indices
|
|
33
|
+
])
|
|
34
|
+
else:
|
|
35
|
+
frames = np.asarray(source)
|
|
36
|
+
if frames.ndim != 3 or frames.shape[0] == 0:
|
|
37
|
+
raise ValueError("Expected a nonempty cube with shape (exposures, height, width)")
|
|
38
|
+
indices = validate_indices(frame_indices, frames.shape[0])
|
|
39
|
+
frames = frames[indices].astype(np.float64, copy=True)
|
|
40
|
+
if min(frames.shape[1:]) < 8:
|
|
41
|
+
raise ValueError("Exposure dimensions must each be at least 8 pixels")
|
|
42
|
+
return frames, indices
|