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,1067 @@
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 photutils.centroids import centroid_2dg
6
+ from tqdm import tqdm
7
+ import matplotlib.pyplot as plt
8
+ from matplotlib.colors import AsinhNorm
9
+
10
+ from .core import StarCutouts, process_cutout, align_and_rotate_star, normalize_cutout
11
+
12
+
13
+ @dataclass
14
+ class RefinementResult:
15
+ """Results from iterative PSF refinement."""
16
+ n_iterations: int
17
+ shift_corrections: List[np.ndarray]
18
+ total_shifts: List[np.ndarray]
19
+ rms_correction_per_iteration: np.ndarray
20
+ epsf_fwhm_per_iteration: np.ndarray
21
+ epsf_history: List[np.ndarray]
22
+ final_epsf: np.ndarray
23
+ converged: bool
24
+ valid_indices: List[int]
25
+
26
+
27
+ class EPIBuilder:
28
+ """
29
+ Builds effective PSF (ePSF) through iterative shift refinement and stacking.
30
+
31
+ IMPORTANT: This class does NOT modify the original cutouts. All shifts and
32
+ elaborated cutouts are stored internally.
33
+ """
34
+
35
+ DEFAULT_MAX_SHIFT = 5.0 #px
36
+ DEFAULT_FIT_ORDER = 5
37
+ DEFAULT_SHIFT_ORDER = 3
38
+ DEFAULT_K_SIGMA = 3.0
39
+ DEFAULT_MAXITERS = 10
40
+ DEFAULT_CENTROID_RADIUS = 7 #px
41
+ DEFAULT_NORM_RADIUS = 1.0 #arcsec
42
+
43
+ def __init__(self, cutouts: StarCutouts, norm_radius: float = DEFAULT_NORM_RADIUS):
44
+ self.cutouts = cutouts
45
+ self.norm_radius = norm_radius # NUOVO
46
+ self.current_epsf: Optional[np.ndarray] = None
47
+ self._last_refinement: Optional[RefinementResult] = None
48
+
49
+ # Internal storage (does NOT modify original cutouts)
50
+ self._shifts: Dict[int, Tuple[float, float]] = {}
51
+ self._elaborated: Dict[int, np.ndarray] = {}
52
+ self._elaborated_wht: Dict[int, np.ndarray] = {}
53
+
54
+ # Initialize with original values
55
+ self._initialize_from_cutouts()
56
+
57
+ def _initialize_from_cutouts(self) -> None:
58
+ """Copy initial shifts and elaborated cutouts from original cutouts."""
59
+ self._shifts.clear()
60
+ self._elaborated.clear()
61
+ self._elaborated_wht.clear()
62
+
63
+ for i, star in enumerate(self.cutouts.stars):
64
+ if star is not None and star.is_valid == 1 and not star.mask:
65
+ # Copy shift
66
+ if star.shift is not None:
67
+ self._shifts[i] = star.shift
68
+
69
+ # Copy elaborated cutouts
70
+ if star.cutout_elaborated is not None:
71
+ self._elaborated[i] = star.cutout_elaborated.copy()
72
+ if star.cutout_wht_elaborated is not None:
73
+ self._elaborated_wht[i] = star.cutout_wht_elaborated.copy()
74
+
75
+ def reset(self) -> None:
76
+ """Reset internal storage to original cutout values."""
77
+ self._initialize_from_cutouts()
78
+ self.current_epsf = None
79
+ self._last_refinement = None
80
+
81
+ # =========================================================================
82
+ # VALID STAR UTILITIES
83
+ # =========================================================================
84
+
85
+ def get_valid_indices(self) -> List[int]:
86
+ """Get indices of valid stars for stacking."""
87
+ return [
88
+ i for i, star in enumerate(self.cutouts.stars)
89
+ if star is not None
90
+ and star.is_valid == 1
91
+ and not star.mask
92
+ and (i in self._elaborated or star.cutout_elaborated is not None)
93
+ ]
94
+
95
+ def get_n_valid(self) -> int:
96
+ """Return number of valid stars."""
97
+ return len(self.get_valid_indices())
98
+
99
+ def _get_shift(self, star_index: int) -> Tuple[float, float]:
100
+ """Get shift from internal storage or fall back to original."""
101
+ if star_index in self._shifts:
102
+ return self._shifts[star_index]
103
+ star = self.cutouts.stars[star_index]
104
+ if star is not None and star.shift is not None:
105
+ return star.shift
106
+ return (0.0, 0.0)
107
+
108
+ def _get_stacking_data(self) -> Tuple[np.ndarray, np.ndarray]:
109
+ """Collect cutouts and weights from valid stars (uses internal storage)."""
110
+ valid_indices = self.get_valid_indices()
111
+
112
+ cutouts_list = []
113
+ weights_list = []
114
+
115
+ for idx in valid_indices:
116
+ # Always prefer internal storage
117
+ if idx in self._elaborated:
118
+ cutouts_list.append(self._elaborated[idx])
119
+ if idx in self._elaborated_wht:
120
+ weights_list.append(self._elaborated_wht[idx])
121
+ else:
122
+ weights_list.append(np.ones_like(self._elaborated[idx]))
123
+ else:
124
+ # Fallback to original (should not happen after init)
125
+ star = self.cutouts.stars[idx]
126
+ cutouts_list.append(star.cutout_elaborated)
127
+ if star.cutout_wht_elaborated is not None:
128
+ weights_list.append(star.cutout_wht_elaborated)
129
+ else:
130
+ weights_list.append(np.ones_like(star.cutout_elaborated))
131
+
132
+ return np.array(cutouts_list), np.array(weights_list)
133
+
134
+ def _align_star_internal(self,
135
+ star_index: int,
136
+ shift: Tuple[float, float],
137
+ final_angle: float = 0.0,
138
+ fine_rotation: bool = False,
139
+ order: int = 3,
140
+ normalize: bool = True,
141
+ norm_radius: float = 1.0) -> None:
142
+
143
+ """Align star and store result internally (does NOT modify original)."""
144
+ star = self.cutouts.stars[star_index]
145
+
146
+ best_pa = star.best_pa if star.best_pa is not None else 0
147
+
148
+ reduced_image, reduced_wht = align_and_rotate_star(
149
+ cutout=star.cutout,
150
+ cutout_wht=star.cutout_wht,
151
+ cutout_mask=star.cutout_mask,
152
+ shift=shift,
153
+ best_pa=best_pa,
154
+ scale_factor=star.scale_factor,
155
+ upsample_factor=self.cutouts.upsample_factor,
156
+ final_size=self.cutouts.cutout_shape,
157
+ final_angle=final_angle,
158
+ rotation=star.rotation,
159
+ fine_rotation=fine_rotation,
160
+ order=order
161
+ )
162
+
163
+ # Normalize if requested
164
+ if normalize:
165
+ reduced_image, reduced_wht = normalize_cutout(
166
+ cutout=reduced_image,
167
+ cutout_wht=reduced_wht,
168
+ norm_radius=norm_radius,
169
+ final_resolution=self.cutouts.final_resolution
170
+ )
171
+
172
+ self._elaborated[star_index] = reduced_image
173
+ if reduced_wht is not None:
174
+ self._elaborated_wht[star_index] = reduced_wht
175
+
176
+ # =========================================================================
177
+ # ePSF METRICS
178
+ # =========================================================================
179
+
180
+ def compute_fwhm(self, epsf: np.ndarray, method: str = 'half_max',
181
+ n_radial_samples: int = 500, n_angular_samples: int = 360) -> float:
182
+ """
183
+ Compute FWHM of the ePSF at subpixel resolution.
184
+
185
+ Parameters
186
+ ----------
187
+ epsf : np.ndarray
188
+ 2D ePSF image.
189
+ method : str
190
+ Method to use: 'half_max' (interpolated) or 'gaussian' (fit).
191
+ n_radial_samples : int
192
+ Number of radial samples for interpolation. Default is 500.
193
+ n_angular_samples : int
194
+ Number of angular samples for azimuthal averaging. Default is 360.
195
+
196
+ Returns
197
+ -------
198
+ float
199
+ FWHM in pixels.
200
+ """
201
+ from scipy.ndimage import map_coordinates
202
+ from scipy.interpolate import UnivariateSpline
203
+ from scipy.optimize import brentq
204
+
205
+ center = (np.array(epsf.shape) - 1) / 2.0
206
+ r_max = min(center) * 0.95 # Stay slightly inside image
207
+
208
+ # Create fine radial grid
209
+ r_fine = np.linspace(0, r_max, n_radial_samples)
210
+ theta = np.linspace(0, 2 * np.pi, n_angular_samples, endpoint=False)
211
+
212
+ # Sample image at subpixel positions using bilinear interpolation
213
+ radial_profile = np.zeros(n_radial_samples)
214
+
215
+ for i, r in enumerate(r_fine):
216
+ if r == 0:
217
+ # At center, just take the center pixel value (interpolated)
218
+ radial_profile[i] = map_coordinates(epsf, [[center[0]], [center[1]]],
219
+ order=3, mode='constant')[0]
220
+ else:
221
+ # Sample at n_angular_samples points around the circle
222
+ y_coords = center[0] + r * np.sin(theta)
223
+ x_coords = center[1] + r * np.cos(theta)
224
+
225
+ # Interpolate values at these coordinates
226
+ values = map_coordinates(epsf, [y_coords, x_coords],
227
+ order=3, mode='constant')
228
+ radial_profile[i] = np.mean(values)
229
+
230
+ if method == 'half_max':
231
+ peak = np.max(radial_profile)
232
+ half_max = peak / 2
233
+
234
+ # Check if profile ever drops below half_max
235
+ if np.all(radial_profile > half_max):
236
+ return r_max * 2
237
+
238
+ # Create smooth spline interpolation
239
+ # Use smoothing to handle noise
240
+ spline = UnivariateSpline(r_fine, radial_profile, s=0, k=3)
241
+
242
+ # Find where profile crosses half_max
243
+ # First, find approximate location
244
+ above_half = radial_profile > half_max
245
+ if not np.any(~above_half):
246
+ return r_fine[-1] * 2
247
+
248
+ first_below_idx = np.argmax(~above_half)
249
+ if first_below_idx == 0:
250
+ return r_fine[0] * 2
251
+
252
+ # Bracket the root
253
+ r_low = r_fine[first_below_idx - 1]
254
+ r_high = r_fine[first_below_idx]
255
+
256
+ # Extend bracket slightly if needed
257
+ while spline(r_low) < half_max and first_below_idx > 1:
258
+ first_below_idx -= 1
259
+ r_low = r_fine[first_below_idx - 1]
260
+
261
+ while spline(r_high) > half_max and first_below_idx < len(r_fine) - 1:
262
+ first_below_idx += 1
263
+ r_high = r_fine[first_below_idx]
264
+
265
+ # Use Brent's method to find exact crossing point
266
+ try:
267
+ r_half = brentq(lambda r: spline(r) - half_max, r_low, r_high)
268
+ except ValueError:
269
+ # Fallback to linear interpolation if brentq fails
270
+ p1, p2 = radial_profile[first_below_idx - 1], radial_profile[first_below_idx]
271
+ r1, r2 = r_fine[first_below_idx - 1], r_fine[first_below_idx]
272
+ if p1 != p2:
273
+ r_half = r1 + (half_max - p1) * (r2 - r1) / (p2 - p1)
274
+ else:
275
+ r_half = (r1 + r2) / 2
276
+
277
+ return 2 * r_half
278
+
279
+ else: # gaussian fit
280
+ from scipy.optimize import curve_fit
281
+
282
+ def gaussian(r, amp, sigma, offset):
283
+ return amp * np.exp(-r**2 / (2 * sigma**2)) + offset
284
+
285
+ try:
286
+ p0 = [np.max(radial_profile) - np.min(radial_profile),
287
+ 2.0,
288
+ np.min(radial_profile)]
289
+ popt, _ = curve_fit(gaussian, r_fine, radial_profile, p0=p0, maxfev=2000)
290
+ sigma = abs(popt[1])
291
+ return 2.355 * sigma # FWHM = 2*sqrt(2*ln(2)) * sigma
292
+ except:
293
+ # Fallback to half_max method
294
+ return self.compute_fwhm(epsf, method='half_max')
295
+
296
+ def compute_encircled_energy(self,
297
+ epsf: np.ndarray,
298
+ fractions: List[float] = [0.5, 0.8, 0.9]) -> dict:
299
+ """Compute encircled energy radii."""
300
+ center = (np.array(epsf.shape) - 1) / 2.0
301
+ y, x = np.ogrid[:epsf.shape[0], :epsf.shape[1]]
302
+ r = np.sqrt((x - center[1])**2 + (y - center[0])**2)
303
+
304
+ r_flat = r.flatten()
305
+ epsf_flat = epsf.flatten()
306
+ sort_idx = np.argsort(r_flat)
307
+ r_sorted = r_flat[sort_idx]
308
+ epsf_sorted = epsf_flat[sort_idx]
309
+
310
+ cumsum = np.cumsum(epsf_sorted)
311
+ total = cumsum[-1]
312
+
313
+ results = {}
314
+ for frac in fractions:
315
+ target = frac * total
316
+ idx = np.searchsorted(cumsum, target)
317
+ results[frac] = r_sorted[min(idx, len(r_sorted)-1)]
318
+
319
+ return results
320
+
321
+ # =========================================================================
322
+ # SIGMA CLIPPING
323
+ # =========================================================================
324
+
325
+ def _mad_sigma_clip(self, data: np.ndarray, sigma: float,
326
+ maxiters: int, axis: int = 0) -> np.ndarray:
327
+ """MAD-based sigma clipping."""
328
+
329
+ mask = data==0
330
+
331
+ for _ in range(maxiters):
332
+ data_masked = np.ma.array(data,mask=mask)
333
+ reference = np.ma.median(data_masked, axis=axis, keepdims=True)
334
+ distance = np.abs(data - reference)
335
+
336
+ masked_distance = np.ma.array(distance, mask=mask)
337
+ mad = np.ma.median(masked_distance, axis=axis, keepdims=True).filled(1.0)
338
+
339
+ new_mask = distance > sigma * mad
340
+
341
+ if np.array_equal(new_mask, mask):
342
+ break
343
+ mask = new_mask
344
+
345
+ return mask
346
+
347
+ def _weighted_sigma_clip(self, data: np.ndarray, weights: np.ndarray,
348
+ sigma: float, maxiters: int,
349
+ use_median: bool = False, axis: int = 0) -> np.ndarray:
350
+ """Weighted sigma clipping."""
351
+ mask = np.zeros(data.shape, dtype=bool)
352
+
353
+ for _ in range(maxiters):
354
+ w = np.where(mask, 0.0, weights)
355
+ w_sum = np.sum(w, axis=axis, keepdims=True)
356
+ w_sum = np.where(w_sum == 0, 1.0, w_sum)
357
+
358
+ if use_median:
359
+ reference = np.median(data, axis=axis, keepdims=True)
360
+ else:
361
+ reference = np.sum(data * w, axis=axis, keepdims=True) / w_sum
362
+
363
+ masked_data = np.ma.array(data, mask=mask)
364
+ std = np.ma.std(masked_data, axis=axis, keepdims=True).filled(1.0)
365
+
366
+ new_mask = np.abs(data - reference) > sigma * std
367
+
368
+ if np.array_equal(new_mask, mask):
369
+ break
370
+ mask = new_mask
371
+
372
+ return mask
373
+
374
+ # =========================================================================
375
+ # STACKING
376
+ # =========================================================================
377
+
378
+ def stack(self,
379
+ rejection_mode: Literal['none', 'weighted', 'mad'] = 'mad',
380
+ k_sigma: float = DEFAULT_K_SIGMA,
381
+ maxiters: int = DEFAULT_MAXITERS,
382
+ verbose: bool = True) -> np.ndarray:
383
+ """Stack valid star cutouts with optional sigma rejection."""
384
+ n_valid = self.get_n_valid()
385
+
386
+ if n_valid == 0:
387
+ raise ValueError("No valid stars available for stacking")
388
+
389
+ data, weights = self._get_stacking_data()
390
+
391
+ if verbose:
392
+ print(f"Stacking {n_valid} stars | rejection='{rejection_mode}' | k_sigma={k_sigma}")
393
+
394
+ if rejection_mode == 'none':
395
+ mask = np.zeros(data.shape, dtype=bool)
396
+ elif rejection_mode == 'mad':
397
+ mask = self._mad_sigma_clip(data, k_sigma, maxiters)
398
+ elif rejection_mode == 'weighted':
399
+ use_median = n_valid < 10
400
+ mask = self._weighted_sigma_clip(data, weights, k_sigma, maxiters, use_median)
401
+ else:
402
+ raise ValueError(f"Unknown rejection_mode: '{rejection_mode}'")
403
+
404
+ weights_masked = weights.copy()
405
+ weights_masked[mask] = 0.0
406
+
407
+ if verbose:
408
+ rejected = np.sum(mask)
409
+ total = np.prod(data.shape)
410
+ print(f" Rejected: {rejected}/{total} pixels ({100*rejected/total:.2f}%)")
411
+
412
+ numerator = np.sum(data * weights_masked, axis=0)
413
+ denominator = np.sum(weights_masked, axis=0)
414
+ denominator[denominator == 0] = 1.0
415
+
416
+ self.current_epsf = numerator / denominator
417
+
418
+ return self.current_epsf
419
+
420
+ # =========================================================================
421
+ # SHIFT FITTING
422
+ # =========================================================================
423
+
424
+ def _fit_shift_to_original(self,
425
+ star_index: int,
426
+ epsf: np.ndarray,
427
+ centroid_radius: int = None,
428
+ max_shift: float = DEFAULT_MAX_SHIFT,
429
+ fit_order: int = DEFAULT_FIT_ORDER) -> Tuple[float, float]:
430
+ """Fit TOTAL shift needed to align original cutout to ePSF."""
431
+ star = self.cutouts.stars[star_index]
432
+
433
+ if star is None or star.cutout is None:
434
+ return 0.0, 0.0
435
+
436
+ scale_factor = star.scale_factor
437
+
438
+ if centroid_radius is None:
439
+ centroid_radius = int(self.DEFAULT_CENTROID_RADIUS * scale_factor)
440
+
441
+ output_shape = star.cutout.shape
442
+
443
+ rot_angle = star.best_pa if star.best_pa is not None else 0
444
+ if star.rotation is not None:
445
+ rot_angle -= star.rotation
446
+
447
+ probe_psf = process_cutout(
448
+ data=epsf,
449
+ shift=(0, 0),
450
+ angle=rot_angle,
451
+ scale_factor=scale_factor,
452
+ output_shape=output_shape,
453
+ order=fit_order
454
+ )
455
+
456
+ center = (np.array(star.cutout.shape) - 1) / 2.0
457
+ c_int = center.astype(int)
458
+
459
+ slice_fit = (
460
+ slice(c_int[0] - centroid_radius, c_int[0] + centroid_radius + 1),
461
+ slice(c_int[1] - centroid_radius, c_int[1] + centroid_radius + 1)
462
+ )
463
+
464
+ data = star.cutout[slice_fit]
465
+ psf_crop = probe_psf[slice_fit]
466
+
467
+ mask_data = star.cutout_mask[slice_fit]
468
+
469
+ if star.cutout_wht is not None:
470
+ wht = star.cutout_wht[slice_fit].copy()
471
+ wht[~np.isfinite(wht)] = 0.0
472
+ wht[wht < 0] = 0.0
473
+ else:
474
+ wht = np.ones_like(data)
475
+
476
+ wht[mask_data] = 0
477
+
478
+ wht_sum = np.sum(wht)
479
+ wht_norm = wht / wht_sum if wht_sum > 0 else np.ones_like(wht) / wht.size
480
+
481
+ def residual(params):
482
+ shift_x, shift_y, amplitude, offset = params
483
+ shifted_psf = process_cutout(
484
+ data=psf_crop,
485
+ shift=(shift_y, shift_x),
486
+ angle=0.0,
487
+ scale_factor=1,
488
+ output_shape=psf_crop.shape,
489
+ order=fit_order
490
+ )
491
+ model = amplitude * shifted_psf + offset
492
+ return np.sum(wht_norm * (data - model)**2)
493
+
494
+ p0 = [0.0, 0.0, np.max(data) / (np.max(psf_crop) + 1e-10), np.median(data)]
495
+ bounds = [(-max_shift, max_shift), (-max_shift, max_shift), (0, None), (None, None)]
496
+
497
+ result = minimize(residual, p0, method='Powell', bounds=bounds)
498
+
499
+ if result.success:
500
+ shift_x, shift_y = result.x[0], result.x[1]
501
+ else:
502
+
503
+ if star.cutout_wht is not None:
504
+ with np.errstate(divide='ignore', invalid='ignore'):
505
+ error = np.sqrt(1.0 / (wht + 1e-50))
506
+ error[~np.isfinite(error)] = np.nanmax(error[np.isfinite(error)])
507
+ else:
508
+ error = None
509
+
510
+ cx, cy = centroid_2dg(data, error=error, mask=mask_data)
511
+ shift_x = cx - centroid_radius
512
+ shift_y = cy - centroid_radius
513
+
514
+ return -shift_y, -shift_x
515
+
516
+ # =========================================================================
517
+ # ITERATIVE REFINEMENT
518
+ # =========================================================================
519
+ def _recenter_epsf(self, epsf: np.ndarray) -> Tuple[np.ndarray, Tuple[float, float]]:
520
+ """
521
+ Recenter ePSF to geometric center using centroid.
522
+
523
+ Returns
524
+ -------
525
+ recentered_epsf : np.ndarray
526
+ ePSF shifted to center.
527
+ centroid_offset : Tuple[float, float]
528
+ (offset_y, offset_x) that was applied.
529
+ """
530
+
531
+ center = (np.array(epsf.shape) - 1) / 2.0
532
+
533
+ # Find centroid using center of mass or 2D Gaussian
534
+ # Use weighted centroid for robustness
535
+ y, x = np.ogrid[:epsf.shape[0], :epsf.shape[1]]
536
+
537
+ # Mask to use only central region for centroid
538
+ r = np.sqrt((x - center[1])**2 + (y - center[0])**2)
539
+ mask = r < min(center) * 0.5 # Use central 50%
540
+
541
+ epsf_masked = np.where(mask, epsf, 0)
542
+ total = np.sum(epsf_masked)
543
+
544
+ if total > 0:
545
+ centroid_y = np.sum(y * epsf_masked) / total
546
+ centroid_x = np.sum(x * epsf_masked) / total
547
+ else:
548
+ centroid_y, centroid_x = center
549
+
550
+ # Offset from geometric center
551
+ offset_y = centroid_y - center[0]
552
+ offset_x = centroid_x - center[1]
553
+
554
+ # Shift ePSF to center it
555
+ recentered = process_cutout(
556
+ data=epsf,
557
+ shift=(-offset_y, -offset_x), # Shift in opposite direction
558
+ angle=0.0,
559
+ scale_factor=1,
560
+ output_shape=epsf.shape,
561
+ order=3
562
+ )
563
+
564
+ return recentered, (offset_y, offset_x)
565
+
566
+ def refine_shifts(self,
567
+ n_iterations: int = 3,
568
+ rejection_mode: Literal['none', 'weighted', 'mad'] = 'mad',
569
+ k_sigma: float = DEFAULT_K_SIGMA,
570
+ maxiters: int = DEFAULT_MAXITERS,
571
+ max_shift: float = DEFAULT_MAX_SHIFT,
572
+ fit_order: int = DEFAULT_FIT_ORDER,
573
+ shift_order: int = DEFAULT_SHIFT_ORDER,
574
+ convergence_threshold: float = 0.01,
575
+ recenter_epsf: bool = True,
576
+ normalize: bool = True,
577
+ verbose: bool = True) -> RefinementResult:
578
+ """
579
+ Iteratively refine star shifts by fitting original cutouts to stacked ePSF.
580
+
581
+ This does NOT modify the original cutouts. All changes are
582
+ stored internally in self._shifts and self._elaborated.
583
+ """
584
+ # Reset internal storage to original values at the start
585
+ self._initialize_from_cutouts()
586
+
587
+ valid_indices = self.get_valid_indices()
588
+ n_valid = len(valid_indices)
589
+
590
+ if n_valid == 0:
591
+ raise ValueError("No valid stars for refinement")
592
+
593
+ if verbose:
594
+ print(f"{'='*60}")
595
+ print(f"Starting iterative shift refinement")
596
+ print(f" Valid stars: {n_valid}")
597
+ print(f" Max iterations: {n_iterations}")
598
+ print(f" Rejection: {rejection_mode}, k_sigma={k_sigma}")
599
+ print(f" Recenter ePSF: {recenter_epsf}")
600
+ print(f" Convergence threshold: {convergence_threshold} px")
601
+ print(f"{'='*60}")
602
+
603
+ # Compute initial ePSF
604
+ epsf_initial = self.stack(rejection_mode=rejection_mode, k_sigma=k_sigma,
605
+ maxiters=maxiters, verbose=verbose)
606
+
607
+ # RICENTRALIZZA L'ePSF INIZIALE
608
+ if recenter_epsf:
609
+ epsf_initial, initial_offset = self._recenter_epsf(epsf_initial)
610
+ self.current_epsf = epsf_initial
611
+ if verbose:
612
+ print(f" Initial ePSF recentered by: ({initial_offset[0]:.4f}, {initial_offset[1]:.4f}) px")
613
+
614
+ fwhm_initial = self.compute_fwhm(epsf_initial)
615
+
616
+ if verbose:
617
+ print(f" Initial FWHM: {fwhm_initial:.3f} px")
618
+
619
+ shift_corrections = []
620
+ total_shifts = []
621
+ rms_history = []
622
+ fwhm_history = [fwhm_initial]
623
+ epsf_history = [epsf_initial.copy()]
624
+ epsf_offsets = [] # Track offsets for debugging
625
+ converged = False
626
+
627
+ for iteration in range(n_iterations):
628
+ if verbose:
629
+ print(f"\n--- Iteration {iteration + 1}/{n_iterations} ---")
630
+
631
+ epsf = self.current_epsf
632
+
633
+ # Fit shifts
634
+ corrections = np.zeros((n_valid, 2))
635
+ new_shifts = np.zeros((n_valid, 2))
636
+
637
+ iterator = tqdm(enumerate(valid_indices), total=n_valid,
638
+ desc="Fitting shifts", disable=not verbose)
639
+
640
+ for i, star_idx in iterator:
641
+ old_shift = np.array(self._get_shift(star_idx))
642
+
643
+ fitted_y, fitted_x = self._fit_shift_to_original(
644
+ star_idx, epsf,
645
+ max_shift=max_shift,
646
+ fit_order=fit_order
647
+ )
648
+ new_shift = np.array([fitted_y, fitted_x])
649
+
650
+ correction = new_shift - old_shift
651
+ corrections[i] = correction
652
+ new_shifts[i] = new_shift
653
+
654
+ self._shifts[star_idx] = (fitted_y, fitted_x)
655
+
656
+ shift_corrections.append(corrections.copy())
657
+ total_shifts.append(new_shifts.copy())
658
+
659
+ # Update elaborated cutouts
660
+ if verbose:
661
+ print("Updating elaborated cutouts...")
662
+ for star_idx in valid_indices:
663
+ self._align_star_internal(
664
+ star_idx,
665
+ self._shifts[star_idx],
666
+ final_angle=0.0,
667
+ fine_rotation=False,
668
+ normalize=normalize,
669
+ order=shift_order,
670
+ norm_radius=self.norm_radius
671
+ )
672
+
673
+ # Stack
674
+ epsf = self.stack(
675
+ rejection_mode=rejection_mode,
676
+ k_sigma=k_sigma,
677
+ maxiters=maxiters,
678
+ verbose=verbose
679
+ )
680
+
681
+ # center ePSF
682
+ if recenter_epsf:
683
+ epsf, offset = self._recenter_epsf(epsf)
684
+ self.current_epsf = epsf
685
+ epsf_offsets.append(offset)
686
+ if verbose:
687
+ print(f" ePSF recentered by: ({offset[0]:.4f}, {offset[1]:.4f}) px")
688
+
689
+ epsf_history.append(epsf.copy())
690
+
691
+ fwhm = self.compute_fwhm(epsf)
692
+ fwhm_history.append(fwhm)
693
+ if verbose:
694
+ print(f" ePSF FWHM: {fwhm:.3f} px")
695
+
696
+ # Check convergence
697
+ rms_correction = np.sqrt(np.mean(corrections**2))
698
+ rms_history.append(rms_correction)
699
+
700
+ if verbose:
701
+ print(f" RMS correction: {rms_correction:.4f} px")
702
+ print(f" Max correction: {np.max(np.abs(corrections)):.4f} px")
703
+ # Show mean shift to detect drift
704
+ mean_shift = np.mean(new_shifts, axis=0)
705
+ print(f" Mean shift: ({mean_shift[0]:.4f}, {mean_shift[1]:.4f}) px")
706
+
707
+ if rms_correction < convergence_threshold:
708
+ if verbose:
709
+ print(f"\n✓ Converged after {iteration + 1} iterations")
710
+ converged = True
711
+ break
712
+
713
+ result = RefinementResult(
714
+ n_iterations=len(shift_corrections),
715
+ shift_corrections=shift_corrections,
716
+ total_shifts=total_shifts,
717
+ rms_correction_per_iteration=np.array(rms_history),
718
+ epsf_fwhm_per_iteration=np.array(fwhm_history),
719
+ epsf_history=epsf_history,
720
+ final_epsf=self.current_epsf,
721
+ converged=converged,
722
+ valid_indices=valid_indices
723
+ )
724
+
725
+ self._last_refinement = result
726
+
727
+ if verbose:
728
+ print(f"\n{'='*60}")
729
+ print(f"Refinement complete: {result.n_iterations} iterations")
730
+ print(f"Converged: {result.converged}")
731
+ final_mean = np.mean(total_shifts[-1], axis=0)
732
+ print(f"{'='*60}")
733
+
734
+ return result
735
+
736
+ # =========================================================================
737
+ # MULTI-ANGLE ePSF
738
+ # =========================================================================
739
+
740
+ def build_multi_angle_epsf(self,
741
+ angles: Optional[Dict[str, float] | List[float]] = None,
742
+ output_shape: Optional[Tuple[int, int] | np.ndarray] = None,
743
+ rejection_mode: Literal['none', 'weighted', 'mad'] = 'mad',
744
+ k_sigma: float = DEFAULT_K_SIGMA,
745
+ maxiters: int = DEFAULT_MAXITERS,
746
+ shift_order: int = DEFAULT_SHIFT_ORDER,
747
+ fine_rotation: bool = False,
748
+ normalize: bool = True,
749
+ verbose: bool = True) -> Dict[str, np.ndarray]:
750
+ """Build ePSF at multiple target angles.
751
+
752
+ Parameters
753
+ ----------
754
+ angles : Dict[str, float] or List[float] or None
755
+ Target angles.
756
+ - If dict: keys are names (e.g., field names), values are angles in degrees
757
+ - If list: creates names as "angle_{a}" for each angle
758
+ - If None: defaults to [0, 45, 90, 135]
759
+ output_shape : Tuple[int, int] or np.ndarray or None
760
+ If specified, crop the final ePSF to this shape (centered).
761
+ If None, keep the original shape.
762
+ rejection_mode : {'none', 'weighted', 'mad'}
763
+ Rejection method for stacking. Default is 'mad'.
764
+ k_sigma : float
765
+ Sigma threshold for rejection. Default is 3.0.
766
+ maxiters : int
767
+ Maximum iterations for sigma clipping. Default is 10.
768
+ fine_rotation : bool
769
+ If True, apply fine rotation correction. Default is False.
770
+ normalize : bool
771
+ If True, normalize each cutout by aperture flux. Default is True.
772
+ verbose : bool
773
+ Print progress. Default is True.
774
+
775
+ Returns
776
+ -------
777
+ Dict[str, np.ndarray]
778
+ Dictionary mapping angle names to ePSF arrays.
779
+
780
+ Raises
781
+ ------
782
+ ValueError
783
+ If no valid stars are available or output_shape is larger than original.
784
+
785
+ Examples
786
+ --------
787
+ >>> # Build for specific fields with their position angles
788
+ >>> psfs = builder.build_multi_angle_epsf(
789
+ ... angles={'A2744': 45.2, 'MACS0416': 120.5, 'generic': 0.0},
790
+ ... output_shape=(101, 101)
791
+ ... )
792
+ >>>
793
+ >>> # Build for regular angles
794
+ >>> psfs = builder.build_multi_angle_epsf(angles=[0, 30, 60, 90, 120, 150])
795
+ >>>
796
+ >>> # Save to FITS
797
+ >>> for name, psf in psfs.items():
798
+ ... fits.PrimaryHDU(data=psf).writeto(f'{name}.fits', overwrite=True)
799
+ """
800
+
801
+ if angles is None:
802
+ angles = [0]
803
+
804
+ # Convert list to dict
805
+ if isinstance(angles, list):
806
+ angles_dict = {f"angle_{int(a)}": float(a) for a in angles}
807
+ else:
808
+ angles_dict = angles
809
+
810
+ valid_indices = self.get_valid_indices()
811
+
812
+ if len(valid_indices) == 0:
813
+ raise ValueError("No valid stars for ePSF building")
814
+
815
+ # Compute slice for cropping (if output_shape specified)
816
+ crop_slice = None
817
+ if output_shape is not None:
818
+ output_shape = np.asarray(output_shape)
819
+ original_shape = np.asarray(self.cutouts.cutout_shape)
820
+
821
+ if np.any(output_shape > original_shape):
822
+ raise ValueError(
823
+ f"output_shape {tuple(output_shape)} cannot be larger than "
824
+ f"original shape {tuple(original_shape)}"
825
+ )
826
+
827
+ # Compute centered slice
828
+ start = (original_shape - output_shape) // 2
829
+ end = start + output_shape
830
+ crop_slice = (slice(start[0], end[0]), slice(start[1], end[1]))
831
+
832
+ if verbose:
833
+ print(f"{'='*60}")
834
+ print(f"Building multi-angle ePSF")
835
+ print(f" Angles: {list(angles_dict.keys())}")
836
+ print(f" Valid stars: {len(valid_indices)}")
837
+ if output_shape is not None:
838
+ print(f" Output shape: {tuple(output_shape)}")
839
+ print(f"{'='*60}")
840
+
841
+ results = {}
842
+
843
+ for name, target_angle in angles_dict.items():
844
+ if verbose:
845
+ print(f"\n--- {name} (PA = {target_angle}°) ---")
846
+
847
+ # Align all stars to target angle
848
+ for star_idx in valid_indices:
849
+ shift = self._get_shift(star_idx)
850
+ self._align_star_internal(
851
+ star_idx,
852
+ shift,
853
+ final_angle=target_angle,
854
+ fine_rotation=fine_rotation,
855
+ normalize=normalize,
856
+ order = shift_order,
857
+ norm_radius=self.norm_radius
858
+ )
859
+
860
+ # Stack
861
+ epsf = self.stack(
862
+ rejection_mode=rejection_mode,
863
+ k_sigma=k_sigma,
864
+ maxiters=maxiters,
865
+ verbose=verbose
866
+ )
867
+
868
+ # Crop if requested
869
+ if crop_slice is not None:
870
+ epsf = epsf[crop_slice]
871
+
872
+ # Normalize the total flux to 1
873
+ epsf = epsf/ np.sum(epsf)
874
+
875
+ results[name] = epsf.copy()
876
+
877
+ if verbose:
878
+ fwhm = self.compute_fwhm(epsf)
879
+ print(f" FWHM: {fwhm:.3f} px")
880
+ print(f" Shape: {epsf.shape}")
881
+
882
+ # Store last one as current
883
+ if results:
884
+ self.current_epsf = list(results.values())[-1]
885
+
886
+ if verbose:
887
+ print(f"\n{'='*60}")
888
+ print(f"Generated {len(results)} ePSFs")
889
+ print(f"{'='*60}")
890
+
891
+ return results
892
+
893
+ # =========================================================================
894
+ # PLOTTING
895
+ # =========================================================================
896
+
897
+ def plot_convergence_results(self, figsize: Tuple[int, int] = (12,8)) -> None:
898
+ """Plot convergence diagnostics."""
899
+ if self._last_refinement is None:
900
+ print("No refinement history. Run refine_shifts() first.")
901
+ return
902
+
903
+ result = self._last_refinement
904
+ n_iter = result.n_iterations
905
+
906
+ fig, axes = plt.subplots(2, 2, figsize=figsize)
907
+
908
+ # Plot 1: RMS correction
909
+ ax = axes[0, 0]
910
+ ax.plot(range(1, n_iter + 1), result.rms_correction_per_iteration, 'o-',
911
+ lw=2, markersize=8, color='C0')
912
+ ax.set_xlabel('Iteration')
913
+ ax.set_ylabel('RMS Shift Correction (pixels)')
914
+ ax.set_title('Corrections convergence')
915
+ ax.grid(True, alpha=0.3)
916
+ ax.set_xticks(range(1, n_iter + 1))
917
+ ax.set_yscale('log')
918
+
919
+ # Plot 2: FWHM evolution (starts from 0)
920
+ ax = axes[0, 1]
921
+ self.plot_cutout_centers(ax)
922
+
923
+ # Plot 3: Shift corrections scatter
924
+ ax = axes[1, 0]
925
+ max_value = np.max(np.abs(result.shift_corrections))*1.1
926
+ colors = plt.cm.viridis(np.linspace(0, 1, n_iter))
927
+ for i, corrections in enumerate(result.shift_corrections):
928
+ ax.scatter(corrections[:, 1], corrections[:, 0], c=[colors[i]],
929
+ alpha=0.5, label=f'Iter {i+1}', s=20)
930
+ ax.axhline(0, color='k', linestyle='--', alpha=0.3)
931
+ ax.axvline(0, color='k', linestyle='--', alpha=0.3)
932
+ ax.set_xlabel('Correction X (pixels)')
933
+ ax.set_ylabel('Correction Y (pixels)')
934
+ ax.set_title('Shift Corrections')
935
+ ax.legend(fontsize=8)
936
+ ax.set_xlim(-max_value,max_value)
937
+ ax.set_ylim(-max_value,max_value)
938
+ ax.set_aspect('equal')
939
+ ax.grid(True, alpha=0.3)
940
+
941
+ # Plot 4: Correction magnitude histogram
942
+ ax = axes[1, 1]
943
+ for i, corrections in enumerate(result.shift_corrections):
944
+ magnitudes = np.sqrt(corrections[:, 0]**2 + corrections[:, 1]**2)
945
+ ax.hist(magnitudes, bins=20, alpha=0.5, label=f'Iter {i+1}',
946
+ edgecolor='black', linewidth=0.5)
947
+ ax.set_xscale("log")
948
+ ax.set_xlabel('Correction Magnitude (pixels)')
949
+ ax.set_ylabel('Count')
950
+ ax.set_title('Correction Distribution')
951
+ ax.legend(fontsize=8)
952
+ ax.grid(True, alpha=0.3)
953
+
954
+ plt.tight_layout()
955
+ plt.show()
956
+
957
+ def plot_cutout_centers(self, ax,
958
+ iteration: int = -1,
959
+ show_arrows: bool = True) -> None:
960
+ """Plot center positions of each cutout after shifts."""
961
+ if self._last_refinement is None:
962
+ print("No refinement history. Run refine_shifts() first.")
963
+ return
964
+
965
+ result = self._last_refinement
966
+
967
+ if iteration == -1:
968
+ iteration = result.n_iterations - 1
969
+
970
+ if iteration >= len(result.total_shifts):
971
+ print(f"Invalid iteration {iteration}. Max is {len(result.total_shifts) - 1}")
972
+ return
973
+
974
+ shifts = result.total_shifts[iteration]
975
+
976
+ ax.scatter(shifts[:, 1], shifts[:, 0], c='C0', s=30, alpha=0.6,
977
+ label=f'Iteration {iteration + 1}')
978
+
979
+ if show_arrows:
980
+ for i in range(len(shifts)):
981
+ ax.annotate('', xy=(shifts[i, 1], shifts[i, 0]), xytext=(0, 0),
982
+ arrowprops=dict(arrowstyle='->', color='C0', alpha=0.3, lw=0.5))
983
+
984
+ ax.scatter([0], [0], c='red', s=100, marker='+', linewidths=2,
985
+ label='Image center', zorder=10)
986
+
987
+ circle = plt.Circle((0, 0), 0.5, fill=False, color='gray',
988
+ linestyle='--', alpha=0)
989
+ ax.add_patch(circle)
990
+
991
+ ax.set_xlabel('Shift X (pixels)')
992
+ ax.set_ylabel('Shift Y (pixels)')
993
+ ax.set_title(f'Cutout Centers - Iteration {iteration + 1}')
994
+ ax.set_aspect('equal')
995
+ ax.legend()
996
+ ax.grid(True, alpha=0.3)
997
+
998
+ """mean_x, mean_y = np.mean(shifts, axis=0)
999
+ std_x, std_y = np.std(shifts, axis=0)
1000
+ ax.text(0.02, 0.98,
1001
+ f'Mean: ({mean_y:.3f}, {mean_x:.3f})\n'
1002
+ f'Std: ({std_y:.3f}, {std_x:.3f})',
1003
+ transform=ax.transAxes, va='top', fontsize=9,
1004
+ bbox=dict(boxstyle='round', facecolor='white', alpha=0.8))"""
1005
+
1006
+
1007
+ def plot_epsf_evolution(self,
1008
+ asinh_scale: float = 1e-4,
1009
+ figsize: Tuple[int, int] = None) -> None:
1010
+ """Plot ePSF at each iteration side by side."""
1011
+ if self._last_refinement is None:
1012
+ print("No refinement history. Run refine_shifts() first.")
1013
+ return
1014
+
1015
+ result = self._last_refinement
1016
+ n_epsf = len(result.epsf_history)
1017
+
1018
+ if figsize is None:
1019
+ figsize = (4 * n_epsf, 4)
1020
+
1021
+ fig, axes = plt.subplots(1, n_epsf, figsize=figsize)
1022
+ if n_epsf == 1:
1023
+ axes = [axes]
1024
+
1025
+ for i, (epsf, ax) in enumerate(zip(result.epsf_history, axes)):
1026
+ im = ax.imshow(epsf, origin='lower', cmap='magma',
1027
+ norm=AsinhNorm(asinh_scale))
1028
+ ax.set_title(f'Iter {i}\nFWHM={result.epsf_fwhm_per_iteration[i]:.2f}')
1029
+ ax.set_xlabel('X')
1030
+ if i == 0:
1031
+ ax.set_ylabel('Y')
1032
+
1033
+ plt.tight_layout()
1034
+ plt.show()
1035
+
1036
+ def plot_epsf(self,
1037
+ log_scale: bool = True,
1038
+ asinh_scale: float = 1e-4,
1039
+ vmin: Optional[float] = None,
1040
+ vmax: Optional[float] = None,
1041
+ figsize: Tuple[int, int] = (8, 7)) -> None:
1042
+ """Display the current ePSF."""
1043
+ if self.current_epsf is None:
1044
+ print("No ePSF available. Run stack() or refine_shifts() first.")
1045
+ return
1046
+
1047
+ fig, ax = plt.subplots(figsize=figsize)
1048
+
1049
+ if log_scale:
1050
+ norm = AsinhNorm(asinh_scale, vmin=vmin, vmax=vmax)
1051
+ else:
1052
+ norm = None
1053
+
1054
+ im = ax.imshow(self.current_epsf, origin='lower', cmap='magma',
1055
+ norm=norm, vmin=vmin, vmax=vmax)
1056
+ plt.colorbar(im, ax=ax, label='Normalized flux')
1057
+
1058
+ fwhm = self.compute_fwhm(self.current_epsf)
1059
+ ee = self.compute_encircled_energy(self.current_epsf)
1060
+
1061
+ ax.set_title(f'ePSF ({self.get_n_valid()} stars)\n'
1062
+ f'FWHM={fwhm:.2f} px, EE50={ee[0.5]:.2f} px')
1063
+ ax.set_xlabel('X (pixels)')
1064
+ ax.set_ylabel('Y (pixels)')
1065
+
1066
+ plt.tight_layout()
1067
+ plt.show()