LSST Applications g042eb84c57+730a74494b,g04e9c324dd+8c5ae1fdc5,g134cb467dc+1f1e3e7524,g199a45376c+0ba108daf9,g1fd858c14a+fa7d31856b,g210f2d0738+f66ac109ec,g262e1987ae+83a3acc0e5,g29ae962dfc+d856a2cb1f,g2cef7863aa+aef1011c0b,g35bb328faa+8c5ae1fdc5,g3fd5ace14f+a1e0c9f713,g47891489e3+0d594cb711,g4d44eb3520+c57ec8f3ed,g4d7b6aa1c5+f66ac109ec,g53246c7159+8c5ae1fdc5,g56a1a4eaf3+fd7ad03fde,g64539dfbff+f66ac109ec,g67b6fd64d1+0d594cb711,g67fd3c3899+f66ac109ec,g6985122a63+0d594cb711,g74acd417e5+3098891321,g786e29fd12+668abc6043,g81db2e9a8d+98e2ab9f28,g87389fa792+8856018cbb,g89139ef638+0d594cb711,g8d7436a09f+80fda9ce03,g8ea07a8fe4+760ca7c3fc,g90f42f885a+033b1d468d,g97be763408+a8a29bda4b,g99822b682c+e3ec3c61f9,g9d5c6a246b+0d5dac0c3d,ga41d0fce20+9243b26dd2,gbf99507273+8c5ae1fdc5,gd7ef33dd92+0d594cb711,gdab6d2f7ff+3098891321,ge410e46f29+0d594cb711,geaed405ab2+c4bbc419c6,gf9a733ac38+8c5ae1fdc5,w.2025.38
LSST Data Management Base Package
Loading...
Searching...
No Matches
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 251 of file stamps.py.

251def _default_position():
252 # SpherePoint is nominally mutable in C++ so we must use a factory
253 # and return an entirely new SpherePoint each time a Stamps is created.
254 return SpherePoint(Angle(np.nan), Angle(np.nan))
255
256
257@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 100 of file stamps.py.

100def readFitsWithOptions(filename, stamp_factory, options):
101 """Read stamps from FITS file, allowing for only a subregion of the stamps
102 to be read.
103
104 Parameters
105 ----------
106 filename : `str`
107 A string indicating the file to read
108 stamp_factory : classmethod
109 A factory function defined on a dataclass for constructing
110 stamp objects a la `~lsst.meas.algorithm.Stamp`
111 options : `PropertyList` or `dict`
112 A collection of parameters. If it contains a bounding box
113 (``bbox`` key), or if certain other keys (``llcX``, ``llcY``,
114 ``width``, ``height``) are available for one to be constructed,
115 the bounding box is passed to the ``FitsReader`` in order to
116 return a sub-image.
117
118 Returns
119 -------
120 stamps : `list` of dataclass objects like `Stamp`, PropertyList
121 A tuple of a list of `Stamp`-like objects
122 metadata : `PropertyList`
123 The metadata
124
125 Notes
126 -----
127 The data are read using the data type expected by the
128 `~lsst.afw.image.MaskedImage` class attached to the `AbstractStamp`
129 dataclass associated with the factory method.
130 """
131 # extract necessary info from metadata
132 metadata = readMetadata(filename, hdu=0)
133 nStamps = metadata["N_STAMPS"]
134 has_archive = metadata["HAS_ARCHIVE"]
135 if has_archive:
136 archive_ids = metadata.getArray("ARCHIVE_IDS")
137 with Fits(filename, "r") as f:
138 nExtensions = f.countHdus()
139 # check if a bbox was provided
140 kwargs = {}
141 if options:
142 # gen3 API
143 if "bbox" in options.keys():
144 kwargs["bbox"] = options["bbox"]
145 # gen2 API
146 elif "llcX" in options.keys():
147 llcX = options["llcX"]
148 llcY = options["llcY"]
149 width = options["width"]
150 height = options["height"]
151 bbox = Box2I(Point2I(llcX, llcY), Extent2I(width, height))
152 kwargs["bbox"] = bbox
153 stamp_parts = {}
154
155 # Determine the dtype from the factory. This allows a Stamp class
156 # to be defined in terms of MaskedImageD or MaskedImageI without
157 # forcing everything to floats.
158 masked_image_cls = None
159 for stamp_field in fields(stamp_factory.__self__):
160 if issubclass(stamp_field.type, MaskedImage):
161 masked_image_cls = stamp_field.type
162 break
163 else:
164 raise RuntimeError("Stamp factory does not use MaskedImage.")
165 default_dtype = np.dtype(masked_image_cls.dtype)
166 variance_dtype = np.dtype(np.float32) # Variance is always the same type.
167
168 # We need to be careful because nExtensions includes the primary HDU.
169 stamp_metadata = []
170 for idx in range(nExtensions - 1):
171 dtype = None
172 _metadata = copy.copy(metadata)
173 md = readMetadata(filename, hdu=idx + 1)
174 _metadata.update(md)
175 stamp_metadata.append(_metadata)
176 # Skip binary tables that aren't images or archives.
177 if md["XTENSION"] == "BINTABLE" and not ("ZIMAGE" in md and md["ZIMAGE"]):
178 if md["EXTNAME"] != "ARCHIVE_INDEX":
179 continue
180 if md["EXTNAME"] in ("IMAGE", "VARIANCE"):
181 reader = ImageFitsReader(filename, hdu=idx + 1)
182 if md["EXTNAME"] == "VARIANCE":
183 dtype = variance_dtype
184 else:
185 dtype = default_dtype
186 elif md["EXTNAME"] == "MASK":
187 reader = MaskFitsReader(filename, hdu=idx + 1)
188 elif md["EXTNAME"] == "ARCHIVE_INDEX":
189 f.setHdu(idx + 1)
190 archive = InputArchive.readFits(f)
191 continue
192 elif md["EXTTYPE"] == "ARCHIVE_DATA":
193 continue
194 else:
195 raise ValueError(f"Unknown extension type: {md['EXTNAME']}")
196 stamp_parts.setdefault(md["EXTVER"], {})[md["EXTNAME"].lower()] = reader.read(dtype=dtype,
197 **kwargs)
198 if len(stamp_parts) != nStamps:
199 raise ValueError(
200 f"Number of stamps read ({len(stamp_parts)}) does not agree with the "
201 f"number of stamps recorded in the metadata ({nStamps})."
202 )
203 # construct stamps themselves
204 stamps = []
205 for k in range(nStamps):
206 # Need to increment by one since EXTVER starts at 1
207 maskedImage = masked_image_cls(**stamp_parts[k + 1])
208 archive_element = archive.get(archive_ids[k]) if has_archive else None
209 stamps.append(stamp_factory(maskedImage, stamp_metadata[k], k, archive_element))
210
211 return stamps, metadata
212
213
214@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 41 of file stamps.py.

41def writeFits(filename, stamps, metadata, type_name, write_mask, write_variance, write_archive=False):
42 """Write a single FITS file containing all stamps.
43
44 Parameters
45 ----------
46 filename : `str`
47 A string indicating the output filename
48 stamps : iterable of `BaseStamp`
49 An iterable of Stamp objects
50 metadata : `PropertyList`
51 A collection of key, value metadata pairs to be
52 written to the primary header
53 type_name : `str`
54 Python type name of the StampsBase subclass to use
55 write_mask : `bool`
56 Write the mask data to the output file?
57 write_variance : `bool`
58 Write the variance data to the output file?
59 write_archive : `bool`, optional
60 Write an archive to store Persistables along with each stamp?
61 Default: ``False``.
62 """
63 metadata["HAS_MASK"] = write_mask
64 metadata["HAS_VARIANCE"] = write_variance
65 metadata["HAS_ARCHIVE"] = write_archive
66 metadata["N_STAMPS"] = len(stamps)
67 metadata["STAMPCLS"] = type_name
68 # Record version number in case of future code changes
69 metadata["VERSION"] = 1
70 # create primary HDU with global metadata
71 fitsFile = Fits(filename, "w")
72 fitsFile.createEmpty()
73 # Store Persistables in an OutputArchive and write it
74 if write_archive:
75 oa = OutputArchive()
76 archive_ids = [oa.put(stamp.archive_element) for stamp in stamps]
77 metadata["ARCHIVE_IDS"] = archive_ids
78 fitsFile.writeMetadata(metadata)
79 oa.writeFits(fitsFile)
80 else:
81 fitsFile.writeMetadata(metadata)
82 fitsFile.closeFile()
83 # add all pixel data optionally writing mask and variance information
84 for i, stamp in enumerate(stamps):
85 metadata = PropertyList()
86 # EXTVER should be 1-based, the index from enumerate is 0-based
87 metadata.update({"EXTVER": i + 1, "EXTNAME": "IMAGE"})
88 stamp.stamp_im.getImage().writeFits(filename, metadata=metadata, mode="a")
89 if write_mask:
90 metadata = PropertyList()
91 metadata.update({"EXTVER": i + 1, "EXTNAME": "MASK"})
92 stamp.stamp_im.getMask().writeFits(filename, metadata=metadata, mode="a")
93 if write_variance:
94 metadata = PropertyList()
95 metadata.update({"EXTVER": i + 1, "EXTNAME": "VARIANCE"})
96 stamp.stamp_im.getVariance().writeFits(filename, metadata=metadata, mode="a")
97 return None
98
99