LSST Applications g0265f82a02+c6dfa2ddaf,g1162b98a3f+b2075782a9,g2079a07aa2+1b2e822518,g2bbee38e9b+c6dfa2ddaf,g337abbeb29+c6dfa2ddaf,g3ddfee87b4+a60788ef87,g50ff169b8f+2eb0e556e8,g52b1c1532d+90ebb246c7,g555ede804d+a60788ef87,g591dd9f2cf+ba8caea58f,g5ec818987f+864ee9cddb,g858d7b2824+9ee1ab4172,g876c692160+a40945ebb7,g8a8a8dda67+90ebb246c7,g8cdfe0ae6a+4fd9e222a8,g99cad8db69+5e309b7bc6,g9ddcbc5298+a1346535a5,ga1e77700b3+df8f93165b,ga8c6da7877+aa12a14d27,gae46bcf261+c6dfa2ddaf,gb0e22166c9+8634eb87fb,gb3f2274832+d0da15e3be,gba4ed39666+1ac82b564f,gbb8dafda3b+5dfd9c994b,gbeb006f7da+97157f9740,gc28159a63d+c6dfa2ddaf,gc86a011abf+9ee1ab4172,gcf0d15dbbd+a60788ef87,gdaeeff99f8+1cafcb7cd4,gdc0c513512+9ee1ab4172,ge79ae78c31+c6dfa2ddaf,geb67518f79+ba1859f325,geb961e4c1e+f9439d1e6f,gee10cc3b42+90ebb246c7,gf1cff7945b+9ee1ab4172,w.2024.12
LSST Data Management Base Package
Loading...
Searching...
No Matches
Classes | Functions
lsst.meas.algorithms.stamps Namespace Reference

Classes

class  AbstractStamp
 
class  Stamp
 
class  Stamps
 
class  StampsBase
 

Functions

 writeFits (filename, stamps, metadata, type_name, write_mask, write_variance, write_archive=False)
 
 readFitsWithOptions (filename, stamp_factory, options)
 
 _default_position ()
 

Detailed Description

Collection of small images (stamps).

Function Documentation

◆ _default_position()

lsst.meas.algorithms.stamps._default_position ( )
protected

Definition at line 242 of file stamps.py.

242def _default_position():
243 # SpherePoint is nominally mutable in C++ so we must use a factory
244 # and return an entirely new SpherePoint each time a Stamps is created.
245 return SpherePoint(Angle(np.nan), Angle(np.nan))
246
247
248@dataclass

◆ readFitsWithOptions()

lsst.meas.algorithms.stamps.readFitsWithOptions ( filename,
stamp_factory,
options )
Read stamps from FITS file, allowing for only a subregion of the stamps
to be read.

Parameters
----------
filename : `str`
    A string indicating the file to read
stamp_factory : classmethod
    A factory function defined on a dataclass for constructing
    stamp objects a la `~lsst.meas.algorithm.Stamp`
options : `PropertyList` or `dict`
    A collection of parameters. If it contains a bounding box
    (``bbox`` key), or if certain other keys (``llcX``, ``llcY``,
    ``width``, ``height``) are available for one to be constructed,
    the bounding box is passed to the ``FitsReader`` in order to
    return a sub-image.

Returns
-------
stamps : `list` of dataclass objects like `Stamp`, PropertyList
    A tuple of a list of `Stamp`-like objects
metadata : `PropertyList`
    The metadata

Notes
-----
The data are read using the data type expected by the
`~lsst.afw.image.MaskedImage` class attached to the `AbstractStamp`
dataclass associated with the factory method.

Definition at line 99 of file stamps.py.

99def readFitsWithOptions(filename, stamp_factory, options):
100 """Read stamps from FITS file, allowing for only a subregion of the stamps
101 to be read.
102
103 Parameters
104 ----------
105 filename : `str`
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
115 return a sub-image.
116
117 Returns
118 -------
119 stamps : `list` of dataclass objects like `Stamp`, PropertyList
120 A tuple of a list of `Stamp`-like objects
121 metadata : `PropertyList`
122 The metadata
123
124 Notes
125 -----
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.
129 """
130 # extract necessary info from metadata
131 metadata = readMetadata(filename, hdu=0)
132 nStamps = metadata["N_STAMPS"]
133 has_archive = metadata["HAS_ARCHIVE"]
134 if has_archive:
135 archive_ids = metadata.getArray("ARCHIVE_IDS")
136 with Fits(filename, "r") as f:
137 nExtensions = f.countHdus()
138 # check if a bbox was provided
139 kwargs = {}
140 if options:
141 # gen3 API
142 if "bbox" in options.keys():
143 kwargs["bbox"] = options["bbox"]
144 # gen2 API
145 elif "llcX" in options.keys():
146 llcX = options["llcX"]
147 llcY = options["llcY"]
148 width = options["width"]
149 height = options["height"]
150 bbox = Box2I(Point2I(llcX, llcY), Extent2I(width, height))
151 kwargs["bbox"] = bbox
152 stamp_parts = {}
153
154 # Determine the dtype from the factory. This allows a Stamp class
155 # to be defined in terms of MaskedImageD or MaskedImageI without
156 # forcing everything to floats.
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
161 break
162 else:
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) # Variance is always the same type.
166
167 # We need to be careful because nExtensions includes the primary HDU.
168 for idx in range(nExtensions - 1):
169 dtype = None
170 md = readMetadata(filename, hdu=idx + 1)
171 if md["EXTNAME"] in ("IMAGE", "VARIANCE"):
172 reader = ImageFitsReader(filename, hdu=idx + 1)
173 if md["EXTNAME"] == "VARIANCE":
174 dtype = variance_dtype
175 else:
176 dtype = default_dtype
177 elif md["EXTNAME"] == "MASK":
178 reader = MaskFitsReader(filename, hdu=idx + 1)
179 elif md["EXTNAME"] == "ARCHIVE_INDEX":
180 f.setHdu(idx + 1)
181 archive = InputArchive.readFits(f)
182 continue
183 elif md["EXTTYPE"] == "ARCHIVE_DATA":
184 continue
185 else:
186 raise ValueError(f"Unknown extension type: {md['EXTNAME']}")
187 stamp_parts.setdefault(md["EXTVER"], {})[md["EXTNAME"].lower()] = reader.read(dtype=dtype,
188 **kwargs)
189 if len(stamp_parts) != nStamps:
190 raise ValueError(
191 f"Number of stamps read ({len(stamp_parts)}) does not agree with the "
192 f"number of stamps recorded in the metadata ({nStamps})."
193 )
194 # construct stamps themselves
195 stamps = []
196 for k in range(nStamps):
197 # Need to increment by one since EXTVER starts at 1
198 maskedImage = masked_image_cls(**stamp_parts[k + 1])
199 archive_element = archive.get(archive_ids[k]) if has_archive else None
200 stamps.append(stamp_factory(maskedImage, metadata, k, archive_element))
201
202 return stamps, metadata
203
204
205@dataclass

◆ writeFits()

lsst.meas.algorithms.stamps.writeFits ( filename,
stamps,
metadata,
type_name,
write_mask,
write_variance,
write_archive = False )
Write a single FITS file containing all stamps.

Parameters
----------
filename : `str`
    A string indicating the output filename
stamps : iterable of `BaseStamp`
    An iterable of Stamp objects
metadata : `PropertyList`
    A collection of key, value metadata pairs to be
    written to the primary header
type_name : `str`
    Python type name of the StampsBase subclass to use
write_mask : `bool`
    Write the mask data to the output file?
write_variance : `bool`
    Write the variance data to the output file?
write_archive : `bool`, optional
    Write an archive to store Persistables along with each stamp?
    Default: ``False``.

Definition at line 40 of file stamps.py.

40def writeFits(filename, stamps, metadata, type_name, write_mask, write_variance, write_archive=False):
41 """Write a single FITS file containing all stamps.
42
43 Parameters
44 ----------
45 filename : `str`
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
52 type_name : `str`
53 Python type name of the StampsBase subclass to use
54 write_mask : `bool`
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?
60 Default: ``False``.
61 """
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
67 # Record version number in case of future code changes
68 metadata["VERSION"] = 1
69 # create primary HDU with global metadata
70 fitsFile = Fits(filename, "w")
71 fitsFile.createEmpty()
72 # Store Persistables in an OutputArchive and write it
73 if write_archive:
74 oa = OutputArchive()
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)
79 else:
80 fitsFile.writeMetadata(metadata)
81 fitsFile.closeFile()
82 # add all pixel data optionally writing mask and variance information
83 for i, stamp in enumerate(stamps):
84 metadata = PropertyList()
85 # EXTVER should be 1-based, the index from enumerate is 0-based
86 metadata.update({"EXTVER": i + 1, "EXTNAME": "IMAGE"})
87 stamp.stamp_im.getImage().writeFits(filename, metadata=metadata, mode="a")
88 if write_mask:
89 metadata = PropertyList()
90 metadata.update({"EXTVER": i + 1, "EXTNAME": "MASK"})
91 stamp.stamp_im.getMask().writeFits(filename, metadata=metadata, mode="a")
92 if write_variance:
93 metadata = PropertyList()
94 metadata.update({"EXTVER": i + 1, "EXTNAME": "VARIANCE"})
95 stamp.stamp_im.getVariance().writeFits(filename, metadata=metadata, mode="a")
96 return None
97
98