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/io.py ADDED
@@ -0,0 +1,438 @@
1
+ from typing import Optional, List, Dict, Tuple, Iterator
2
+
3
+ from astropy.io import fits
4
+ from astropy.wcs import WCS
5
+ import os
6
+
7
+ from .common import ZeropointCalculator
8
+
9
+
10
+ class Image:
11
+ """
12
+ Handles loading and management of FITS image files.
13
+
14
+ This class loads a science image and optionally an associated variance/weight map,
15
+ extracting relevant metadata such as WCS information, magnitude zeropoint, and pixel scale.
16
+
17
+ Parameters
18
+ ----------
19
+ image_path : str
20
+ Path to the science FITS image.
21
+ variance_path : str, optional
22
+ Path to the variance/weight FITS image. Default is None.
23
+ variance_type : str, optional
24
+ Type of variance map: "var" (variance), "rms" (root mean square),
25
+ or "weight" (inverse variance). Default is "var".
26
+ image_ext : int or str, optional
27
+ FITS extension for the science image. If None, uses the primary HDU.
28
+ variance_ext : int or str, optional
29
+ FITS extension for the variance image. If None, uses the primary HDU.
30
+ bunit : str or unit, optional
31
+ If string header keyword to read, if astropy unit: brightness unit override (e.g., "MJy/sr"). If None, read from header.
32
+ pixel_scale : float, optional
33
+ Pixel scale override in arcseconds/pixel. If None, computed from WCS.
34
+ wavelength : float, optional
35
+ Wavelength override in microns for zeropoint calculation.
36
+ best_PA : float, optional
37
+ Best position angle in degrees for this image. Default is None.
38
+ tolerance_pixel_scale : float, optional
39
+ Tolerance for rounding pixel scale to avoid floating point issues.
40
+ Default is 1.e-5.
41
+
42
+ Attributes
43
+ ----------
44
+ image_path : str
45
+ Path to the science image.
46
+ variance_path : str or None
47
+ Path to the variance image.
48
+ variance_type : str
49
+ Type of variance map.
50
+ image_data : np.ndarray
51
+ Science image data array.
52
+ image_header : astropy.io.fits.Header
53
+ Science image FITS header.
54
+ var_data : np.ndarray or None
55
+ Variance image data array (if provided).
56
+ var_header : astropy.io.fits.Header or None
57
+ Variance image FITS header (if provided).
58
+ wcs : astropy.wcs.WCS
59
+ World Coordinate System object.
60
+ has_variance : bool
61
+ Whether a variance map is available.
62
+ mag_zeropoint : float
63
+ AB magnitude zeropoint.
64
+ pixel_scale : float
65
+ Pixel scale in arcseconds/pixel.
66
+ best_PA : float or None
67
+ Best position angle in degrees.
68
+
69
+ Raises
70
+ ------
71
+ ValueError
72
+ If variance_type is not one of "var", "rms", or "weight".
73
+
74
+ Examples
75
+ --------
76
+ >>> img = Image(
77
+ ... image_path="science.fits",
78
+ ... variance_path="variance.fits",
79
+ ... variance_type="var"
80
+ ... )
81
+ >>> print(f"Pixel scale: {img.pixel_scale} arcsec/px")
82
+ >>> print(f"Zeropoint: {img.mag_zeropoint} mag")
83
+ """
84
+
85
+ ALLOWED_VARIANCE_TYPES = ["var", "rms", "weight"]
86
+
87
+ def __init__(self,
88
+ image_path: str,
89
+ variance_path: Optional[str] = None,
90
+ variance_type: str = "var",
91
+ image_ext: Optional[int | str] = None,
92
+ variance_ext: Optional[int | str] = None,
93
+ bunit: Optional[str] = None,
94
+ pixel_scale: Optional[float] = None,
95
+ wavelength: Optional[float] = None,
96
+ best_PA: Optional[float] = None,
97
+ tolerance_pixel_scale: float = 1.e-5):
98
+
99
+ # Validate variance type
100
+ if variance_type not in self.ALLOWED_VARIANCE_TYPES:
101
+ raise ValueError(
102
+ f"Invalid variance_type: '{variance_type}'. "
103
+ f"Allowed values are: {self.ALLOWED_VARIANCE_TYPES}"
104
+ )
105
+
106
+ # Store paths and configuration
107
+ self.image_path = image_path
108
+ self.variance_path = variance_path
109
+ self.variance_type = variance_type
110
+ self.best_PA = best_PA
111
+
112
+ # Load FITS data
113
+ self._load_image(image_ext, variance_ext)
114
+
115
+ # Calculate zeropoint and pixel scale
116
+ zp_calculator = ZeropointCalculator(
117
+ self.image_header,
118
+ bunit=bunit,
119
+ pixel_scale=pixel_scale,
120
+ wavelength=wavelength
121
+ )
122
+
123
+ self.mag_zeropoint = zp_calculator.zeropoint
124
+
125
+ # Round pixel scale to avoid floating point precision issues
126
+ unit = 1.
127
+ raw_pixel_scale = zp_calculator.pixel_scale
128
+ if hasattr(raw_pixel_scale, 'unit'):
129
+ unit = raw_pixel_scale.unit
130
+ raw_pixel_scale = raw_pixel_scale.value
131
+ self.pixel_scale = round(raw_pixel_scale / tolerance_pixel_scale) * tolerance_pixel_scale * unit
132
+
133
+ def _load_image(self,
134
+ image_ext: Optional[int | str],
135
+ variance_ext: Optional[int | str]) -> None:
136
+ """
137
+ Load science and variance FITS images.
138
+
139
+ Parameters
140
+ ----------
141
+ image_ext : int, str, or None
142
+ FITS extension for science image.
143
+ variance_ext : int, str, or None
144
+ FITS extension for variance image.
145
+ """
146
+ # Load science image
147
+ if image_ext is None:
148
+ self.image_data, self.image_header = fits.getdata(
149
+ self.image_path,
150
+ header=True
151
+ )
152
+ else:
153
+ self.image_data, self.image_header = fits.getdata(
154
+ self.image_path,
155
+ image_ext,
156
+ header=True
157
+ )
158
+
159
+ # Extract WCS from header
160
+ self.wcs = WCS(self.image_header)
161
+
162
+ # Load variance image if provided
163
+ if self.variance_path is not None:
164
+ if variance_ext is None:
165
+ self.var_data, self.var_header = fits.getdata(
166
+ self.variance_path,
167
+ header=True
168
+ )
169
+ else:
170
+ self.var_data, self.var_header = fits.getdata(
171
+ self.variance_path,
172
+ variance_ext,
173
+ header=True
174
+ )
175
+ self.has_variance = True
176
+ else:
177
+ self.var_data = None
178
+ self.var_header = None
179
+ self.has_variance = False
180
+
181
+ def update_best_PA(self, best_PA: float) -> None:
182
+ """
183
+ Update the best position angle for this image.
184
+
185
+ Parameters
186
+ ----------
187
+ best_PA : float
188
+ New position angle in degrees.
189
+ """
190
+ self.best_PA = best_PA
191
+
192
+ def __repr__(self) -> str:
193
+ """Return string representation of the Image."""
194
+ return (
195
+ f"Image('{self.image_path}', "
196
+ f"pixel_scale={self.pixel_scale:.4f}, "
197
+ f"has_variance={self.has_variance})"
198
+ )
199
+
200
+
201
+ class ImagesCollection:
202
+ """
203
+ A collection of Image objects for batch processing.
204
+
205
+ This class manages multiple Image objects, providing dictionary-like access
206
+ by image name and methods to add new images to the collection.
207
+
208
+ Parameters
209
+ ----------
210
+ images : list of Image, optional
211
+ List of Image objects to initialise the collection. Default is empty list.
212
+ image_names : list of str, optional
213
+ List of names/identifiers for each image. Must have the same length as images.
214
+ Default is empty list.
215
+
216
+ Attributes
217
+ ----------
218
+ image_names : list of str
219
+ List of image identifiers.
220
+ n_images : int
221
+ Number of images in the collection.
222
+ data : dict
223
+ Dictionary mapping image names to Image objects.
224
+
225
+ Raises
226
+ ------
227
+ ValueError
228
+ If the number of images does not match the number of image names.
229
+
230
+ Examples
231
+ --------
232
+ >>> # Create collection from existing images
233
+ >>> img1 = Image("field1.fits")
234
+ >>> img2 = Image("field2.fits")
235
+ >>> collection = ImagesCollection(
236
+ ... images=[img1, img2],
237
+ ... image_names=["field1", "field2"]
238
+ ... )
239
+
240
+ >>> # Add images incrementally
241
+ >>> collection = ImagesCollection()
242
+ >>> collection.add_image(Image("field3.fits"), "field3")
243
+
244
+ >>> # Access images by name
245
+ >>> field1_data = collection.data["field1"].image_data
246
+ >>> field1_wcs = collection["field1"].wcs
247
+ """
248
+
249
+ def __init__(self,
250
+ images: Optional[List[Image]] = None,
251
+ image_names: Optional[List[str]] = None):
252
+
253
+ # Handle default mutable arguments
254
+ if images is None:
255
+ images = []
256
+ if image_names is None:
257
+ image_names = []
258
+
259
+ # Validate input lengths
260
+ if len(images) != len(image_names):
261
+ raise ValueError(
262
+ f"Number of images ({len(images)}) must match "
263
+ f"number of image names ({len(image_names)})"
264
+ )
265
+
266
+ # Store image names and count
267
+ self.image_names = list(image_names)
268
+ self.n_images = len(self.image_names)
269
+
270
+ # Create dictionary mapping names to Image objects
271
+ self.data: Dict[str, Image] = {
272
+ name: image for name, image in zip(self.image_names, images)
273
+ }
274
+
275
+ def add_image(self, image: Image, image_name: str) -> None:
276
+ """
277
+ Add a new image to the collection.
278
+
279
+ Parameters
280
+ ----------
281
+ image : Image
282
+ Image object to add.
283
+ image_name : str
284
+ Identifier for the image.
285
+
286
+ Raises
287
+ ------
288
+ ValueError
289
+ If an image with the same name already exists.
290
+ """
291
+ if image_name in self.data:
292
+ raise ValueError(
293
+ f"Image with name '{image_name}' already exists in collection. "
294
+ f"Use a different name or remove the existing image first."
295
+ )
296
+
297
+ self.data[image_name] = image
298
+ self.image_names.append(image_name)
299
+ self.n_images += 1
300
+
301
+ def remove_image(self, image_name: str) -> None:
302
+ """
303
+ Remove an image from the collection.
304
+
305
+ Parameters
306
+ ----------
307
+ image_name : str
308
+ Identifier of the image to remove.
309
+
310
+ Raises
311
+ ------
312
+ KeyError
313
+ If no image with the given name exists.
314
+ """
315
+ if image_name not in self.data:
316
+ raise KeyError(f"No image with name '{image_name}' in collection.")
317
+
318
+ del self.data[image_name]
319
+ self.image_names.remove(image_name)
320
+ self.n_images -= 1
321
+
322
+ def __getitem__(self, image_name: str) -> "Image":
323
+ """Return the image associated with `image_name`."""
324
+ return self.data[image_name]
325
+
326
+ def __contains__(self, image_name: str) -> bool:
327
+ """Return whether `image_name` exists in the collection."""
328
+ return image_name in self.data
329
+
330
+ def __len__(self) -> int:
331
+ """Return the number of images in the collection."""
332
+ return len(self.data)
333
+
334
+ def __iter__(self) -> Iterator[str]:
335
+ """Iterate over image names."""
336
+ return iter(self.data)
337
+
338
+ def items(self) -> Iterator[Tuple[str, "Image"]]:
339
+ """Return an iterator over `(image_name, image)` pairs."""
340
+ return self.data.items()
341
+
342
+ def keys(self):
343
+ """Return the image names."""
344
+ return self.data.keys()
345
+
346
+ def values(self):
347
+ """Return the stored `Image` objects."""
348
+ return self.data.values()
349
+
350
+ def summary_dict(self) -> Dict[str, Dict[str, object]]:
351
+ """
352
+ Build a summary dictionary for all images in the collection.
353
+
354
+ Returns
355
+ -------
356
+ dict
357
+ Nested dictionary with image names as top-level keys and summary
358
+ properties as values.
359
+ """
360
+ summary = {}
361
+
362
+ for name, im in self.data.items():
363
+ image_path = getattr(im, "image_path", None)
364
+ summary[name] = {
365
+ "image path": os.path.basename(image_path) if image_path else None,
366
+ "AB zeropoint": getattr(im, "mag_zeropoint", None),
367
+ "pixel scale": getattr(im, "pixel_scale", None),
368
+ "variance type": getattr(im, "variance_type", None)
369
+ }
370
+
371
+ return summary
372
+
373
+ def _format_table(self) -> str:
374
+ """
375
+ Return a plain-text table summarising the collection.
376
+
377
+ The table uses:
378
+ - columns: image names
379
+ - rows: selected image properties
380
+
381
+ Returns
382
+ -------
383
+ str
384
+ Formatted text table.
385
+ """
386
+ if not self.data:
387
+ return "ImagesCollection(empty)"
388
+
389
+ summary = self.summary_dict()
390
+ field_names = list(summary.keys())
391
+ row_names = [
392
+ "image path",
393
+ "AB zeropoint",
394
+ "pixel scale",
395
+ "variance type"
396
+ ]
397
+
398
+ # Build string matrix
399
+ table = []
400
+ header = ["property"] + field_names
401
+ table.append(header)
402
+
403
+ for row_name in row_names:
404
+ row = [row_name]
405
+ for field in field_names:
406
+ value = summary[field][row_name]
407
+
408
+ if isinstance(value, float):
409
+ if row_name == "AB zeropoint":
410
+ value_str = f"{value:.2f}"
411
+ elif row_name == "pixel scale":
412
+ value_str = f"{value:.5f}"
413
+ else:
414
+ value_str = f"{value:.3f}"
415
+ else:
416
+ value_str = str(value)
417
+
418
+ row.append(value_str)
419
+ table.append(row)
420
+
421
+ # Compute column widths
422
+ widths = [max(len(str(row[i])) for row in table) for i in range(len(table[0]))]
423
+
424
+ # Format rows
425
+ lines = []
426
+ for i, row in enumerate(table):
427
+ line = " | ".join(str(cell).ljust(widths[j]) for j, cell in enumerate(row))
428
+ lines.append(line)
429
+ if i == 0:
430
+ lines.append("-+-".join("-" * w for w in widths))
431
+
432
+ return "\n".join(lines) + "\n"
433
+
434
+ def __repr__(self) -> str:
435
+ """Return a readable summary table of the image collection."""
436
+ return self._format_table()
437
+
438
+ __str__ = __repr__