22"""Collection of small images (stamps)."""
24__all__ = [
"Stamp",
"Stamps",
"StampsBase",
"writeFits",
"readFitsWithOptions"]
27from collections.abc
import Sequence
28from dataclasses
import dataclass, field, fields
32from lsst.afw.image import ImageFitsReader, MaskedImage, MaskedImageF, MaskFitsReader
35from lsst.geom import Angle, Box2I, Extent2I, Point2I, SpherePoint, degrees
36from lsst.utils
import doImport
37from lsst.utils.introspection
import get_full_type_name
40def writeFits(filename, stamps, metadata, type_name, write_mask, write_variance, write_archive=False):
41 """Write a single FITS file containing all stamps.
46 A string indicating the output filename
47 stamps : iterable of `BaseStamp`
48 An iterable of Stamp objects
49 metadata : `PropertyList`
50 A collection of key, value metadata pairs to be
51 written to the primary header
53 Python type name of the StampsBase subclass to use
55 Write the mask data to the output file?
56 write_variance : `bool`
57 Write the variance data to the output file?
58 write_archive : `bool`, optional
59 Write an archive to store Persistables along with each stamp?
62 metadata[
"HAS_MASK"] = write_mask
63 metadata[
"HAS_VARIANCE"] = write_variance
64 metadata[
"HAS_ARCHIVE"] = write_archive
65 metadata[
"N_STAMPS"] = len(stamps)
66 metadata[
"STAMPCLS"] = type_name
68 metadata[
"VERSION"] = 1
70 fitsFile =
Fits(filename,
"w")
71 fitsFile.createEmpty()
75 archive_ids = [oa.put(stamp.archive_element)
for stamp
in stamps]
76 metadata[
"ARCHIVE_IDS"] = archive_ids
77 fitsFile.writeMetadata(metadata)
78 oa.writeFits(fitsFile)
80 fitsFile.writeMetadata(metadata)
83 for i, stamp
in enumerate(stamps):
86 metadata.update({
"EXTVER": i + 1,
"EXTNAME":
"IMAGE"})
87 stamp.stamp_im.getImage().
writeFits(filename, metadata=metadata, mode=
"a")
90 metadata.update({
"EXTVER": i + 1,
"EXTNAME":
"MASK"})
91 stamp.stamp_im.getMask().
writeFits(filename, metadata=metadata, mode=
"a")
94 metadata.update({
"EXTVER": i + 1,
"EXTNAME":
"VARIANCE"})
95 stamp.stamp_im.getVariance().
writeFits(filename, metadata=metadata, mode=
"a")
100 """Read stamps from FITS file, allowing for only a subregion of the stamps
106 A string indicating the file to read
107 stamp_factory : classmethod
108 A factory function defined on a dataclass for constructing
109 stamp objects a la `~lsst.meas.algorithm.Stamp`
110 options : `PropertyList` or `dict`
111 A collection of parameters. If it contains a bounding box
112 (``bbox`` key), or if certain other keys (``llcX``, ``llcY``,
113 ``width``, ``height``) are available for one to be constructed,
114 the bounding box is passed to the ``FitsReader`` in order to
119 stamps : `list` of dataclass objects like `Stamp`, PropertyList
120 A tuple of a list of `Stamp`-like objects
121 metadata : `PropertyList`
126 The data are read using the data type expected by the
127 `~lsst.afw.image.MaskedImage` class attached to the `AbstractStamp`
128 dataclass associated with the factory method.
131 metadata = readMetadata(filename, hdu=0)
132 nStamps = metadata[
"N_STAMPS"]
133 has_archive = metadata[
"HAS_ARCHIVE"]
135 archive_ids = metadata.getArray(
"ARCHIVE_IDS")
136 with Fits(filename,
"r")
as f:
137 nExtensions = f.countHdus()
142 if "bbox" in options.keys():
143 kwargs[
"bbox"] = options[
"bbox"]
145 elif "llcX" in options.keys():
146 llcX = options[
"llcX"]
147 llcY = options[
"llcY"]
148 width = options[
"width"]
149 height = options[
"height"]
151 kwargs[
"bbox"] = bbox
157 masked_image_cls =
None
158 for stamp_field
in fields(stamp_factory.__self__):
159 if issubclass(stamp_field.type, MaskedImage):
160 masked_image_cls = stamp_field.type
163 raise RuntimeError(
"Stamp factory does not use MaskedImage.")
164 default_dtype = np.dtype(masked_image_cls.dtype)
165 variance_dtype = np.dtype(np.float32)
168 for idx
in range(nExtensions - 1):
170 md = readMetadata(filename, hdu=idx + 1)
172 if md[
"XTENSION"] ==
"BINTABLE" and not (
"ZIMAGE" in md
and md[
"ZIMAGE"]):
173 if md[
"EXTNAME"] !=
"ARCHIVE_INDEX":
175 if md[
"EXTNAME"]
in (
"IMAGE",
"VARIANCE"):
177 if md[
"EXTNAME"] ==
"VARIANCE":
178 dtype = variance_dtype
180 dtype = default_dtype
181 elif md[
"EXTNAME"] ==
"MASK":
183 elif md[
"EXTNAME"] ==
"ARCHIVE_INDEX":
185 archive = InputArchive.readFits(f)
187 elif md[
"EXTTYPE"] ==
"ARCHIVE_DATA":
190 raise ValueError(f
"Unknown extension type: {md['EXTNAME']}")
191 stamp_parts.setdefault(md[
"EXTVER"], {})[md[
"EXTNAME"].lower()] = reader.read(dtype=dtype,
193 if len(stamp_parts) != nStamps:
195 f
"Number of stamps read ({len(stamp_parts)}) does not agree with the "
196 f
"number of stamps recorded in the metadata ({nStamps})."
200 for k
in range(nStamps):
202 maskedImage = masked_image_cls(**stamp_parts[k + 1])
203 archive_element = archive.get(archive_ids[k])
if has_archive
else None
204 stamps.append(stamp_factory(maskedImage, metadata, k, archive_element))
206 return stamps, metadata
211 """Single abstract stamp.
215 Inherit from this class to add metadata to the stamp.
220 def factory(cls, stamp_im, metadata, index, archive_element=None):
221 """This method is needed to service the FITS reader. We need a standard
222 interface to construct objects like this. Parameters needed to
223 construct this object are passed in via a metadata dictionary and then
224 passed to the constructor of this class.
228 stamp : `~lsst.afw.image.MaskedImage`
229 Pixel data to pass to the constructor
231 Dictionary containing the information
232 needed by the constructor.
234 Index into the lists in ``metadata``
235 archive_element : `~lsst.afw.table.io.Persistable`, optional
236 Archive element (e.g. Transform or WCS) associated with this stamp.
240 stamp : `AbstractStamp`
241 An instance of this class
243 raise NotImplementedError
258 stamp_im : `~lsst.afw.image.MaskedImageF`
259 The actual pixel values for the postage stamp.
260 archive_element : `~lsst.afw.table.io.Persistable` or `None`, optional
261 Archive element (e.g. Transform or WCS) associated with this stamp.
262 position : `~lsst.geom.SpherePoint` or `None`, optional
263 Position of the center of the stamp. Note the user must keep track of
264 the coordinate system.
267 stamp_im: MaskedImageF
268 archive_element: Persistable |
None =
None
269 position: SpherePoint |
None = field(default_factory=_default_position)
272 def factory(cls, stamp_im, metadata, index, archive_element=None):
273 """This method is needed to service the FITS reader. We need a standard
274 interface to construct objects like this. Parameters needed to
275 construct this object are passed in via a metadata dictionary and then
276 passed to the constructor of this class. If lists of values are passed
277 with the following keys, they will be passed to the constructor,
278 otherwise dummy values will be passed: RA_DEG, DEC_DEG. They should
279 each point to lists of values.
283 stamp : `~lsst.afw.image.MaskedImage`
284 Pixel data to pass to the constructor
286 Dictionary containing the information
287 needed by the constructor.
289 Index into the lists in ``metadata``
290 archive_element : `~lsst.afw.table.io.Persistable`, optional
291 Archive element (e.g. Transform or WCS) associated with this stamp.
296 An instance of this class
298 if "RA_DEG" in metadata
and "DEC_DEG" in metadata:
301 archive_element=archive_element,
303 Angle(metadata.getArray(
"RA_DEG")[index], degrees),
304 Angle(metadata.getArray(
"DEC_DEG")[index], degrees),
310 archive_element=archive_element,
316 """Collection of stamps and associated metadata.
321 This should be an iterable of dataclass objects
322 a la ``~lsst.meas.algorithms.Stamp``.
323 metadata : `~lsst.daf.base.PropertyList`, optional
324 Metadata associated with the objects within the stamps.
325 use_mask : `bool`, optional
326 If ``True`` read and write the mask data. Default ``True``.
327 use_variance : `bool`, optional
328 If ``True`` read and write the variance data. Default ``True``.
329 use_archive : `bool`, optional
330 If ``True``, read and write an Archive that contains a Persistable
331 associated with each stamp, for example a Transform or a WCS.
336 A butler can be used to read only a part of the stamps,
339 >>> starSubregions = butler.get(
342 parameters={"bbox": bbox}
346 def __init__(self, stamps, metadata=None, use_mask=True, use_variance=True, use_archive=False):
348 if not isinstance(stamp, AbstractStamp):
349 raise ValueError(f
"The entries in stamps must inherit from AbstractStamp. Got {type(stamp)}.")
358 """Build an instance of this class from a file.
363 Name of the file to read
370 """Build an instance of this class with options.
375 Name of the file to read
376 options : `PropertyList`
377 Collection of metadata parameters
384 if cls
is not StampsBase:
385 raise NotImplementedError(f
"Please implement specific FITS reader for class {cls}")
388 metadata = readMetadata(filename, hdu=0)
389 type_name = metadata.get(
"STAMPCLS")
390 if type_name
is None:
392 f
"No class name in file {filename}. Unable to instantiate correct stamps subclass. "
393 "Is this an old version format Stamps file?"
397 stamp_type = doImport(type_name)
404 """Make sure metadata is up to date, as this object can be extended."""
405 raise NotImplementedError
408 """Write this object to a file.
413 Name of file to write.
416 type_name = get_full_type_name(self)
437 """Retrieve star images.
442 `list` [`~lsst.afw.image.MaskedImageF`]
444 return [stamp.stamp_im
for stamp
in self.
_stamps]
447 """Retrieve archive elements associated with each stamp.
452 `list` [`~lsst.afw.table.io.Persistable`]
454 return [stamp.archive_element
for stamp
in self.
_stamps]
464 self.
_metadata[
"RA_DEG"] = [p.getRa().asDegrees()
for p
in positions]
465 self.
_metadata[
"DEC_DEG"] = [p.getDec().asDegrees()
for p
in positions]
468 return [s.position
for s
in self.
_stamps]
471 """Add an additional stamp.
476 Stamp object to append.
478 if not isinstance(item, Stamp):
479 raise ValueError(
"Objects added must be a Stamp object.")
484 """Extend Stamps instance by appending elements from another instance.
488 stamps_list : `list` [`Stamp`]
489 List of Stamp object to append.
492 if not isinstance(s, Stamp):
493 raise ValueError(
"Can only extend with Stamp objects")
498 """Build an instance of this class from a file.
503 Name of the file to read.
508 An instance of this class.
514 """Build an instance of this class with options.
519 Name of the file to read.
520 options : `PropertyList` or `dict`
521 Collection of metadata parameters.
526 An instance of this class.
532 use_mask=metadata[
"HAS_MASK"],
533 use_variance=metadata[
"HAS_VARIANCE"],
534 use_archive=metadata[
"HAS_ARCHIVE"],
factory(cls, stamp_im, metadata, index, archive_element=None)
factory(cls, stamp_im, metadata, index, archive_element=None)
__init__(self, stamps, metadata=None, use_mask=True, use_variance=True, use_archive=False)
readFitsWithOptions(cls, filename, options)
writeFits(self, filename)
readFitsWithOptions(cls, filename, options)
writeFits(filename, stamps, metadata, type_name, write_mask, write_variance, write_archive=False)
readFitsWithOptions(filename, stamp_factory, options)