Loading [MathJax]/extensions/tex2jax.js
LSST Applications g0000d66e7c+4a51730b0a,g0485b4d2cb+be65c9c1d7,g0fba68d861+eb108e5914,g1ec0fe41b4+3ea9d11450,g1fd858c14a+41d169aaf2,g2440f9efcc+8c5ae1fdc5,g35bb328faa+8c5ae1fdc5,g470b45d79c+bb7d8e732a,g4d2262a081+972b13e66a,g53246c7159+8c5ae1fdc5,g55585698de+c657de43f9,g56a49b3a55+7eddd92ad8,g60b5630c4e+c657de43f9,g67b6fd64d1+97cc007aa2,g78460c75b0+7e33a9eb6d,g786e29fd12+668abc6043,g7ac00fbb6c+088e1a4fa9,g8352419a5c+8c5ae1fdc5,g8852436030+3f3bba821f,g89139ef638+97cc007aa2,g94187f82dc+c657de43f9,g989de1cb63+97cc007aa2,g9d31334357+c657de43f9,g9f33ca652e+06d39d8afb,ga815be3f0b+8e7c4d07ad,gabe3b4be73+8856018cbb,gabf8522325+977d9fabaf,gb1101e3267+12c96a40b1,gb89ab40317+97cc007aa2,gc91f06edcd+2ffb87f22b,gcf25f946ba+3f3bba821f,gd6cbbdb0b4+1cc2750d2e,gde0f65d7ad+4ad7118dbf,ge278dab8ac+6b863515ed,ge410e46f29+97cc007aa2,gf35d7ec915+97dd712d81,gf5e32f922b+8c5ae1fdc5,gf67bdafdda+97cc007aa2,w.2025.19
LSST Data Management Base Package
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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 246 of file stamps.py.

246def _default_position():
247 # SpherePoint is nominally mutable in C++ so we must use a factory
248 # and return an entirely new SpherePoint each time a Stamps is created.
249 return SpherePoint(Angle(np.nan), Angle(np.nan))
250
251
252@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 # Skip binary tables that aren't images or archives.
172 if md["XTENSION"] == "BINTABLE" and not ("ZIMAGE" in md and md["ZIMAGE"]):
173 if md["EXTNAME"] != "ARCHIVE_INDEX":
174 continue
175 if md["EXTNAME"] in ("IMAGE", "VARIANCE"):
176 reader = ImageFitsReader(filename, hdu=idx + 1)
177 if md["EXTNAME"] == "VARIANCE":
178 dtype = variance_dtype
179 else:
180 dtype = default_dtype
181 elif md["EXTNAME"] == "MASK":
182 reader = MaskFitsReader(filename, hdu=idx + 1)
183 elif md["EXTNAME"] == "ARCHIVE_INDEX":
184 f.setHdu(idx + 1)
185 archive = InputArchive.readFits(f)
186 continue
187 elif md["EXTTYPE"] == "ARCHIVE_DATA":
188 continue
189 else:
190 raise ValueError(f"Unknown extension type: {md['EXTNAME']}")
191 stamp_parts.setdefault(md["EXTVER"], {})[md["EXTNAME"].lower()] = reader.read(dtype=dtype,
192 **kwargs)
193 if len(stamp_parts) != nStamps:
194 raise ValueError(
195 f"Number of stamps read ({len(stamp_parts)}) does not agree with the "
196 f"number of stamps recorded in the metadata ({nStamps})."
197 )
198 # construct stamps themselves
199 stamps = []
200 for k in range(nStamps):
201 # Need to increment by one since EXTVER starts at 1
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))
205
206 return stamps, metadata
207
208
209@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