lightstack 0.2.0__py3-none-any.whl → 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lightstack/__init__.py CHANGED
@@ -5,7 +5,7 @@ of multi-filter photometric datacubes using astronomical imaging (HST and JWST).
5
5
  Main functionalities include:
6
6
  - Crop regions
7
7
  - Image alignment and photometric datacube construction
8
- - PSF matching using convolution kernels
8
+ - Empirical PSF (ePSF) construction and PSF matching using convolution kernels
9
9
  - Visualization of FITS images and datacubes
10
10
  """
11
11
 
@@ -14,8 +14,10 @@ Main functionalities include:
14
14
  # =========================
15
15
  from .crop import (
16
16
  get_sky_bbox_from_cutout,
17
+ get_common_sky_bbox,
17
18
  crop_from_radec,
18
19
  crop_using_reference,
20
+ get_common_region_from_reg,
19
21
  crop_reg,
20
22
  cut_region_2d,
21
23
  )
@@ -25,6 +27,7 @@ from .crop import (
25
27
  # Datacube / alignment
26
28
  # =========================
27
29
  from .datacube import (
30
+ load_image_fits,
28
31
  align_reproject_fits,
29
32
  build_datacube,
30
33
  cut_region_datacube,
@@ -37,6 +40,29 @@ from .datacube import (
37
40
  # PSF matching
38
41
  # =========================
39
42
  from .psf import (
43
+ get_psf_input_files,
44
+ extract_cutouts,
45
+ subtract_background,
46
+ measure_centers,
47
+ recenter_cutouts,
48
+ normalize_by_aperture,
49
+ radial_profile,
50
+ center_crop,
51
+ normalize_psf,
52
+ oversample_psf,
53
+ add_arcsec_axis,
54
+ encircled_energy,
55
+ clean_stellar_cutouts_radially,
56
+ plot_stellar_radial_profiles,
57
+ plot_psf_stars,
58
+ plot_psf_diagnostics,
59
+ make_psf_header,
60
+ build_empirical_psf,
61
+ pad_psf_for_resampling,
62
+ resample_psf_to_pixel_scale,
63
+ centroid_weighted,
64
+ make_odd,
65
+ resample_psf,
40
66
  build_kernel,
41
67
  save_kernel,
42
68
  apply_kernel,
@@ -56,8 +82,18 @@ from .plot import (
56
82
  # Utils
57
83
  # =========================
58
84
  from .utils import (
85
+ identify_filter,
86
+ get_filter_info,
87
+ select_filters,
88
+ add_custom_dataset,
89
+ simplify_fits_filename,
59
90
  find_ext,
60
- infer_filter,
91
+ save_fits,
92
+ read_ds9_physical_boxes,
93
+ counts_s_to_jy,
94
+ MJy_sr_to_jy,
95
+ get_pixel_scale,
96
+ get_pixel_scale_from_wcs,
61
97
  )
62
98
 
63
99
  # =========================
@@ -66,12 +102,15 @@ from .utils import (
66
102
  __all__ = [
67
103
  # crop
68
104
  "get_sky_bbox_from_cutout",
105
+ "get_common_sky_bbox",
69
106
  "crop_from_radec",
70
107
  "crop_using_reference",
108
+ "get_common_region_from_reg",
71
109
  "crop_reg",
72
110
  "cut_region_2d",
73
111
 
74
112
  # datacube
113
+ "load_image_fits",
75
114
  "align_reproject_fits",
76
115
  "build_datacube",
77
116
  "cut_region_datacube",
@@ -80,6 +119,29 @@ __all__ = [
80
119
  "update_cube_header",
81
120
 
82
121
  # psf
122
+ "get_psf_input_files",
123
+ "extract_cutouts",
124
+ "subtract_background",
125
+ "measure_centers",
126
+ "recenter_cutouts",
127
+ "normalize_by_aperture",
128
+ "radial_profile",
129
+ "center_crop",
130
+ "normalize_psf",
131
+ "oversample_psf",
132
+ "add_arcsec_axis",
133
+ "encircled_energy",
134
+ "clean_stellar_cutouts_radially",
135
+ "plot_stellar_radial_profiles",
136
+ "plot_psf_stars",
137
+ "plot_psf_diagnostics",
138
+ "make_psf_header",
139
+ "build_empirical_psf",
140
+ "pad_psf_for_resampling",
141
+ "resample_psf_to_pixel_scale",
142
+ "centroid_weighted",
143
+ "make_odd",
144
+ "resample_psf",
83
145
  "build_kernel",
84
146
  "save_kernel",
85
147
  "apply_kernel",
@@ -92,13 +154,16 @@ __all__ = [
92
154
 
93
155
  # utils
94
156
  "find_ext",
95
- "infer_filter",
96
- "pick_folder",
97
- "get_filter",
98
- "filter_id",
157
+ "identify_filter",
158
+ "get_filter_info",
159
+ "select_filters",
160
+ "add_custom_dataset",
161
+ "simplify_fits_filename",
99
162
  "save_fits",
100
- "sort_fits",
163
+ "read_ds9_physical_boxes",
164
+ "counts_s_to_jy",
101
165
  "MJy_sr_to_jy",
102
166
  "get_pixel_scale",
167
+ "get_pixel_scale_from_wcs",
103
168
 
104
169
  ]
lightstack/crop.py CHANGED
@@ -6,50 +6,9 @@ from astropy.wcs.utils import proj_plane_pixel_scales, skycoord_to_pixel
6
6
  from astropy.coordinates import SkyCoord
7
7
  import astropy.units as u
8
8
 
9
- from .utils import find_ext
10
-
11
- def get_sky_bbox_from_cutout(fits_cut):
12
- """
13
- Get sky bounding box (RA, Dec) from a FITS cutout.
14
-
15
- Parameters
16
- ----------
17
- fits_cut : str
18
- Path to FITS file
19
-
20
- Returns
21
- -------
22
- ra, dec : arrays
23
- RA and Dec of the four corners
24
- """
25
- # Read FITS
26
- with fits.open(fits_cut) as hdul:
27
- ext = find_ext(hdul)
28
- if ext is None:
29
- raise ValueError(f"No 2D image found in {fits_cut}")
30
-
31
- data = hdul[ext].data
32
- header = hdul[ext].header
9
+ from regions import Regions, RectangleSkyRegion
33
10
 
34
- wcs = WCS(header)
35
-
36
- ny, nx = data.shape
37
-
38
- # Define pixel coordinates of the four corners
39
- corners_pix = np.array([
40
- [0, 0],
41
- [nx-1, 0],
42
- [0, ny-1],
43
- [nx-1, ny-1]])
44
-
45
- # Convert pixel coordinates to sky (RA, Dec)
46
- ra, dec = wcs.wcs_pix2world(
47
- corners_pix[:, 0],
48
- corners_pix[:, 1],
49
- 0 # origin = 0 (Python convention)
50
- )
51
-
52
- return ra, dec
11
+ from .utils import find_ext
53
12
 
54
13
 
55
14
  def crop_from_radec(fits_path, ra, dec, size_arcsec, output_path=None):
@@ -70,6 +29,9 @@ def crop_from_radec(fits_path, ra, dec, size_arcsec, output_path=None):
70
29
  size_arcsec : float
71
30
  Size of the cutout (in arcseconds). The cutout is square.
72
31
 
32
+ output_path : str or pathlib.Path, optional
33
+ If provided, path where the cropped FITS image is written.
34
+
73
35
  Returns
74
36
  -------
75
37
  data_cut : 2D numpy array
@@ -129,78 +91,380 @@ def crop_from_radec(fits_path, ra, dec, size_arcsec, output_path=None):
129
91
  return data_cut, header_cut
130
92
 
131
93
 
132
- def crop_using_reference(fits_path, ref_cutout, output_path=None):
94
+ def get_sky_bbox_from_cutout(fits_cut):
95
+ """
96
+ Compute the sky bounding box of a FITS image.
97
+
98
+ The bounding box is defined by the minimum and maximum right ascension
99
+ and declination covered by the image footprint.
100
+
101
+ Parameters
102
+ ----------
103
+ fits_cut : str
104
+ Path to the FITS image.
105
+
106
+ Returns
107
+ -------
108
+ sky_bbox : dict
109
+ Dictionary describing the sky bounding box with the keys:
110
+
111
+ - "ra_min"
112
+ - "ra_max"
113
+ - "dec_min"
114
+ - "dec_max"
115
+
116
+ Raises
117
+ ------
118
+ ValueError
119
+ If the FITS file does not contain a valid 2D image.
120
+ """
121
+
122
+ with fits.open(fits_cut) as hdul:
123
+
124
+ ext = find_ext(hdul)
125
+ if ext is None:
126
+ raise ValueError(f"No 2D image found in {fits_cut}")
127
+
128
+ header = hdul[ext].header
129
+ wcs = WCS(header)
130
+
131
+ footprint = wcs.calc_footprint()
132
+
133
+ sky_bbox = {
134
+ "ra_min": np.min(footprint[:, 0]),
135
+ "ra_max": np.max(footprint[:, 0]),
136
+ "dec_min": np.min(footprint[:, 1]),
137
+ "dec_max": np.max(footprint[:, 1]),
138
+ }
139
+
140
+ return sky_bbox
141
+
142
+
143
+ def get_common_sky_bbox(fits_files):
144
+ """
145
+ Compute the common sky bounding box shared by a list of FITS images. The returned region is the rectangular intersection of the RA/Dec bounding boxes of the image footprints; it is not the exact geometric intersection of the footprints.
146
+
147
+ Parameters
148
+ ----------
149
+ fits_files : list of str
150
+ List of FITS filenames.
151
+
152
+ Returns
153
+ -------
154
+ sky_bbox : dict
155
+ Dictionary containing the common sky region with the keys:
156
+
157
+ - "ra_min"
158
+ - "ra_max"
159
+ - "dec_min"
160
+ - "dec_max"
161
+
162
+ Raises
163
+ ------
164
+ ValueError
165
+ If the images do not share a common sky footprint.
166
+ """
167
+
168
+ ra_min_all = []
169
+ ra_max_all = []
170
+ dec_min_all = []
171
+ dec_max_all = []
172
+
173
+ for file in fits_files:
174
+
175
+ with fits.open(file) as hdul:
176
+
177
+ ext = find_ext(hdul)
178
+ if ext is None:
179
+ continue
180
+
181
+ wcs = WCS(hdul[ext].header)
182
+
183
+ footprint = wcs.calc_footprint()
184
+
185
+ ra = footprint[:, 0]
186
+ dec = footprint[:, 1]
187
+
188
+ ra_min_all.append(np.min(ra))
189
+ ra_max_all.append(np.max(ra))
190
+ dec_min_all.append(np.min(dec))
191
+ dec_max_all.append(np.max(dec))
192
+
193
+ sky_bbox = {
194
+ "ra_min": max(ra_min_all),
195
+ "ra_max": min(ra_max_all),
196
+ "dec_min": max(dec_min_all),
197
+ "dec_max": min(dec_max_all)
198
+ }
199
+
200
+ if (
201
+ sky_bbox["ra_min"] >= sky_bbox["ra_max"] or
202
+ sky_bbox["dec_min"] >= sky_bbox["dec_max"]
203
+ ):
204
+ raise ValueError("Images have no common sky footprint.")
205
+
206
+ return sky_bbox
207
+
208
+
209
+ def crop_using_reference(
210
+ fits_path,
211
+ ref_cutout=None,
212
+ sky_bbox=None,
213
+ output_path=None):
133
214
  """
134
- Crop a FITS image using the sky footprint of a reference cutout.
215
+ Crop a FITS image to a specified sky region.
135
216
 
136
- This function extracts a region from a target image such that it matches
137
- the sky coverage (RA/Dec bounding box) of a reference FITS cutout.
217
+ The sky region can be defined either by the footprint of a reference
218
+ FITS image or by a sky bounding box returned by
219
+ ``get_sky_bbox_from_cutout()`` or ``get_common_sky_bbox()``.
138
220
 
139
221
  Parameters
140
222
  ----------
141
223
  fits_path : str
142
- Path to the target FITS image to be cropped.
224
+ Path to the FITS image to be cropped.
143
225
 
144
- ref_cutout : str
145
- Path to the reference FITS cutout defining the sky region.
226
+ ref_cutout : str, optional
227
+ Path to a reference FITS image. If provided, its sky footprint is
228
+ used to define the cropping region.
229
+
230
+ sky_bbox : dict, optional
231
+ Dictionary describing the sky bounding box with the keys
232
+
233
+ - "ra_min"
234
+ - "ra_max"
235
+ - "dec_min"
236
+ - "dec_max"
237
+
238
+ Typically the output of ``get_sky_bbox_from_cutout()`` or
239
+ ``get_common_sky_bbox()``.
146
240
 
147
241
  output_path : str, optional
148
- If provided, saves the cropped FITS to this path.
242
+ If provided, the cropped FITS image is written to this path.
149
243
 
150
244
  Returns
151
245
  -------
152
- data_cut : 2D numpy array
153
- Cropped image data.
246
+ data_cut : ndarray
247
+ Cropped image.
154
248
 
155
- header_cut : FITS header
156
- Updated header with corrected WCS reference (CRPIX).
249
+ header_cut : astropy.io.fits.Header
250
+ Updated FITS header with corrected WCS information.
157
251
  """
158
252
 
159
- # Get RA/Dec bounding box from reference cutout
160
- ra, dec = get_sky_bbox_from_cutout(ref_cutout)
253
+ # Determine sky bounding box
254
+ if sky_bbox is None:
255
+
256
+ if ref_cutout is None:
257
+ raise ValueError(
258
+ "Provide either ref_cutout or sky_bbox."
259
+ )
260
+
261
+ sky_bbox = get_sky_bbox_from_cutout(ref_cutout)
262
+
263
+ # Bounding-box corners
264
+ ra = np.array([
265
+ sky_bbox["ra_min"],
266
+ sky_bbox["ra_max"],
267
+ sky_bbox["ra_max"],
268
+ sky_bbox["ra_min"]
269
+ ])
270
+
271
+ dec = np.array([
272
+ sky_bbox["dec_min"],
273
+ sky_bbox["dec_min"],
274
+ sky_bbox["dec_max"],
275
+ sky_bbox["dec_max"]
276
+ ])
161
277
 
162
278
  # Open FITS
163
279
  with fits.open(fits_path) as hdul:
280
+
164
281
  ext = find_ext(hdul)
165
282
  if ext is None:
166
- raise ValueError(f"No 2D image found in {fits_path}")
283
+ raise ValueError(
284
+ f"No 2D image found in {fits_path}"
285
+ )
167
286
 
168
287
  data = hdul[ext].data
169
288
  header = hdul[ext].header
170
289
  wcs = WCS(header)
171
290
 
172
- # Convert sky coordinates (RA/Dec) to pixel coordinates
291
+ # Convert sky coordinates to pixels
173
292
  x, y = wcs.wcs_world2pix(ra, dec, 0)
174
293
 
175
- # Define bounding box in pixel space
294
+ # Pixel limits
176
295
  x_min = int(np.floor(np.min(x)))
177
296
  x_max = int(np.ceil(np.max(x)))
297
+
178
298
  y_min = int(np.floor(np.min(y)))
179
299
  y_max = int(np.ceil(np.max(y)))
180
300
 
181
301
  ny, nx = data.shape
302
+
182
303
  x_min = max(0, x_min)
183
304
  x_max = min(nx, x_max)
305
+
184
306
  y_min = max(0, y_min)
185
307
  y_max = min(ny, y_max)
186
308
 
187
- # Extract cutout
309
+ # Crop image
188
310
  data_cut = data[y_min:y_max, x_min:x_max]
189
311
 
190
312
  # Update WCS
191
313
  header_cut = header.copy()
192
- header_cut['CRPIX1'] -= x_min
193
- header_cut['CRPIX2'] -= y_min
194
314
 
195
- # Save
315
+ header_cut["CRPIX1"] -= x_min
316
+ header_cut["CRPIX2"] -= y_min
317
+
318
+ # Save output
196
319
  if output_path is not None:
197
- fits.PrimaryHDU(data_cut, header=header_cut).writeto(
320
+
321
+ fits.PrimaryHDU(
322
+ data_cut,
323
+ header=header_cut
324
+ ).writeto(
198
325
  output_path,
199
- overwrite=True)
326
+ overwrite=True
327
+ )
200
328
 
201
329
  return data_cut, header_cut
202
330
 
203
331
 
332
+ def get_common_region_from_reg(
333
+ reg_path,
334
+ output_reg=None,
335
+ color="green"
336
+ ):
337
+ """
338
+ Calculate the common sky area defined by multiple DS9 box regions.
339
+
340
+ Parameters
341
+ ----------
342
+ reg_path : str
343
+ Path to a DS9 region file containing box regions in FK5.
344
+
345
+ output_reg : str or None
346
+ If provided, saves the common region to this DS9 region file.
347
+
348
+ color : str
349
+ Color used for the output DS9 region.
350
+
351
+ Returns
352
+ -------
353
+ common_region : RectangleSkyRegion
354
+ Rectangle representing the common sky area.
355
+
356
+ sky_bbox : dict
357
+ Dictionary containing the sky limits of the common area:
358
+
359
+ - ra_min
360
+ - ra_max
361
+ - dec_min
362
+ - dec_max
363
+
364
+ All values are in degrees.
365
+
366
+ """
367
+
368
+ # Read regions
369
+ regions = Regions.read(reg_path, format="ds9")
370
+
371
+ # Keep only rectangular sky regions
372
+ boxes = [
373
+ region
374
+ for region in regions
375
+ if isinstance(region, RectangleSkyRegion)
376
+ ]
377
+
378
+ if len(boxes) == 0:
379
+ raise ValueError(
380
+ "No RectangleSkyRegion (box) found in the region file."
381
+ )
382
+
383
+ # Get bounding limits of each box
384
+ ra_min_all = []
385
+ ra_max_all = []
386
+ dec_min_all = []
387
+ dec_max_all = []
388
+
389
+ for box in boxes:
390
+
391
+ center = box.center
392
+
393
+ width = box.width.to(u.deg).value
394
+ height = box.height.to(u.deg).value
395
+
396
+ ra = center.ra.deg
397
+ dec = center.dec.deg
398
+
399
+ # Approximation valid for non-rotated boxes
400
+ ra_min_all.append(ra - width / 2)
401
+ ra_max_all.append(ra + width / 2)
402
+
403
+ dec_min_all.append(dec - height / 2)
404
+ dec_max_all.append(dec + height / 2)
405
+
406
+ # Intersection of all boxes
407
+ ra_min = max(ra_min_all)
408
+ ra_max = min(ra_max_all)
409
+
410
+ dec_min = max(dec_min_all)
411
+ dec_max = min(dec_max_all)
412
+
413
+ if ra_min >= ra_max or dec_min >= dec_max:
414
+ raise ValueError(
415
+ "The regions do not have a common sky area."
416
+ )
417
+
418
+ # Center and dimensions
419
+ ra_center = (ra_min + ra_max) / 2
420
+ dec_center = (dec_min + dec_max) / 2
421
+
422
+ width = (ra_max - ra_min) * u.deg
423
+ height = (dec_max - dec_min) * u.deg
424
+
425
+ center = SkyCoord(
426
+ ra_center * u.deg,
427
+ dec_center * u.deg,
428
+ frame="fk5"
429
+ )
430
+
431
+ common_region = RectangleSkyRegion(
432
+ center=center,
433
+ width=width,
434
+ height=height,
435
+ angle=0 * u.deg
436
+ )
437
+
438
+ # Save DS9 region
439
+ if output_reg is not None:
440
+
441
+ output = Regions([common_region])
442
+
443
+ output.write(
444
+ output_reg,
445
+ format="ds9",
446
+ overwrite=True
447
+ )
448
+
449
+ print(f"Common region saved to: {output_reg}")
450
+
451
+ # Return information
452
+ sky_bbox = {
453
+ "ra_min": ra_min,
454
+ "ra_max": ra_max,
455
+ "dec_min": dec_min,
456
+ "dec_max": dec_max,
457
+ "ra_center": ra_center,
458
+ "dec_center": dec_center,
459
+ "width_deg": width.to_value(u.deg),
460
+ "height_deg": height.to_value(u.deg),
461
+ "width_arcsec": width.to_value(u.arcsec),
462
+ "height_arcsec": height.to_value(u.arcsec),
463
+ }
464
+
465
+ return common_region, sky_bbox
466
+
467
+
204
468
  def crop_reg(fits_path, region):
205
469
  """
206
470
  Crops a FITS image using a DS9 region.
@@ -276,7 +540,7 @@ def cut_region_2d(fits_file, x_start, x_end, y_start, y_end, output_path):
276
540
  with fits.open(fits_file) as hdul:
277
541
  ext = find_ext(hdul)
278
542
  if ext is None:
279
- raise ValueError(f"No image data found in {fits_path}")
543
+ raise ValueError(f"No image data found in {fits_file}")
280
544
 
281
545
  data = hdul[ext].data
282
546
  header = hdul[ext].header