LSST Applications g0f08755f38+9c285cab97,g1635faa6d4+13f3999e92,g1653933729+a8ce1bb630,g1a0ca8cf93+bf6eb00ceb,g28da252d5a+0829b12dee,g29321ee8c0+5700dc9eac,g2bbee38e9b+9634bc57db,g2bc492864f+9634bc57db,g2cdde0e794+c2c89b37c4,g3156d2b45e+41e33cbcdc,g347aa1857d+9634bc57db,g35bb328faa+a8ce1bb630,g3a166c0a6a+9634bc57db,g3e281a1b8c+9f2c4e2fc3,g414038480c+077ccc18e7,g41af890bb2+fde0dd39b6,g5fbc88fb19+17cd334064,g781aacb6e4+a8ce1bb630,g80478fca09+55a9465950,g82479be7b0+d730eedb7d,g858d7b2824+9c285cab97,g9125e01d80+a8ce1bb630,g9726552aa6+10f999ec6a,ga5288a1d22+2a84bb7594,gacf8899fa4+c69c5206e8,gae0086650b+a8ce1bb630,gb58c049af0+d64f4d3760,gc28159a63d+9634bc57db,gcf0d15dbbd+4b7d09cae4,gda3e153d99+9c285cab97,gda6a2b7d83+4b7d09cae4,gdaeeff99f8+1711a396fd,ge2409df99d+5e831397f4,ge79ae78c31+9634bc57db,gf0baf85859+147a0692ba,gf3967379c6+41c94011de,gf3fb38a9a8+8f07a9901b,gfb92a5be7c+9c285cab97,w.2024.46
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 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