epimetheus-psf 0.8.2__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.
epimetheus/builder.py ADDED
@@ -0,0 +1,1799 @@
1
+ from dataclasses import dataclass
2
+ from typing import Optional, List, Literal, Tuple, Dict
3
+ import numpy as np
4
+ from scipy.optimize import minimize
5
+ from scipy.ndimage import map_coordinates
6
+ from photutils.centroids import centroid_2dg
7
+ from tqdm import tqdm
8
+ import matplotlib.pyplot as plt
9
+ from matplotlib.colors import AsinhNorm
10
+ from drizzle.resample import Drizzle
11
+ from astropy.stats import sigma_clipped_stats
12
+ import warnings
13
+ import os
14
+ from astropy.io import fits
15
+ import warnings
16
+
17
+ from .common import block_reduce
18
+
19
+ from .core import (
20
+ StarCutouts,
21
+ process_cutout,
22
+ normalize_cutout,
23
+ build_pixmap,
24
+ center_index,
25
+ harmonic_mean_weight
26
+ )
27
+
28
+ def extract_centered_symmetric(arr: np.ndarray,
29
+ center_rc: Tuple[float, float],
30
+ shape: Tuple[int, int]) -> np.ndarray:
31
+ """
32
+ Symmetric crop around center_rc (float), with zero padding.
33
+ Rule:
34
+ - pixel-centered center (integer coords) -> odd crop
35
+ - inter-pixel center (half-integer coords) -> even crop
36
+ """
37
+ cy, cx = map(float, center_rc)
38
+ sy, sx = map(int, shape)
39
+
40
+ fy, fx = cy - np.floor(cy), cx - np.floor(cx)
41
+ if np.isclose(fy, 0.0) and np.isclose(fx, 0.0):
42
+ want_odd = True
43
+ elif np.isclose(fy, 0.5) and np.isclose(fx, 0.5):
44
+ want_odd = False
45
+ else:
46
+ raise ValueError(
47
+ f"center_rc={center_rc} must be either integer-like or half-integer-like in both axes."
48
+ )
49
+
50
+ if ((sy % 2 == 1) != want_odd) or ((sx % 2 == 1) != want_odd):
51
+ parity = "odd" if want_odd else "even"
52
+ raise ValueError(
53
+ f"center_rc={center_rc} requires a {parity} cutout shape, but shape is {shape}"
54
+ )
55
+
56
+ out = np.zeros((sy, sx), dtype=arr.dtype)
57
+
58
+ y0 = int(np.floor(cy - (sy - 1) / 2.0))
59
+ x0 = int(np.floor(cx - (sx - 1) / 2.0))
60
+ y1, x1 = y0 + sy, x0 + sx
61
+
62
+ ay0, ax0 = max(0, y0), max(0, x0)
63
+ ay1, ax1 = min(arr.shape[0], y1), min(arr.shape[1], x1)
64
+
65
+ if ay1 > ay0 and ax1 > ax0:
66
+ oy0, ox0 = ay0 - y0, ax0 - x0
67
+ out[oy0:oy0 + (ay1 - ay0), ox0:ox0 + (ax1 - ax0)] = arr[ay0:ay1, ax0:ax1]
68
+
69
+ return out
70
+
71
+
72
+ @dataclass
73
+ class RefinementResult:
74
+ """Results from iterative PSF refinement."""
75
+ n_iterations: int
76
+ shift_corrections: List[np.ndarray]
77
+ total_shifts: List[np.ndarray]
78
+ rms_correction_per_iteration: np.ndarray
79
+ epsf_fwhm_per_iteration: np.ndarray
80
+ epsf_history: List[np.ndarray]
81
+ final_epsf: np.ndarray
82
+ converged: bool
83
+ valid_indices: List[int]
84
+
85
+ class EPIBuilder:
86
+ """
87
+ Builds effective PSF (ePSF) through iterative shift refinement and stacking.
88
+
89
+ IMPORTANT: This class does NOT modify the original cutouts. All shifts and
90
+ elaborated cutouts are stored internally.
91
+
92
+ Resampling backend
93
+ -------------------
94
+ Each star's native-resolution cutout is resampled directly onto the
95
+ final ePSF grid with the `drizzle` package (`drizzle_resample_star`),
96
+ which applies the native->final rescaling, the fitted shift, and the
97
+ rotation (best_pa [+ measured fine rotation]) in a single pass. This
98
+ replaced the older "upsample onto a supersampled grid with
99
+ scipy.ndimage.affine_transform, then block-reduce" approach, which had
100
+ two problems this class now avoids:
101
+
102
+ * ``star.scale_factor`` < 1 (final grid finer than the native image)
103
+ was silently mishandled — the "native -> final" ratio is now
104
+ always computed as ``1.0 / star.scale_factor``, which is correct
105
+ for scale_factor either >= 1 or < 1 (see ``drizzle_resample_star``
106
+ in core.py).
107
+ * The intermediate supersampled grid could be off-center by a
108
+ fraction of a pixel whenever the upsampling factor wasn't an
109
+ exact integer. Drizzling straight onto the final grid removes the
110
+ intermediate step entirely, so there's nothing to mis-center.
111
+ """
112
+
113
+ DEFAULT_MAX_SHIFT = 5.0 # px (native)
114
+ DEFAULT_FIT_ORDER = 5
115
+ DEFAULT_K_SIGMA = 3.0
116
+ DEFAULT_MAXITERS = 10
117
+ DEFAULT_NORM_RADIUS = 1.0 # arcsec
118
+ DEFAULT_PIXFRAC = 0.6
119
+ DEFAULT_KERNEL = "gaussian"
120
+
121
+ def __init__(self, cutouts: StarCutouts, norm_radius: float = DEFAULT_NORM_RADIUS,
122
+ pixfrac: float = DEFAULT_PIXFRAC, kernel: str = DEFAULT_KERNEL):
123
+ self.cutouts = cutouts
124
+ self.norm_radius = norm_radius
125
+ self.pixfrac = pixfrac
126
+ self.kernel = kernel
127
+ warnings.filterwarnings("ignore", message="Kernel 'gaussian' is not a flux-conserving kernel")
128
+ self.current_epsf: Optional[np.ndarray] = None
129
+ self._last_refinement: Optional[RefinementResult] = None
130
+
131
+ # Internal storage (does NOT modify original cutouts)
132
+ self._shifts: Dict[int, Tuple[float, float]] = {}
133
+ self._fit_amplitudes: Dict[int, float] = {}
134
+
135
+ #Contains the builded epsf
136
+ self.epsf_angle0 = None
137
+
138
+ # Initialize with original values
139
+ self._initialize_from_cutouts()
140
+
141
+ def _initialize_from_cutouts(self) -> None:
142
+ """Copy initial shifts and elaborated cutouts from original cutouts."""
143
+ self._shifts.clear()
144
+ self._fit_amplitudes.clear()
145
+
146
+ self._pixmaps = {}
147
+ self._native_weight_working = {}
148
+ self._native_flux_scale = {}
149
+
150
+
151
+ for i, star in enumerate(self.cutouts.stars):
152
+ if star is not None and star.is_valid == 1 and not star.mask:
153
+ # Copy shift (NATIVE pixel units)
154
+ if star.shift is not None:
155
+ self._shifts[i] = star.shift
156
+
157
+ def reset(self) -> None:
158
+ """Reset internal storage to original cutout values."""
159
+ self._initialize_from_cutouts()
160
+ self.current_epsf = None
161
+ self._last_refinement = None
162
+
163
+ # =========================================================================
164
+ # VALID STAR UTILITIES
165
+ # =========================================================================
166
+
167
+ def get_valid_indices(self) -> List[int]:
168
+ """Get indices of valid stars for stacking."""
169
+ return [
170
+ i for i, star in enumerate(self.cutouts.stars)
171
+ if star is not None
172
+ and star.is_valid == 1
173
+ and not star.mask
174
+ and star.cutout is not None
175
+ ]
176
+
177
+ def get_n_valid(self) -> int:
178
+ """Return number of valid stars."""
179
+ return len(self.get_valid_indices())
180
+
181
+ def _get_shift(self, star_index: int) -> Tuple[float, float]:
182
+ """Get shift (NATIVE pixel units) from internal storage or fall back to original."""
183
+ if star_index in self._shifts:
184
+ return self._shifts[star_index]
185
+ star = self.cutouts.stars[star_index]
186
+ if star is not None and star.shift is not None:
187
+ return star.shift
188
+ return (0.0, 0.0)
189
+
190
+ def _align_star_internal(self,
191
+ star_index: int,
192
+ shift: Tuple[float, float],
193
+ final_angle: float = 0.0,
194
+ fine_rotation: bool = False,
195
+ normalize: bool = True,
196
+ norm_radius: float = 1.0) -> None:
197
+ """
198
+ Prepare ONE star for shared drizzle stacking.
199
+
200
+ Does NOT resample the star onto the final grid as a standalone
201
+ "final" product. Instead it:
202
+ - computes and caches this star's NATIVE -> FINAL `pixmap`
203
+ (`self._pixmaps[star_index]`), needed both to add this star's
204
+ NATIVE data into the shared multi-image Drizzle object in
205
+ `stack()`, and to translate output-grid pixel rejections back
206
+ into native-pixel weight zeroing;
207
+ - seeds a mutable working copy of the NATIVE weight map
208
+ (`self._native_weight_working[star_index]`), from
209
+ `star.cutout_wht` with `star.cutout_mask` applied. `stack()`'s
210
+ rejection loop progressively zeroes entries in this array; it
211
+ is the ONLY thing rejection is allowed to mutate;
212
+ - drizzles the NATIVE data (single star, single image) onto the
213
+ final grid purely as a per-star STATISTICS image for outlier
214
+ detection in `stack()` -- this is never treated as a final
215
+ combined product on its own.
216
+
217
+ ``shift`` is in NATIVE pixel units. `star.cutout` / `star.cutout_wht`
218
+ (the originals) are read but never modified.
219
+ """
220
+ star = self.cutouts.stars[star_index]
221
+ best_pa = star.best_pa if star.best_pa is not None else 0
222
+
223
+ conv_factor = 1.0 / float(star.scale_factor)
224
+ rot_angle = best_pa - final_angle
225
+ if fine_rotation and star.rotation is not None:
226
+ rot_angle -= star.rotation
227
+
228
+ shift_native = np.asarray(shift, dtype=float)
229
+ shift_out = tuple(shift_native * conv_factor)
230
+
231
+ final_size = tuple(int(s)*self.cutouts.upsample_factor for s in self.cutouts.cutout_shape)
232
+
233
+ pixmap = build_pixmap(
234
+ shape_in=star.cutout.shape,
235
+ shape_out=final_size,
236
+ shift=shift_out,
237
+ angle_deg=rot_angle,
238
+ scale_factor=conv_factor,
239
+ )
240
+
241
+ if star.cutout_wht is not None:
242
+ working_weight = np.asarray(star.cutout_wht, dtype=np.float32).copy()
243
+ working_weight[~np.isfinite(working_weight)] = 0.0
244
+ working_weight[working_weight < 0] = 0.0
245
+ else:
246
+ working_weight = np.ones_like(star.cutout, dtype=np.float32)
247
+
248
+ if star.cutout_mask is not None:
249
+ working_weight[star.cutout_mask] = 0.0
250
+
251
+ if not hasattr(self, '_pixmaps'):
252
+ self._pixmaps = {}
253
+ if not hasattr(self, '_native_weight_working'):
254
+ self._native_weight_working = {}
255
+ if not hasattr(self, '_native_flux_scale'):
256
+ self._native_flux_scale = {}
257
+
258
+ self._pixmaps[star_index] = pixmap
259
+ self._native_weight_working[star_index] = working_weight
260
+
261
+ # Single-star statistics drizzle (native -> final), for REJECTION
262
+ # PURPOSES ONLY.
263
+ driz = Drizzle(kernel=self.kernel, out_shape=final_size, fillval="0.0")
264
+ driz.add_image(
265
+ data=np.asarray(star.cutout, dtype=np.float32),
266
+ exptime=1.0,
267
+ pixmap=pixmap,
268
+ weight_map=working_weight,
269
+ pixfrac=self.pixfrac,
270
+ in_units="cps",
271
+ )
272
+ reduced_image = np.nan_to_num(driz.out_img, nan=0.0).astype(np.float64)/conv_factor**2 # scale down area
273
+ reduced_wht = np.nan_to_num(driz.out_wht, nan=0.0).astype(np.float64)*conv_factor**4 # scale down area
274
+
275
+
276
+ flux_scale = 1.0
277
+
278
+ if normalize and star_index in self._fit_amplitudes:
279
+ amp = max(self._fit_amplitudes[star_index], 1e-12)
280
+ flux_scale = 1.0 / amp
281
+
282
+ reduced_image = reduced_image * flux_scale
283
+ reduced_wht = reduced_wht / (flux_scale ** 2)
284
+
285
+ elif normalize:
286
+ valid = reduced_wht > 0
287
+ flux_init = reduced_image[valid].sum() if np.any(valid) else 0.0
288
+
289
+ reduced_image, reduced_wht = normalize_cutout(
290
+ cutout=reduced_image,
291
+ cutout_wht=reduced_wht,
292
+ norm_radius=norm_radius,
293
+ final_resolution=self.cutouts.final_resolution
294
+ )
295
+
296
+ flux_after = reduced_image[valid].sum() if np.any(valid) else 1.0
297
+
298
+ flux_scale = flux_after/flux_init
299
+
300
+ self._native_flux_scale[star_index] = flux_scale
301
+ star.cutout_elaborated_builder = reduced_image
302
+ star.cutout_wht_elaborated_builder = reduced_wht
303
+
304
+
305
+ # =========================================================================
306
+ # ePSF METRICS
307
+ # =========================================================================
308
+
309
+ def compute_fwhm(self, epsf: np.ndarray, method: str = 'half_max',
310
+ n_radial_samples: int = 500, n_angular_samples: int = 360) -> float:
311
+ """
312
+ Compute FWHM of the ePSF at subpixel resolution.
313
+
314
+ Parameters
315
+ ----------
316
+ epsf : np.ndarray
317
+ 2D ePSF image.
318
+ method : str
319
+ Method to use: 'half_max' (interpolated) or 'gaussian' (fit).
320
+ n_radial_samples : int
321
+ Number of radial samples for interpolation. Default is 500.
322
+ n_angular_samples : int
323
+ Number of angular samples for azimuthal averaging. Default is 360.
324
+
325
+ Returns
326
+ -------
327
+ float
328
+ FWHM in pixels.
329
+ """
330
+ from scipy.interpolate import UnivariateSpline
331
+ from scipy.optimize import brentq
332
+
333
+ center = (np.array(epsf.shape) - 1) / 2.0
334
+ r_max = min(center) * 0.95 # Stay slightly inside image
335
+
336
+ # Create fine radial grid
337
+ r_fine = np.linspace(0, r_max, n_radial_samples)
338
+ theta = np.linspace(0, 2 * np.pi, n_angular_samples, endpoint=False)
339
+
340
+ # Sample image at subpixel positions using bilinear interpolation
341
+ radial_profile = np.zeros(n_radial_samples)
342
+
343
+ for i, r in enumerate(r_fine):
344
+ if r == 0:
345
+ # At center, just take the center pixel value (interpolated)
346
+ radial_profile[i] = map_coordinates(epsf, [[center[0]], [center[1]]],
347
+ order=3, mode='constant')[0]
348
+ else:
349
+ # Sample at n_angular_samples points around the circle
350
+ y_coords = center[0] + r * np.sin(theta)
351
+ x_coords = center[1] + r * np.cos(theta)
352
+
353
+ # Interpolate values at these coordinates
354
+ values = map_coordinates(epsf, [y_coords, x_coords],
355
+ order=3, mode='constant')
356
+ radial_profile[i] = np.mean(values)
357
+
358
+ if method == 'half_max':
359
+ peak = np.max(radial_profile)
360
+ half_max = peak / 2
361
+
362
+ # Check if profile ever drops below half_max
363
+ if np.all(radial_profile > half_max):
364
+ return r_max * 2
365
+
366
+ # Create smooth spline interpolation
367
+ spline = UnivariateSpline(r_fine, radial_profile, s=0, k=3)
368
+
369
+ # Find where profile crosses half_max
370
+ above_half = radial_profile > half_max
371
+ if not np.any(~above_half):
372
+ return r_fine[-1] * 2
373
+
374
+ first_below_idx = np.argmax(~above_half)
375
+ if first_below_idx == 0:
376
+ return r_fine[0] * 2
377
+
378
+ # Bracket the root
379
+ r_low = r_fine[first_below_idx - 1]
380
+ r_high = r_fine[first_below_idx]
381
+
382
+ # Extend bracket slightly if needed
383
+ while spline(r_low) < half_max and first_below_idx > 1:
384
+ first_below_idx -= 1
385
+ r_low = r_fine[first_below_idx - 1]
386
+
387
+ while spline(r_high) > half_max and first_below_idx < len(r_fine) - 1:
388
+ first_below_idx += 1
389
+ r_high = r_fine[first_below_idx]
390
+
391
+ # Use Brent's method to find exact crossing point
392
+ try:
393
+ r_half = brentq(lambda r: spline(r) - half_max, r_low, r_high)
394
+ except ValueError:
395
+ # Fallback to linear interpolation if brentq fails
396
+ p1, p2 = radial_profile[first_below_idx - 1], radial_profile[first_below_idx]
397
+ r1, r2 = r_fine[first_below_idx - 1], r_fine[first_below_idx]
398
+ if p1 != p2:
399
+ r_half = r1 + (half_max - p1) * (r2 - r1) / (p2 - p1)
400
+ else:
401
+ r_half = (r1 + r2) / 2
402
+
403
+ return 2 * r_half
404
+
405
+ else: # gaussian fit
406
+ from scipy.optimize import curve_fit
407
+
408
+ def gaussian(r, amp, sigma, offset):
409
+ return amp * np.exp(-r ** 2 / (2 * sigma ** 2)) + offset
410
+
411
+ try:
412
+ p0 = [np.max(radial_profile) - np.min(radial_profile),
413
+ 2.0,
414
+ np.min(radial_profile)]
415
+ popt, _ = curve_fit(gaussian, r_fine, radial_profile, p0=p0, maxfev=2000)
416
+ sigma = abs(popt[1])
417
+ return 2.355 * sigma # FWHM = 2*sqrt(2*ln(2)) * sigma
418
+ except Exception:
419
+ # Fallback to half_max method
420
+ return self.compute_fwhm(epsf, method='half_max')
421
+
422
+ def compute_encircled_energy(self,
423
+ epsf: np.ndarray,
424
+ fractions: List[float] = [0.5, 0.8, 0.9]) -> dict:
425
+ """Compute encircled energy radii."""
426
+ center = (np.array(epsf.shape) - 1) / 2.0
427
+ y, x = np.ogrid[:epsf.shape[0], :epsf.shape[1]]
428
+ r = np.sqrt((x - center[1]) ** 2 + (y - center[0]) ** 2)
429
+
430
+ r_flat = r.flatten()
431
+ epsf_flat = epsf.flatten()
432
+ sort_idx = np.argsort(r_flat)
433
+ r_sorted = r_flat[sort_idx]
434
+ epsf_sorted = epsf_flat[sort_idx]
435
+
436
+ cumsum = np.cumsum(epsf_sorted)
437
+ total = cumsum[-1]
438
+
439
+ results = {}
440
+ for frac in fractions:
441
+ target = frac * total
442
+ idx = np.searchsorted(cumsum, target)
443
+ results[frac] = r_sorted[min(idx, len(r_sorted) - 1)]
444
+
445
+ return results
446
+
447
+ # =========================================================================
448
+ # STACKING
449
+ # =========================================================================
450
+
451
+ def stack(self,
452
+ rejection_mode: Literal['none', 'weighted', 'mad'] = 'mad',
453
+ k_sigma: float = DEFAULT_K_SIGMA,
454
+ maxiters_rejection: int = 2,
455
+ remove_background: bool = True,
456
+ verbose: bool = True) -> np.ndarray:
457
+ """
458
+ Combine all stars prepared by `_align_star_internal` into a single
459
+ ePSF.
460
+
461
+ Rejection (per output pixel, across stars) is driven by each star's
462
+ single-image statistics drizzle (`star.cutout_elaborated_builder`). An
463
+ output-pixel outlier for a given star is converted back to NATIVE
464
+ pixels via that star's forward `pixmap` and zeroed in
465
+ `self._native_weight_working[star_idx]` -- `star.cutout` /
466
+ `star.cutout_wht` are never touched.
467
+
468
+ The FINAL image is produced by ONE shared `Drizzle` object: every
469
+ star's ORIGINAL NATIVE cutout is added via its own `add_image` call
470
+ (native data, rejection-pruned native weight, native->final pixmap),
471
+ all accumulating onto the same output grid in a single pass. This is
472
+ what actually uses the cross-star sub-pixel dithering -- collapsing
473
+ each star to the final grid separately first and only then
474
+ co-adding would not.
475
+ """
476
+ valid_indices = [
477
+ i for i in self.get_valid_indices()
478
+ if getattr(self.cutouts.stars[i], 'cutout_elaborated_builder', None) is not None
479
+ and i in getattr(self, '_pixmaps', {})
480
+ ]
481
+
482
+ if len(valid_indices) == 0:
483
+ raise ValueError("No aligned stars available for stacking "
484
+ "(call _align_star_internal first)")
485
+
486
+ n_stars = len(valid_indices)
487
+ final_size = tuple(int(s)*self.cutouts.upsample_factor for s in self.cutouts.cutout_shape)
488
+
489
+ # Per-star statistics images/weights on the output grid -- used ONLY
490
+ # to decide which NATIVE pixels to reject, never combined directly.
491
+ stat_images = np.nan_to_num(
492
+ np.stack([self.cutouts.stars[i].cutout_elaborated_builder for i in valid_indices], axis=0),
493
+ nan=0.0
494
+ ).astype(np.float64)
495
+ stat_weights = np.stack(
496
+ [np.nan_to_num(self.cutouts.stars[i].cutout_wht_elaborated_builder, nan=0.0) for i in valid_indices],
497
+ axis=0
498
+ ).astype(np.float64)
499
+ stat_weights[stat_weights < 0] = 0.0
500
+
501
+ for iteration in range(max(1, maxiters_rejection)):
502
+ if rejection_mode == 'none' or n_stars < 3:
503
+ break
504
+
505
+ active = stat_weights > 0
506
+ n_active_before = int(np.sum(active))
507
+ if n_active_before == 0:
508
+ break
509
+
510
+ if rejection_mode == 'mad':
511
+ masked = np.where(active, stat_images, np.nan)
512
+ with warnings.catch_warnings():
513
+ warnings.filterwarnings(
514
+ 'ignore', message='All-NaN slice encountered', category=RuntimeWarning
515
+ )
516
+ with np.errstate(invalid='ignore'):
517
+ center = np.nanmedian(masked, axis=0)
518
+ sigma = 1.4826 * np.nanmedian(np.abs(masked - center[None, ...]), axis=0)
519
+
520
+ else: # 'weighted'
521
+ with np.errstate(invalid='ignore', divide='ignore'):
522
+ wsum = np.sum(stat_weights, axis=0)
523
+ center = np.divide(np.sum(stat_weights * stat_images, axis=0), wsum,
524
+ out=np.zeros(final_size), where=wsum > 0)
525
+ resid = np.where(active, stat_images - center[None, ...], np.nan)
526
+ with warnings.catch_warnings():
527
+ warnings.filterwarnings('ignore', category=RuntimeWarning)
528
+ sigma = np.nanstd(resid, axis=0)
529
+
530
+ n_contrib = np.sum(active, axis=0)
531
+ sigma = np.where((sigma > 0) & np.isfinite(sigma) & (n_contrib >= 2), sigma, np.inf)
532
+
533
+ deviation = np.abs(stat_images - center[None, ...])
534
+ outliers = active & (deviation > k_sigma * sigma[None, ...])
535
+
536
+ if not np.any(outliers):
537
+ if verbose:
538
+ print(f" Rejection converged after {iteration + 1} iteration(s)")
539
+ break
540
+
541
+ for pos, star_idx in enumerate(valid_indices):
542
+ star_outliers = outliers[pos]
543
+ if not np.any(star_outliers):
544
+ continue
545
+
546
+ stat_weights[pos][star_outliers] = 0.0
547
+ stat_images[pos][star_outliers] = 0.0
548
+
549
+ pixmap = self._pixmaps[star_idx]
550
+ out_x = np.round(pixmap[..., 0]).astype(int)
551
+ out_y = np.round(pixmap[..., 1]).astype(int)
552
+ in_bounds = (
553
+ (out_x >= 0) & (out_x < final_size[1]) &
554
+ (out_y >= 0) & (out_y < final_size[0])
555
+ )
556
+ native_reject = np.zeros(out_x.shape, dtype=bool)
557
+ native_reject[in_bounds] = star_outliers[out_y[in_bounds], out_x[in_bounds]]
558
+
559
+ self._native_weight_working[star_idx][native_reject] = 0.0
560
+
561
+ n_active_after = int(np.sum(stat_weights > 0))
562
+ if verbose:
563
+ print(f" Iter {iteration + 1}: rejected "
564
+ f"{n_active_before - n_active_after} pixel-contribution(s)")
565
+
566
+ if n_active_after == n_active_before:
567
+ break
568
+
569
+ # ------------------------------------------------------------------
570
+ # Final combination: ONE shared Drizzle object, every star's NATIVE
571
+ # data added together in a single accumulation pass.
572
+ # ------------------------------------------------------------------
573
+
574
+ max_inv_k2 = max(1.0 / (self._native_flux_scale.get(i, 1.0) * star.scale_factor**2)**2 for i, star in enumerate(self.cutouts.stars) if i in valid_indices)
575
+
576
+
577
+ driz = Drizzle(kernel=self.kernel, out_shape=final_size, fillval="0.0")
578
+ for star_idx in valid_indices:
579
+ star = self.cutouts.stars[star_idx]
580
+ flux_scale = self._native_flux_scale.get(star_idx, 1.0)
581
+
582
+
583
+ k_factor = flux_scale * star.scale_factor**2
584
+
585
+
586
+ # This normalizes the weights so the maximum weight multiplier is around 1.0
587
+ norm_weight_modifier = (1.0 / (k_factor ** 2)) / max_inv_k2
588
+
589
+ """driz_2 = Drizzle(kernel=self.kernel, out_shape=final_size, fillval="0.0")
590
+ driz_2.add_image(
591
+ data=np.asarray(star.cutout, dtype=np.float32) * k_factor,
592
+ exptime=1.0,
593
+ pixmap=self._pixmaps[star_idx],
594
+ weight_map=np.asarray(self._native_weight_working[star_idx], dtype=np.float32) * norm_weight_modifier,
595
+ pixfrac=self.pixfrac,
596
+ in_units="cps",
597
+ )"""
598
+
599
+ driz.add_image(
600
+ data=np.asarray(star.cutout, dtype=np.float32) * k_factor,
601
+ exptime=1.0,
602
+ pixmap=self._pixmaps[star_idx],
603
+ weight_map = np.asarray(self._native_weight_working[star_idx], dtype=np.float32) * norm_weight_modifier,
604
+ pixfrac=self.pixfrac,
605
+ in_units="cps",
606
+ )
607
+
608
+ """plt.figure()
609
+ plt.subplot(131)
610
+ plt.imshow(driz_2.out_img,norm=AsinhNorm(1e-7,0,3e-3),origin="lower",cmap="magma")
611
+ plt.subplot(132)
612
+ plt.imshow(block_reduce(driz_2.out_img,4)[90:110,90:110],origin="lower",cmap="magma")
613
+ plt.subplot(133)
614
+ plt.imshow(block_reduce(driz.out_img,4)[90:110,90:110],origin="lower",cmap="magma")
615
+ plt.show()
616
+
617
+ print(np.median(driz_2.out_wht), np.median(star.cutout_wht), star.scale_factor)"""
618
+
619
+
620
+ stacked = np.nan_to_num(driz.out_img, nan=0.0).astype(np.float64)
621
+
622
+ """plt.figure()
623
+ plt.title("stacked")
624
+ plt.imshow(stacked,norm=AsinhNorm(1e-7,0,3e-3),origin="lower",cmap="magma")
625
+ plt.colorbar()
626
+ plt.show()"""
627
+
628
+ if remove_background:
629
+ __, bkg, __ = sigma_clipped_stats(stacked)
630
+ stacked = stacked - bkg
631
+
632
+ stacked = stacked/np.sum(stacked)
633
+
634
+ # Persist rejection-pruned stat weights for inspection.
635
+ for pos, star_idx in enumerate(valid_indices):
636
+ self.cutouts.stars[star_idx].cutout_wht_elaborated_builder = stat_weights[pos]
637
+ self.cutouts.stars[star_idx].cutout_weights_rej_builder = np.asarray(self._native_weight_working[star_idx], dtype=np.float32)
638
+
639
+ return stacked
640
+
641
+ # =========================================================================
642
+ # SHIFT FITTING
643
+ # =========================================================================
644
+ def _fit_shift_to_original(self,
645
+ star_index: int,
646
+ epsf: np.ndarray,
647
+ fwhm: float,
648
+ fwhm_fraction: float = 3.0,
649
+ max_shift: float = DEFAULT_MAX_SHIFT,
650
+ fit_order: int = DEFAULT_FIT_ORDER) -> Tuple[float, float]:
651
+ """
652
+ Fit the TOTAL shift (in NATIVE pixels) needed to align the original
653
+ native-resolution cutout to the current ePSF.
654
+
655
+ 1. crop a high-resolution patch from the ePSF,
656
+ 2. rotate it into the star's native orientation, still at high-res,
657
+ 3. apply the trial subpixel shift on that high-res grid,
658
+ 4. block-reduce back to native resolution,
659
+ 5. fit amplitude analytically (background offset fixed to 0).
660
+
661
+ Notes
662
+ -----
663
+ - Returned shifts are in NATIVE pixel units.
664
+ - The fitted amplitude is stored in `self._fit_amplitudes[star_index]`.
665
+ If you want to use it for normalization, scale the star by 1/amplitude.
666
+ - Background offset is NOT fitted; it is fixed to 0.
667
+ - This version is consistent with refinement done in the canonical
668
+ `final_angle=0` frame with `fine_rotation=False`, i.e. the inverse
669
+ rotation applied here is just `+best_pa`.
670
+ """
671
+
672
+ star = self.cutouts.stars[star_index]
673
+
674
+ if star is None or star.cutout is None:
675
+ raise ValueError("Star is not extracted, cannot fit.")
676
+
677
+ centroid_radius = max(int(round((fwhm * fwhm_fraction * star.scale_factor - 1)/2)),1)
678
+ #so if images of different scales the physical psf size in the same , with different number of pixels. Indeed fwhm is measured on the upsample images
679
+
680
+ # Native -> ePSF magnification
681
+ native_to_epsf = 1.0 / float(star.scale_factor)
682
+
683
+ # Use integer block reduction only when the upsampling is effectively integer
684
+ upsamp_int = max(1,int(round(native_to_epsf)))
685
+ use_block_reduce = (
686
+ upsamp_int > 1 and
687
+ np.isclose(native_to_epsf, upsamp_int, rtol=0.0, atol=1e-6)
688
+ )
689
+
690
+ # ------------------------------------------------------------------
691
+ # Native fitting patch from the original cutout
692
+ # ------------------------------------------------------------------
693
+
694
+ if star.scale_factor>1:
695
+ if np.isclose(star.scale_factor, int(np.round(star.scale_factor))):
696
+ data_reducing_factor = int(np.round(star.scale_factor))
697
+ img = block_reduce(star.cutout, data_reducing_factor , func = np.sum)
698
+
699
+ if star.cutout_wht is not None:
700
+ img_wht = block_reduce(star.cutout_wht, data_reducing_factor, func = harmonic_mean_weight)
701
+ else:
702
+ img_wht = None
703
+
704
+ if star.cutout_mask is not None:
705
+ img_mask = block_reduce(star.cutout_mask, data_reducing_factor, func = np.min)
706
+ else:
707
+ img_mask = None
708
+ else:
709
+ raise NotImplementedError(f"star.scale_factor is {star.scale_factor} which is not integer")
710
+ else:
711
+ data_reducing_factor = 1
712
+ img = star.cutout
713
+ img_wht = star.cutout_wht
714
+ img_mask = star.cutout_mask
715
+
716
+
717
+ center_native = center_index(img.shape[0]), center_index(img.shape[1])
718
+
719
+ if img.shape[0] % 2 == 0:
720
+ patch_size = 2 * centroid_radius + 2
721
+ else:
722
+ patch_size = 2 * centroid_radius + 1
723
+
724
+
725
+ if np.shape(img)[0] != np.shape(img)[1]:
726
+ self._fit_amplitudes[star_index] = 1e-12
727
+ return 0.0, 0.0, (np.zeros((patch_size,patch_size)), np.zeros((patch_size,patch_size)))
728
+
729
+
730
+ data = extract_centered_symmetric(img, center_rc=center_native, shape=(patch_size,patch_size)).astype(np.float64)
731
+
732
+
733
+ if img_mask is not None:
734
+ mask_data = extract_centered_symmetric(img_mask, center_rc=center_native, shape=(patch_size,patch_size)).astype(bool)
735
+ else:
736
+ mask_data = np.zeros_like(data, dtype=bool)
737
+
738
+ if img_wht is not None:
739
+ wht = extract_centered_symmetric(img_wht, center_rc=center_native, shape=(patch_size,patch_size)).astype(np.float64)
740
+ wht[~np.isfinite(wht)] = 0.0
741
+ wht[wht < 0] = 0.0
742
+ else:
743
+ wht = np.ones_like(data, dtype=np.float64)
744
+
745
+ wht[mask_data] = 0.0
746
+ valid = wht > 0
747
+
748
+ """plt.figure()
749
+ plt.subplot(131)
750
+ plt.imshow(data)
751
+ plt.subplot(132)
752
+ plt.imshow(mask_data)
753
+ plt.subplot(133)
754
+ plt.imshow(wht)
755
+ plt.show()"""
756
+
757
+ if not np.any(valid):
758
+ if not hasattr(self, "_fit_amplitudes"):
759
+ self._fit_amplitudes = {}
760
+ self._fit_amplitudes[star_index] = 1.0
761
+ return 0.0, 0.0, (data, np.zeros_like(data))
762
+
763
+ wht_sum = np.sum(wht)
764
+ wht_norm = wht / wht_sum if wht_sum > 0 else np.ones_like(wht) / wht.size
765
+
766
+ # Consistent with refine_shifts(... final_angle=0, fine_rotation=False)
767
+ rot_angle = star.best_pa if star.best_pa is not None else 0.0
768
+
769
+ # ------------------------------------------------------------------
770
+ # Build a high-resolution, native-orientation PSF patch
771
+ # ------------------------------------------------------------------
772
+ margin_interp = int(np.ceil(fit_order / 2.0)) + 2
773
+ hr_core_size = max(patch_size, 3) * upsamp_int
774
+
775
+ epsf_radius = int(np.ceil((fwhm * fwhm_fraction - 1) / 2 + max_shift * self.cutouts.upsample_factor)) + margin_interp
776
+
777
+ epsf_center = center_index(epsf.shape[0]), center_index(epsf.shape[1])
778
+ center_is_integer = np.isclose(epsf_center[0] % 1.0, 0.0)
779
+
780
+ epsf_cutout_size = max(
781
+ int(np.ceil(epsf_radius / self.cutouts.upsample_factor)) * self.cutouts.upsample_factor,
782
+ hr_core_size
783
+ )
784
+
785
+ if ((epsf_cutout_size % 2 == 1) != center_is_integer):
786
+ epsf_cutout_size += 1
787
+
788
+ epsf_crop_hr = extract_centered_symmetric(
789
+ epsf,
790
+ center_rc=(epsf_center[0], epsf_center[1]),
791
+ shape=(epsf_cutout_size,epsf_cutout_size)
792
+ )
793
+
794
+ if use_block_reduce:
795
+
796
+ # Rotate to the star's native orientation, but KEEP the high-res grid
797
+ psf_hr_native = process_cutout(
798
+ data=epsf_crop_hr,
799
+ shift=(0.0, 0.0),
800
+ angle=rot_angle,
801
+ scale_factor=1.0,
802
+ output_shape=epsf_crop_hr.shape,
803
+ order=fit_order
804
+ )
805
+
806
+ center_hr = center_index(epsf_cutout_size)
807
+ pad0 = int(np.floor(center_hr - (hr_core_size - 1) / 2.0))
808
+ core_slice = (slice(pad0, pad0 + hr_core_size), slice(pad0, pad0 + hr_core_size))
809
+
810
+ def build_model(shift_x_native: float, shift_y_native: float) -> np.ndarray:
811
+ # Apply shift on the HIGH-RES grid first
812
+ shift_x_hr = shift_x_native * upsamp_int
813
+ shift_y_hr = shift_y_native * upsamp_int
814
+
815
+ shifted_hr = process_cutout(
816
+ data=psf_hr_native,
817
+ shift=(shift_y_hr, shift_x_hr),
818
+ angle=0.0,
819
+ scale_factor=1.0,
820
+ output_shape=psf_hr_native.shape,
821
+ order=fit_order
822
+ )
823
+
824
+ core_hr = shifted_hr[core_slice]
825
+
826
+ model_native = block_reduce(
827
+ core_hr,
828
+ block_size=(upsamp_int, upsamp_int),
829
+ func=np.sum
830
+ )
831
+ model_native = np.asarray(model_native, dtype=np.float64)
832
+
833
+ if model_native.shape != (patch_size, patch_size):
834
+ raise ValueError(
835
+ f"[star {star_index}] block_reduce produced shape "
836
+ f"{model_native.shape}, expected ({patch_size}, {patch_size}). "
837
+ f"hr_core_size={hr_core_size}, upsamp_int={upsamp_int}."
838
+ )
839
+
840
+ return model_native
841
+
842
+ else:
843
+ scale_factor = min(1, star.scale_factor)#scale_factor>1 are already computed separately by blocking reduce the image
844
+
845
+ psf_hr_native = process_cutout(
846
+ data=epsf_crop_hr,
847
+ shift=(0.0, 0.0),
848
+ angle=rot_angle,
849
+ scale_factor=scale_factor, # fine -> native
850
+ output_shape=(patch_size, patch_size),
851
+ order=fit_order
852
+ )
853
+
854
+ def build_model(shift_x_native: float, shift_y_native: float) -> np.ndarray:
855
+ model_native = process_cutout(
856
+ data=psf_hr_native,
857
+ shift=(shift_y_native, shift_x_native),
858
+ angle=0.0,
859
+ scale_factor=1.0,
860
+ output_shape=psf_hr_native.shape,
861
+ order=fit_order
862
+ )
863
+ return np.asarray(model_native, dtype=np.float64)
864
+
865
+ """plt.figure()
866
+ plt.subplot(131)
867
+ plt.suptitle("PSF")
868
+ plt.imshow(epsf_crop_hr)
869
+ plt.subplot(132)
870
+ plt.imshow(psf_hr_native)
871
+ plt.subplot(133)
872
+ plt.imshow(data)
873
+ plt.show()"""
874
+
875
+ # ------------------------------------------------------------------
876
+ # Weighted linear solve for amplitude at fixed shift
877
+ # (background offset is fixed to 0, NOT fitted)
878
+ # ------------------------------------------------------------------
879
+ def solve_amplitude(model: np.ndarray) -> float:
880
+ m = model[valid].ravel()
881
+ d = data[valid].ravel()
882
+ ww = wht[valid].ravel()
883
+
884
+ if m.size == 0:
885
+ return 1.0
886
+
887
+ # Weighted least squares for a single scale parameter:
888
+ # minimize sum(w * (d - amp*m)^2) -> amp = sum(w*m*d) / sum(w*m^2)
889
+ denom = np.sum(ww * m * m)
890
+ if denom > 0:
891
+ amp = float(np.sum(ww * m * d) / denom)
892
+ else:
893
+ amp = 1.0
894
+
895
+ # Optional positivity constraint on amplitude
896
+ if not np.isfinite(amp) or amp < 0:
897
+ amp = 0.0
898
+
899
+ return amp
900
+
901
+ def residual(shift_params: np.ndarray) -> float:
902
+ shift_x, shift_y = shift_params
903
+ model = build_model(shift_x, shift_y)
904
+ amp = solve_amplitude(model)
905
+ resid = data - amp * model
906
+ return float(np.sum(wht_norm * resid ** 2))
907
+
908
+ # ------------------------------------------------------------------
909
+ # Optimize shift only; amplitude solved analytically, offset = 0
910
+ # ------------------------------------------------------------------
911
+ max_shift_star = max_shift * self.cutouts.upsample_factor / upsamp_int
912
+ #same shift in science for each star
913
+
914
+ result = minimize(
915
+ residual,
916
+ x0=np.array([0.0, 0.0], dtype=float),
917
+ method='Powell',
918
+ bounds=[(-max_shift_star, max_shift_star), (-max_shift_star, max_shift_star)]
919
+ )
920
+
921
+ if result.success:
922
+ shift_x, shift_y = float(result.x[0]), float(result.x[1])
923
+ best_model = build_model(shift_x, shift_y)
924
+ best_amp = solve_amplitude(best_model)
925
+
926
+ """print(star_index, shift_x,shift_y)
927
+ fig, (ax1,ax2,ax3,ax4) = plt.subplots(1,4,figsize=(8,2))
928
+ im1 = ax1.imshow(data/np.sum(data),origin="lower",cmap="magma")
929
+ ax2.imshow((best_model*best_amp)/np.sum(data),origin="lower",cmap="magma")
930
+ try:
931
+ ax3.imshow(block_reduce(psf_hr_native[core_slice],upsamp_int, np.sum)/np.sum(psf_hr_native[core_slice]),origin="lower",cmap="magma")
932
+ shift_img = process_cutout(data,(-shift_y, -shift_x))
933
+ ax4.imshow(shift_img/np.sum(data),origin="lower",cmap="magma")
934
+ except:
935
+ pass
936
+ plt.show()"""
937
+
938
+ else:
939
+ # Fallback: centroid on native cutout patch
940
+ if star.cutout_wht is not None:
941
+ with np.errstate(divide='ignore', invalid='ignore'):
942
+ error = np.sqrt(1.0 / (wht + 1e-50))
943
+ finite = np.isfinite(error)
944
+ if np.any(finite):
945
+ error[~finite] = np.nanmax(error[finite])
946
+ else:
947
+ error = None
948
+ else:
949
+ error = None
950
+
951
+ cx, cy = centroid_2dg(data, error=error, mask=mask_data)
952
+ shift_x = float(cx - center_index(patch_size))
953
+ shift_y = float(cy - center_index(patch_size))
954
+
955
+ best_model = build_model(shift_x, shift_y)
956
+ best_amp = solve_amplitude(best_model)
957
+
958
+ """fig, (ax1,ax2) = plt.subplots(1,2)
959
+ im1 = ax1.imshow(data/np.sum(data),norm=AsinhNorm(1e-5,0,0.1),origin="lower",cmap="magma")
960
+ ax2.imshow((best_model*best_amp)/np.sum(data),norm=AsinhNorm(1e-5,0,0.1),origin="lower",cmap="magma")
961
+ plt.show()"""
962
+
963
+ #residuals = data-(best_model*best_amp)
964
+
965
+ # Store amplitude for later normalization use
966
+ if not hasattr(self, "_fit_amplitudes"):
967
+ self._fit_amplitudes = {}
968
+ self._fit_amplitudes[star_index] = max(float(best_amp), 1e-12)
969
+
970
+ # fitted model shift -> total star alignment shift
971
+ # return to the data original shift frame
972
+ return -shift_y*data_reducing_factor, -shift_x*data_reducing_factor, (data, best_model*best_amp)
973
+
974
+ def _recenter_epsf(self,
975
+ epsf: np.ndarray,
976
+ fwhm: float,
977
+ fwhm_fraction: float = 1.0,
978
+ order: int = 3,
979
+ max_iter: int = 10,
980
+ shift_tol: float = 1e-4) -> Tuple[np.ndarray, Tuple[float, float]]:
981
+ """
982
+ Recenter ePSF so its centroid (from a 2D Gaussian fit) sits at the
983
+ array's geometric center, iterating until convergence.
984
+
985
+ Target parity is fixed by array shape:
986
+ - odd size -> geometric center is an integer pixel (pixel-centered)
987
+ - even size -> geometric center is a half-integer (inter-pixel corner)
988
+
989
+ The fitting window is built with matching parity so it is always
990
+ symmetric around that fixed target, regardless of where the star
991
+ currently sits.
992
+
993
+ At each iteration the centroid offset is measured on the current
994
+ recentered estimate; the *cumulative* offset is then re-applied to the
995
+ original (unshifted) array, so the star only ever passes through a
996
+ single resampling relative to its original position (avoiding repeated
997
+ interpolation blur from re-shifting an already-shifted image).
998
+
999
+ Iterates until the incremental offset is below `shift_tol` (in pixels)
1000
+ or `max_iter` iterations are reached.
1001
+ """
1002
+ epsf = np.asarray(epsf, dtype=np.float64)
1003
+ epsf_copy = epsf.copy()
1004
+ epsf_copy[~np.isfinite(epsf_copy)] = 0.0
1005
+
1006
+ ny, nx = epsf_copy.shape
1007
+ geom_center = (np.array(epsf_copy.shape, dtype=float) - 1.0) / 2.0
1008
+ cy, cx = geom_center
1009
+
1010
+ # Parity is a fixed property of the array shape, not of where the star sits.
1011
+ want_odd_y = (ny % 2 == 1)
1012
+ want_odd_x = (nx % 2 == 1)
1013
+ if want_odd_y != want_odd_x:
1014
+ raise ValueError(
1015
+ f"epsf shape {epsf_copy.shape} has mixed odd/even axes; "
1016
+ "extract_centered_symmetric requires matching parity on both axes."
1017
+ )
1018
+ want_odd = want_odd_y
1019
+
1020
+ total = np.maximum(epsf_copy, 0.0).sum()
1021
+ if total <= 0:
1022
+ return epsf_copy.copy(), (0.0, 0.0)
1023
+
1024
+ # Window size, forced to match the array's fixed parity
1025
+ half_width = max(fwhm_fraction * fwhm, 2.0)
1026
+ box_size = int(np.ceil(2 * half_width)) + 1
1027
+
1028
+ if (want_odd and box_size % 2 == 0) or ((not want_odd) and box_size % 2 == 1):
1029
+ box_size += 1
1030
+
1031
+ # Crop origin in the full-array frame (matches extract_centered_symmetric's
1032
+ # own placement formula) so we can convert local fits back to absolute coords.
1033
+ y0 = int(np.floor(cy - (box_size - 1) / 2.0))
1034
+ x0 = int(np.floor(cx - (box_size - 1) / 2.0))
1035
+
1036
+ def _measure_offset(image: np.ndarray) -> Tuple[float, float]:
1037
+ """Return (offset_y, offset_x) of image's centroid from geom_center,
1038
+ or None if the measurement failed."""
1039
+ core = extract_centered_symmetric(image, (cy, cx), (box_size, box_size))
1040
+ if core.sum() <= 0:
1041
+ return None
1042
+
1043
+ try:
1044
+ x_local, y_local = centroid_2dg(core)
1045
+ except Exception:
1046
+ return None
1047
+
1048
+ if not (np.isfinite(x_local) and np.isfinite(y_local)):
1049
+ return None
1050
+
1051
+ centroid_y = y_local + y0
1052
+ centroid_x = x_local + x0
1053
+ return (centroid_y - cy, centroid_x - cx)
1054
+
1055
+ current = epsf_copy
1056
+ total_offset_y, total_offset_x = 0.0, 0.0
1057
+ converged = False
1058
+
1059
+ for _ in range(max_iter):
1060
+ measured = _measure_offset(current)
1061
+ if measured is None:
1062
+ # Fit failed on the first iteration -> bail out safely as before.
1063
+ if total_offset_y == 0.0 and total_offset_x == 0.0:
1064
+ return epsf.copy(), (0.0, 0.0)
1065
+ # Otherwise keep the best estimate obtained so far.
1066
+ break
1067
+
1068
+ offset_y, offset_x = measured
1069
+ step = np.hypot(offset_y, offset_x)
1070
+
1071
+ if step < shift_tol:
1072
+ converged = True
1073
+ break
1074
+
1075
+ total_offset_y += offset_y
1076
+ total_offset_x += offset_x
1077
+
1078
+ # Re-derive the recentered image from the ORIGINAL array using the
1079
+ # cumulative offset, so only one resampling is ever applied.
1080
+ current = process_cutout(
1081
+ data=epsf_copy,
1082
+ shift=(-total_offset_y, -total_offset_x),
1083
+ angle=0.0,
1084
+ scale_factor=1.0,
1085
+ output_shape=epsf_copy.shape,
1086
+ order=order
1087
+ )
1088
+
1089
+ if total_offset_y == 0.0 and total_offset_x == 0.0:
1090
+ # Either converged immediately, or nothing ever moved.
1091
+ return epsf_copy.copy(), (0.0, 0.0)
1092
+
1093
+ return current, (total_offset_y, total_offset_x)
1094
+
1095
+ def _propagate_epsf_recentering_to_shifts(self,
1096
+ offset_epsf: Tuple[float, float],
1097
+ star_indices: Optional[List[int]] = None) -> None:
1098
+ """
1099
+ Propagate an ePSF-frame recentering into the stored native-pixel shifts.
1100
+
1101
+ Parameters
1102
+ ----------
1103
+ offset_epsf : Tuple[float, float]
1104
+ (offset_y, offset_x) returned by `_recenter_epsf`, i.e.
1105
+ centroid - geometric_center, in ePSF/final-grid pixels.
1106
+ star_indices : list[int] or None
1107
+ Which stars to update. If None, update all valid stars.
1108
+ """
1109
+ if star_indices is None:
1110
+ star_indices = self.get_valid_indices()
1111
+
1112
+ offset_epsf = np.asarray(offset_epsf, dtype=float)
1113
+
1114
+ for star_idx in star_indices:
1115
+ star = self.cutouts.stars[star_idx]
1116
+ old_shift = np.asarray(self._get_shift(star_idx), dtype=float)
1117
+
1118
+ # Convert ePSF-pixel offset -> native-pixel offset
1119
+ offset_native = offset_epsf * float(star.scale_factor)
1120
+
1121
+ # Important: add the raw centroid offset here.
1122
+ # This keeps the stored shifts consistent with the recentered PSF frame.
1123
+ new_shift = old_shift - offset_native
1124
+
1125
+ self._shifts[star_idx] = (float(new_shift[0]), float(new_shift[1]))
1126
+
1127
+ def refine_shifts(self,
1128
+ n_iterations: int = DEFAULT_MAXITERS,
1129
+ rejection_mode: Literal['none', 'weighted', 'mad'] = 'mad',
1130
+ k_sigma: float = DEFAULT_K_SIGMA,
1131
+ max_shift: float = DEFAULT_MAX_SHIFT,
1132
+ fit_order: int = DEFAULT_FIT_ORDER,
1133
+ maxiters_rejection: int = 2,
1134
+ convergence_threshold: float = 0.01,
1135
+ fwhm_fraction: int = 3, #the cutout size in fwhm to align fit the psf to te stars
1136
+ recenter_epsf: bool = True,
1137
+ remove_background: bool = True,
1138
+ normalize: bool = True,
1139
+ verbose: bool = True) -> RefinementResult:
1140
+ """
1141
+ Iteratively refine star shifts by fitting original cutouts to stacked ePSF.
1142
+
1143
+ This does NOT modify the original cutouts. All changes are
1144
+ stored internally in self._shifts and self._elaborated.
1145
+ """
1146
+ self._initialize_from_cutouts()
1147
+
1148
+ valid_indices = self.get_valid_indices()
1149
+ n_valid = len(valid_indices)
1150
+
1151
+ if n_valid == 0:
1152
+ raise ValueError("No valid stars for refinement")
1153
+
1154
+ if verbose:
1155
+ print(f"{'=' * 60}")
1156
+ print("Starting iterative shift refinement")
1157
+ print(f" Valid stars: {n_valid}")
1158
+ print(f" Max iterations: {n_iterations}")
1159
+ print(f" Rejection: {rejection_mode}, k_sigma={k_sigma}")
1160
+ print(f" Recenter ePSF: {recenter_epsf}")
1161
+ print(f" Convergence threshold: {convergence_threshold} px")
1162
+ print(f"{'=' * 60}")
1163
+
1164
+
1165
+ for star_idx in valid_indices:
1166
+ self._align_star_internal(
1167
+ star_idx,
1168
+ shift = self._get_shift(star_idx),
1169
+ final_angle=0.0,
1170
+ fine_rotation=False,
1171
+ normalize=normalize,
1172
+ norm_radius=self.norm_radius
1173
+ )
1174
+
1175
+ epsf_initial = self.stack(rejection_mode=rejection_mode, k_sigma=k_sigma,
1176
+ maxiters_rejection=maxiters_rejection, verbose=verbose, remove_background=remove_background)
1177
+
1178
+ fwhm_initial = self.compute_fwhm(epsf_initial)
1179
+
1180
+ if recenter_epsf:
1181
+ epsf_initial, initial_offset = self._recenter_epsf(epsf_initial, fwhm=fwhm_initial)
1182
+ if verbose:
1183
+ print(f" Initial ePSF recentered by: ({initial_offset[0]:.4f}, {initial_offset[1]:.4f}) px")
1184
+
1185
+ self.current_epsf = epsf_initial
1186
+
1187
+
1188
+ if verbose:
1189
+ print(f" Initial FWHM: {fwhm_initial:.3f} px")
1190
+
1191
+ shift_corrections = []
1192
+ total_shifts = []
1193
+ rms_history = []
1194
+ fwhm_history = [fwhm_initial]
1195
+ epsf_history = [epsf_initial.copy()]
1196
+ epsf_offsets = [] # Track offsets for debugging
1197
+ converged = False
1198
+
1199
+ for iteration in range(n_iterations):
1200
+ if verbose:
1201
+ print(f"\n--- Iteration {iteration + 1}/{n_iterations} ---")
1202
+
1203
+ epsf = np.copy(self.current_epsf)
1204
+
1205
+ corrections = np.zeros((n_valid, 2))
1206
+ new_shifts = np.zeros((n_valid, 2))
1207
+
1208
+ iterator = tqdm(enumerate(valid_indices), total=n_valid,
1209
+ desc="Fitting shifts", disable=not verbose)
1210
+
1211
+ for i, star_idx in iterator:
1212
+ old_shift = np.array(self._get_shift(star_idx))
1213
+
1214
+ fitted_y, fitted_x, __ = self._fit_shift_to_original(
1215
+ star_idx, epsf,
1216
+ max_shift=max_shift,
1217
+ fit_order=fit_order,
1218
+ fwhm=fwhm_history[-1],
1219
+ fwhm_fraction = fwhm_fraction
1220
+ )
1221
+ new_shift = np.array([fitted_y, fitted_x])
1222
+
1223
+ correction = new_shift - old_shift
1224
+ corrections[i] = correction
1225
+ new_shifts[i] = new_shift
1226
+
1227
+ self._shifts[star_idx] = (fitted_y, fitted_x)
1228
+
1229
+ shift_corrections.append(corrections.copy())
1230
+ total_shifts.append(new_shifts.copy())
1231
+
1232
+ if verbose:
1233
+ print("Updating elaborated cutouts...")
1234
+
1235
+
1236
+ for star_idx in valid_indices:
1237
+ self._align_star_internal(
1238
+ star_idx,
1239
+ self._shifts[star_idx],
1240
+ final_angle=0.0,
1241
+ fine_rotation=False,
1242
+ normalize=normalize,
1243
+ norm_radius=self.norm_radius
1244
+ )
1245
+ epsf = self.stack(
1246
+ rejection_mode=rejection_mode,
1247
+ k_sigma=k_sigma,
1248
+ maxiters_rejection=maxiters_rejection,
1249
+ remove_background=remove_background,
1250
+ verbose=verbose
1251
+ )
1252
+
1253
+ """plt.imshow(epsf,norm=AsinhNorm(1e-5),origin="lower",cmap="magma")
1254
+ plt.colorbar()
1255
+ print(np.sum(epsf))
1256
+ plt.axhline(102.5)
1257
+ plt.axvline(102.5)
1258
+ plt.show()"""
1259
+
1260
+ fwhm = self.compute_fwhm(epsf)
1261
+
1262
+ if recenter_epsf:
1263
+
1264
+ epsf_rec, offset = self._recenter_epsf(epsf, fwhm=fwhm)
1265
+ epsf_offsets.append(offset)
1266
+ if verbose:
1267
+ print(f" ePSF recentered by: ({offset[0]:.4f}, {offset[1]:.4f}) px")
1268
+
1269
+
1270
+ """plt.subplot(121)
1271
+ plt.imshow(epsf[180:220,180:220])
1272
+ plt.subplot(122)
1273
+ plt.imshow(epsf_rec[180:220,180:220])
1274
+ plt.show()"""
1275
+
1276
+ epsf = epsf_rec
1277
+
1278
+ self.current_epsf = epsf
1279
+
1280
+ epsf_history.append(epsf.copy())
1281
+
1282
+ fwhm_history.append(fwhm)
1283
+ if verbose:
1284
+ print(f" ePSF FWHM: {fwhm:.3f} px")
1285
+
1286
+ # Check convergence
1287
+ rms_correction = np.sqrt(np.mean(corrections ** 2))
1288
+ rms_history.append(rms_correction)
1289
+
1290
+ if verbose:
1291
+ print(f" RMS correction: {rms_correction:.4f} px")
1292
+ print(f" Max correction: {np.max(np.abs(corrections)):.4f} px")
1293
+ # Show mean shift to detect drift
1294
+ mean_shift = np.mean(new_shifts, axis=0)
1295
+ print(f" Mean shift: ({mean_shift[0]:.4f}, {mean_shift[1]:.4f}) px")
1296
+
1297
+ if rms_correction < convergence_threshold:
1298
+ if verbose:
1299
+ print(f"\n✓ Converged after {iteration + 1} iterations")
1300
+ converged = True
1301
+ break
1302
+
1303
+ if recenter_epsf and len(epsf_offsets) > 0:
1304
+ self._propagate_epsf_recentering_to_shifts(np.array(epsf_offsets[-1]), valid_indices) # keep shifts consistent with current_epsf
1305
+
1306
+
1307
+ result = RefinementResult(
1308
+ n_iterations=len(shift_corrections),
1309
+ shift_corrections=shift_corrections,
1310
+ total_shifts=total_shifts,
1311
+ rms_correction_per_iteration=np.array(rms_history),
1312
+ epsf_fwhm_per_iteration=np.array(fwhm_history),
1313
+ epsf_history=epsf_history,
1314
+ final_epsf=self.current_epsf,
1315
+ converged=converged,
1316
+ valid_indices=valid_indices
1317
+ )
1318
+
1319
+ self._last_refinement = result
1320
+
1321
+ if verbose:
1322
+ print(f"\n{'=' * 60}")
1323
+ print(f"Refinement complete: {result.n_iterations} iterations")
1324
+ print(f"Converged: {result.converged}")
1325
+ print(f"{'=' * 60}")
1326
+
1327
+ return result
1328
+
1329
+ # =========================================================================
1330
+ # MULTI-ANGLE ePSF
1331
+ # =========================================================================
1332
+ def build_multi_angle_epsf(self,
1333
+ angles: Optional[Dict[str, float] | List[float]] = None,
1334
+ output_shape: Optional[Tuple[int, int] | np.ndarray] = None,
1335
+ rejection_mode: Literal['none', 'weighted', 'mad'] = 'mad',
1336
+ k_sigma: float = DEFAULT_K_SIGMA,
1337
+ maxiters_rejection: int = 2,
1338
+ fine_rotation: bool = False,
1339
+ remove_background: bool = True,
1340
+ normalize: bool = True,
1341
+ verbose: bool = True,
1342
+ show_plots: bool = True,
1343
+ save_fits: bool = True) -> Dict[str, np.ndarray]:
1344
+ """Build ePSF at multiple target angles.
1345
+
1346
+ Parameters
1347
+ ----------
1348
+ angles : Dict[str, float] or List[float] or None
1349
+ Target angles.
1350
+ - If dict: keys are names (e.g., field names), values are angles in degrees
1351
+ - If list: creates names as "angle_{a}" for each angle
1352
+ - If None: defaults to [0, 45, 90, 135]
1353
+ output_shape : Tuple[int, int] or np.ndarray or None
1354
+ If specified, crop the final ePSF to this shape (centered).
1355
+ If None, keep the original shape.
1356
+ rejection_mode : {'none', 'weighted', 'mad'}
1357
+ Rejection method for stacking. Default is 'mad'.
1358
+ k_sigma : float
1359
+ Sigma threshold for rejection. Default is 3.0.
1360
+ maxiters_rejection : int
1361
+ Maximum iterations for rejection algorithm. Default is 2.
1362
+ fine_rotation : bool
1363
+ If True, apply fine rotation correction. Default is False.
1364
+ normalize : bool
1365
+ If True, normalize each cutout by aperture flux. Default is True.
1366
+ verbose : bool
1367
+ Print progress. Default is True.
1368
+ show_plots : bool
1369
+ If True, displays visual plots using matplotlib. Default is True.
1370
+ save_fits : bool
1371
+ If True, saves FITS files into the cache directory. Default is True.
1372
+ base_name : str
1373
+ Prefix token for output filenames. Default is "epsf".
1374
+
1375
+ Returns
1376
+ -------
1377
+ Dict[str, np.ndarray]
1378
+ Dictionary mapping angle names to ePSF arrays.
1379
+ """
1380
+ if angles is None:
1381
+ angles = [0]
1382
+
1383
+ if isinstance(angles, list):
1384
+ angles_dict = {f"angle_{int(a)}": float(a) for a in angles}
1385
+ else:
1386
+ angles_dict = angles
1387
+
1388
+ if 0 not in angles_dict.values():
1389
+ angles_dict["angle_0"] = 0
1390
+
1391
+ valid_indices = self.get_valid_indices()
1392
+
1393
+ if len(valid_indices) == 0:
1394
+ raise ValueError("No valid stars for ePSF building")
1395
+
1396
+ crop_slice = None
1397
+ if output_shape is not None:
1398
+ output_shape = np.asarray(output_shape).copy()
1399
+ original_shape = np.asarray(self.cutouts.cutout_shape).copy()
1400
+
1401
+ if np.any(output_shape > original_shape):
1402
+ raise ValueError(
1403
+ f"output_shape {tuple(output_shape)} cannot be larger than "
1404
+ f"original shape {tuple(original_shape)}"
1405
+ )
1406
+
1407
+ # transform to upsample sizes
1408
+ original_shape *= self.cutouts.upsample_factor
1409
+ output_shape *= self.cutouts.upsample_factor
1410
+
1411
+ start = np.array([
1412
+ int(np.floor(center_index(original_shape[0]) - (output_shape[0] - 1) / 2.0)),
1413
+ int(np.floor(center_index(original_shape[1]) - (output_shape[1] - 1) / 2.0)),
1414
+ ])
1415
+ end = start + output_shape
1416
+ crop_slice = (slice(start[0], end[0]), slice(start[1], end[1]))
1417
+
1418
+
1419
+ if verbose:
1420
+ print(f"{'=' * 60}")
1421
+ print("Building multi-angle ePSF")
1422
+ print(f" Angles: {list(angles_dict.keys())}")
1423
+ print(f" Valid stars: {len(valid_indices)}")
1424
+ if output_shape is not None:
1425
+ print(f" Output shape: {tuple(output_shape)}")
1426
+ print(f"{'=' * 60}")
1427
+
1428
+ results = {}
1429
+ factor = getattr(self.cutouts, 'upsample_factor', 1)
1430
+
1431
+ # Determine target directory
1432
+ output_dir = os.path.join(getattr(self.cutouts, 'cache_dir'), "output_psf/")
1433
+
1434
+ if save_fits:
1435
+ os.makedirs(output_dir, exist_ok=True)
1436
+
1437
+ for name, target_angle in angles_dict.items():
1438
+ if verbose:
1439
+ print(f"\n--- {name} (PA = {target_angle}°) ---")
1440
+
1441
+ for star_idx in valid_indices:
1442
+ shift = np.array(self._get_shift(star_idx), dtype=float)
1443
+
1444
+ self._align_star_internal(
1445
+ star_idx,
1446
+ tuple(shift),
1447
+ final_angle=target_angle,
1448
+ fine_rotation=fine_rotation,
1449
+ normalize=normalize
1450
+ )
1451
+
1452
+ epsf = self.stack(
1453
+ rejection_mode=rejection_mode,
1454
+ k_sigma=k_sigma,
1455
+ maxiters_rejection=maxiters_rejection,
1456
+ remove_background=remove_background,
1457
+ verbose=verbose
1458
+ )
1459
+
1460
+ if crop_slice is not None:
1461
+ epsf = epsf[crop_slice]
1462
+
1463
+ s = np.sum(epsf)
1464
+ if s > 0:
1465
+ epsf = epsf / s
1466
+
1467
+ results[name] = epsf.copy()
1468
+
1469
+ if verbose:
1470
+ fwhm = self.compute_fwhm(epsf)
1471
+ print(f" FWHM: {fwhm:.3f} px")
1472
+ print(f" Shape: {epsf.shape}")
1473
+
1474
+ if target_angle==0:
1475
+ self.epsf_angle0=epsf
1476
+
1477
+ # --- SAVE FITS SECTION ---
1478
+ if save_fits:
1479
+ base_name = self.cutouts.name
1480
+ if factor > 1:
1481
+ # Save upsampled
1482
+ outpath_upsampled = os.path.join(output_dir, f"{base_name}_{name}_x{factor}sampled.fits")
1483
+ fits.PrimaryHDU(data=epsf).writeto(outpath_upsampled, overwrite=True)
1484
+
1485
+ # Save downscaled native resolution
1486
+ epsf_red = block_reduce(epsf, factor)
1487
+ outpath_native = os.path.join(output_dir, f"{base_name}_{name}.fits")
1488
+ fits.PrimaryHDU(data=epsf_red).writeto(outpath_native, overwrite=True)
1489
+ else:
1490
+ # Save native resolution directly
1491
+ outpath_native = os.path.join(output_dir, f"{base_name}_{name}.fits")
1492
+ fits.PrimaryHDU(data=epsf).writeto(outpath_native, overwrite=True)
1493
+
1494
+ if verbose and save_fits:
1495
+ print(f"\nSaved {len(results)} ePSF sets to {output_dir}")
1496
+
1497
+ # --- PLOTTING SECTION ---
1498
+ if show_plots and len(results) > 0:
1499
+ num_angles = len(results)
1500
+
1501
+ # Setup figures (Row 1: Main/upsampled, Row 2: Downscaled/Native if upsampled)
1502
+ rows = 2 if factor > 1 else 1
1503
+ fig, axes = plt.subplots(rows, num_angles, figsize=(5 * num_angles, 5 * rows), squeeze=False)
1504
+
1505
+ for col_idx, (name, epsf) in enumerate(results.items()):
1506
+ # Row 0: Full calculated resolution
1507
+ ax_top = axes[0, col_idx]
1508
+ im_top = ax_top.imshow(epsf, origin="lower", norm=AsinhNorm(1e-6, 0), cmap="magma")
1509
+ plt.colorbar(im_top, ax=ax_top, shrink=0.8)
1510
+ title_suffix = f" (x{factor} Sampled)" if factor > 1 else ""
1511
+ ax_top.set_title(f"{name}{title_suffix}")
1512
+
1513
+ # Row 1: Downscaled Native (only if factor > 1)
1514
+ if factor > 1:
1515
+ ax_bot = axes[1, col_idx]
1516
+ epsf_red = block_reduce(epsf, factor)
1517
+ im_bot = ax_bot.imshow(epsf_red, origin="lower", norm=AsinhNorm(1e-5, 0), cmap="magma")
1518
+ plt.colorbar(im_bot, ax=ax_bot, shrink=0.8)
1519
+ ax_bot.set_title(f"{name} (Native Res)")
1520
+
1521
+ plt.tight_layout()
1522
+ plt.show()
1523
+
1524
+ if verbose:
1525
+ print(f"\n{'=' * 60}")
1526
+ print(f"Generated {len(results)} ePSFs")
1527
+ print(f"{'=' * 60}")
1528
+
1529
+ return results
1530
+
1531
+ def get_fit_statistics(self,
1532
+ magnitude_field: str = "MAG_APER_1",
1533
+ qFit_region_size = 5): #5px x 5px crop, as in Jay Anderson
1534
+
1535
+ """
1536
+ Returns magnitudes, quality-of-fit and sharpness arrays
1537
+ """
1538
+
1539
+ if self.epsf_angle0 is None:
1540
+ raise ValueError("No ePSF generated"
1541
+ "(call build_multi_angle_epsf first)")
1542
+
1543
+ if qFit_region_size % 2 == 0:
1544
+ raise ValueError("qFit_cropSize must be an odd number")
1545
+
1546
+ print("Extracting the cutout for each star")
1547
+ self.cutouts.extract_all_cutouts(magnitude_field, extract_invalid_stars=True)
1548
+ self.cutouts.subtract_background_all()
1549
+
1550
+ fwhm = self.compute_fwhm(self.epsf_angle0)
1551
+ print("FWHM", fwhm)
1552
+
1553
+ print("Fitting...")
1554
+ q_fits = []
1555
+ C_fits = []
1556
+ mags = []
1557
+ scales = []
1558
+
1559
+ for star_idx in tqdm(range(len(self.cutouts.stars))):
1560
+
1561
+ shift_y, shift_x, (data, model) = self._fit_shift_to_original(
1562
+ star_idx,
1563
+ self.epsf_angle0,
1564
+ fwhm,
1565
+ fwhm_fraction=max(3, (qFit_region_size + self.DEFAULT_MAX_SHIFT)*self.cutouts.upsample_factor/fwhm) # force min size of residuals
1566
+ )
1567
+
1568
+ residual = data - model
1569
+
1570
+ cy = int(round(center_index(data.shape[0]) - shift_y))
1571
+ cx = int(round(center_index(data.shape[1]) - shift_x))
1572
+
1573
+ cy_clamped = max(0, min(cy, data.shape[0] - 1))
1574
+ cx_clamped = max(0, min(cx, data.shape[1] - 1))
1575
+ C_fit = residual[cy_clamped, cx_clamped] / self._fit_amplitudes[star_idx]
1576
+
1577
+ half_crop = qFit_region_size // 2
1578
+ y_min = cy - half_crop
1579
+ x_min = cx - half_crop
1580
+
1581
+ y1 = max(0, min(y_min, data.shape[0] - qFit_region_size))
1582
+ y2 = y1 + qFit_region_size
1583
+ x1 = max(0, min(x_min, data.shape[1] - qFit_region_size))
1584
+ x2 = x1 + qFit_region_size
1585
+
1586
+ res_qfit_cutout = residual[y1:y2, x1:x2]
1587
+ data_qfit_cutout = data[y1:y2, x1:x2]
1588
+ model_qfit_cutout = model[y1:y2, x1:x2]
1589
+
1590
+ q_fit = np.sum(np.abs(res_qfit_cutout)) / self._fit_amplitudes[star_idx]
1591
+
1592
+ # --- PLOT ---
1593
+
1594
+ """plt.style.use("article_style")
1595
+ plt.figure(figsize=(10,2))
1596
+ plt.suptitle(rf"$Q_f = {q_fit:.3f}$")
1597
+
1598
+ plt.subplot(131)
1599
+ plt.imshow(data_qfit_cutout, origin="lower", cmap="magma", vmin=0, vmax=np.max(data_qfit_cutout))
1600
+ plt.colorbar()
1601
+
1602
+ plt.subplot(132)
1603
+ # Usiamo direttamente il ritaglio del modello (model_qfit_cutout)
1604
+ plt.imshow(model_qfit_cutout, origin="lower", cmap="magma", vmin=0, vmax=np.max(data_qfit_cutout))
1605
+ plt.colorbar()
1606
+
1607
+ plt.subplot(133)
1608
+ m = np.max(np.abs(res_qfit_cutout))
1609
+ plt.imshow(res_qfit_cutout, origin="lower", cmap="coolwarm", vmin=-m, vmax=m)
1610
+ plt.colorbar()
1611
+
1612
+ plt.show()"""
1613
+
1614
+
1615
+ # 5. Salvataggio delle metriche
1616
+ q_fits.append(q_fit)
1617
+ C_fits.append(C_fit)
1618
+
1619
+ zero_point_mag = self.cutouts.image_collection.data[self.cutouts.stars[0].image_name].mag_zeropoint
1620
+ if zero_point_mag is None:
1621
+ zero_point_mag = 0 # instrumnetal magnitude
1622
+
1623
+ mags.append(-2.5 * np.log10(self._fit_amplitudes[star_idx]) + zero_point_mag)
1624
+
1625
+ scales.append(self.cutouts.stars[star_idx].scale_factor)
1626
+
1627
+
1628
+ return mags, q_fits, C_fits
1629
+
1630
+ #quality-of-fit statistic
1631
+ #extract a 5x5 crop
1632
+
1633
+
1634
+ # =========================================================================
1635
+ # PLOTTING
1636
+ # =========================================================================
1637
+
1638
+ def plot_convergence_results(self, figsize: Tuple[int, int] = (12, 8)) -> None:
1639
+ """Plot convergence diagnostics."""
1640
+ if self._last_refinement is None:
1641
+ print("No refinement history. Run refine_shifts() first.")
1642
+ return
1643
+
1644
+ result = self._last_refinement
1645
+ n_iter = result.n_iterations
1646
+
1647
+ fig, axes = plt.subplots(2, 2, figsize=figsize)
1648
+
1649
+ # Plot 1: RMS correction
1650
+ ax = axes[0, 0]
1651
+ ax.plot(range(1, n_iter + 1), result.rms_correction_per_iteration, 'o-',
1652
+ lw=2, markersize=8, color='C0')
1653
+ ax.set_xlabel('Iteration')
1654
+ ax.set_ylabel('RMS Shift Correction (pixels)')
1655
+ ax.set_title('Corrections convergence')
1656
+ ax.grid(True, alpha=0.3)
1657
+ ax.set_xticks(range(1, n_iter + 1))
1658
+ ax.set_yscale('log')
1659
+
1660
+ # Plot 2: FWHM evolution (starts from 0)
1661
+ ax = axes[0, 1]
1662
+ self.plot_cutout_centers(ax)
1663
+
1664
+ # Plot 3: Shift corrections scatter
1665
+ ax = axes[1, 0]
1666
+ max_value = np.max(np.abs(result.shift_corrections)) * 1.1
1667
+ colors = plt.cm.viridis(np.linspace(0, 1, n_iter))
1668
+ for i, corrections in enumerate(result.shift_corrections):
1669
+ ax.scatter(corrections[:, 1], corrections[:, 0], c=[colors[i]],
1670
+ alpha=0.5, label=f'Iter {i+1}', s=20)
1671
+ ax.axhline(0, color='k', linestyle='--', alpha=0.3)
1672
+ ax.axvline(0, color='k', linestyle='--', alpha=0.3)
1673
+ ax.set_xlabel('Correction X (pixels)')
1674
+ ax.set_ylabel('Correction Y (pixels)')
1675
+ ax.set_title('Shift Corrections')
1676
+ ax.legend(fontsize=8)
1677
+ ax.set_xlim(-max_value, max_value)
1678
+ ax.set_ylim(-max_value, max_value)
1679
+ ax.set_aspect('equal')
1680
+ ax.grid(True, alpha=0.3)
1681
+
1682
+ # Plot 4: Correction magnitude histogram
1683
+ ax = axes[1, 1]
1684
+ for i, corrections in enumerate(result.shift_corrections):
1685
+ magnitudes = np.sqrt(corrections[:, 0] ** 2 + corrections[:, 1] ** 2)
1686
+ ax.hist(magnitudes, bins=20, alpha=0.5, label=f'Iter {i+1}',
1687
+ edgecolor='black', linewidth=0.5)
1688
+ ax.set_xscale("log")
1689
+ ax.set_xlabel('Correction Magnitude (pixels)')
1690
+ ax.set_ylabel('Count')
1691
+ ax.set_title('Correction Distribution')
1692
+ ax.legend(fontsize=8)
1693
+ ax.grid(True, alpha=0.3)
1694
+
1695
+ plt.tight_layout()
1696
+ plt.show()
1697
+
1698
+ def plot_cutout_centers(self, ax,
1699
+ iteration: int = -1,
1700
+ show_arrows: bool = True) -> None:
1701
+ """Plot center positions of each cutout after shifts."""
1702
+ if self._last_refinement is None:
1703
+ print("No refinement history. Run refine_shifts() first.")
1704
+ return
1705
+
1706
+ result = self._last_refinement
1707
+
1708
+ if iteration == -1:
1709
+ iteration = result.n_iterations - 1
1710
+
1711
+ if iteration >= len(result.total_shifts):
1712
+ print(f"Invalid iteration {iteration}. Max is {len(result.total_shifts) - 1}")
1713
+ return
1714
+
1715
+ shifts = result.total_shifts[iteration]
1716
+
1717
+ ax.scatter(shifts[:, 1], shifts[:, 0], c='C0', s=30, alpha=0.6,
1718
+ label=f'Iteration {iteration + 1}')
1719
+
1720
+ if show_arrows:
1721
+ for i in range(len(shifts)):
1722
+ ax.annotate('', xy=(shifts[i, 1], shifts[i, 0]), xytext=(0, 0),
1723
+ arrowprops=dict(arrowstyle='->', color='C0', alpha=0.3, lw=0.5))
1724
+
1725
+ ax.scatter([0], [0], c='red', s=100, marker='+', linewidths=2,
1726
+ label='Image center', zorder=10)
1727
+
1728
+ circle = plt.Circle((0, 0), 0.5, fill=False, color='gray',
1729
+ linestyle='--', alpha=0)
1730
+ ax.add_patch(circle)
1731
+
1732
+ ax.set_xlabel('Shift X (pixels)')
1733
+ ax.set_ylabel('Shift Y (pixels)')
1734
+ ax.set_title(f'Cutout Centers - Iteration {iteration + 1}')
1735
+ ax.set_aspect('equal')
1736
+ ax.legend()
1737
+ ax.grid(True, alpha=0.3)
1738
+
1739
+ def plot_epsf_evolution(self,
1740
+ asinh_scale: float = 1e-4,
1741
+ figsize: Tuple[int, int] = None) -> None:
1742
+ """Plot ePSF at each iteration side by side."""
1743
+ if self._last_refinement is None:
1744
+ print("No refinement history. Run refine_shifts() first.")
1745
+ return
1746
+
1747
+ result = self._last_refinement
1748
+ n_epsf = len(result.epsf_history)
1749
+
1750
+ if figsize is None:
1751
+ figsize = (4 * n_epsf, 4)
1752
+
1753
+ fig, axes = plt.subplots(1, n_epsf, figsize=figsize)
1754
+ if n_epsf == 1:
1755
+ axes = [axes]
1756
+
1757
+ for i, (epsf, ax) in enumerate(zip(result.epsf_history, axes)):
1758
+ im = ax.imshow(epsf, origin='lower', cmap='magma',
1759
+ norm=AsinhNorm(asinh_scale))
1760
+ ax.set_title(f'Iter {i}\nFWHM={result.epsf_fwhm_per_iteration[i]:.2f}')
1761
+ ax.set_xlabel('X')
1762
+ if i == 0:
1763
+ ax.set_ylabel('Y')
1764
+
1765
+ plt.tight_layout()
1766
+ plt.show()
1767
+
1768
+ def plot_epsf(self,
1769
+ log_scale: bool = True,
1770
+ asinh_scale: float = 1e-4,
1771
+ vmin: Optional[float] = None,
1772
+ vmax: Optional[float] = None,
1773
+ figsize: Tuple[int, int] = (8, 7)) -> None:
1774
+ """Display the current ePSF."""
1775
+ if self.current_epsf is None:
1776
+ print("No ePSF available. Run stack() or refine_shifts() first.")
1777
+ return
1778
+
1779
+ fig, ax = plt.subplots(figsize=figsize)
1780
+
1781
+ if log_scale:
1782
+ norm = AsinhNorm(asinh_scale, vmin=vmin, vmax=vmax)
1783
+ else:
1784
+ norm = None
1785
+
1786
+ im = ax.imshow(self.current_epsf, origin='lower', cmap='magma',
1787
+ norm=norm, vmin=vmin, vmax=vmax)
1788
+ plt.colorbar(im, ax=ax, label='Normalized flux')
1789
+
1790
+ fwhm = self.compute_fwhm(self.current_epsf)
1791
+ ee = self.compute_encircled_energy(self.current_epsf)
1792
+
1793
+ ax.set_title(f'ePSF ({self.get_n_valid()} stars)\n'
1794
+ f'FWHM={fwhm:.2f} px, EE50={ee[0.5]:.2f} px')
1795
+ ax.set_xlabel('X (pixels)')
1796
+ ax.set_ylabel('Y (pixels)')
1797
+
1798
+ plt.tight_layout()
1799
+ plt.show()