LSST Applications g0b6bd0c080+a72a5dd7e6,g1182afd7b4+2a019aa3bb,g17e5ecfddb+2b8207f7de,g1d67935e3f+06cf436103,g38293774b4+ac198e9f13,g396055baef+6a2097e274,g3b44f30a73+6611e0205b,g480783c3b1+98f8679e14,g48ccf36440+89c08d0516,g4b93dc025c+98f8679e14,g5c4744a4d9+a302e8c7f0,g613e996a0d+e1c447f2e0,g6c8d09e9e7+25247a063c,g7271f0639c+98f8679e14,g7a9cd813b8+124095ede6,g9d27549199+a302e8c7f0,ga1cf026fa3+ac198e9f13,ga32aa97882+7403ac30ac,ga786bb30fb+7a139211af,gaa63f70f4e+9994eb9896,gabf319e997+ade567573c,gba47b54d5d+94dc90c3ea,gbec6a3398f+06cf436103,gc6308e37c7+07dd123edb,gc655b1545f+ade567573c,gcc9029db3c+ab229f5caf,gd01420fc67+06cf436103,gd877ba84e5+06cf436103,gdb4cecd868+6f279b5b48,ge2d134c3d5+cc4dbb2e3f,ge448b5faa6+86d1ceac1d,gecc7e12556+98f8679e14,gf3ee170dca+25247a063c,gf4ac96e456+ade567573c,gf9f5ea5b4d+ac198e9f13,gff490e6085+8c2580be5c,w.2022.27
LSST Data Management Base Package
sfm.py
Go to the documentation of this file.
1# This file is part of meas_base.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
21
22r"""Base classes for single-frame measurement plugins and the associated task.
23
24In single-frame measurement, we assume that detection and probably deblending
25have already been run on the same frame, so a `~lsst.afw.table.SourceCatalog`
26has already been created with `lsst.afw.detection.Footprint`\ s (which may be
27"heavy" — that is, include pixel data). Measurements are generally recorded in
28the coordinate system of the image being measured (and all slot-eligible
29fields must be), but non-slot fields may be recorded in other coordinate
30systems if necessary to avoid information loss (this should, of course, be
31indicated in the field documentation).
32"""
33
34import lsst.pex.config
35from lsst.utils.logging import PeriodicLogger
36from lsst.utils.timer import timeMethod
37
38from .pluginRegistry import PluginRegistry
39from .baseMeasurement import (BaseMeasurementPluginConfig, BaseMeasurementPlugin,
40 BaseMeasurementConfig, BaseMeasurementTask)
41from .noiseReplacer import NoiseReplacer, DummyNoiseReplacer
42
43__all__ = ("SingleFramePluginConfig", "SingleFramePlugin",
44 "SingleFrameMeasurementConfig", "SingleFrameMeasurementTask")
45
46
48 """Base class for single-frame plugin configuration classes.
49 """
50 pass
51
52
54 """Base class for single-frame measurement plugin.
55
56 Parameters
57 ----------
58 config : `SingleFramePlugin.ConfigClass`
59 Configuration for this plugin.
60 name : `str`
61 The string with which the plugin was registered.
62 schema : `lsst.afw.table.Schema`
63 The schema for the source table . New fields are added here to
64 hold measurements produced by this plugin.
65 metadata : `lsst.daf.base.PropertySet`
66 Plugin metadata that will be attached to the output catalog
67 logName : `str`, optional
68 Name to use when logging errors.
69
70 Notes
71 -----
72 New plugins can be created in Python by inheriting directly from this
73 class and implementing the `measure`, `fail` (from `BasePlugin`), and
74 optionally `__init__` and `measureN` methods. Plugins can also be defined
75 in C++ via the `WrappedSingleFramePlugin` class.
76 """
77
78 registry = PluginRegistry(SingleFramePluginConfig)
79 """Registry of subclasses of `SingleFramePlugin` (`PluginRegistry`).
80 """
81
82 ConfigClass = SingleFramePluginConfig
83
84 def __init__(self, config, name, schema, metadata, logName=None, **kwds):
85 BaseMeasurementPlugin.__init__(self, config, name, logName=logName)
86
87 def measure(self, measRecord, exposure):
88 """Measure the properties of a source on a single image.
89
90 The image may be from a single epoch, or it may be a coadd.
91
92 Parameters
93 ----------
94 measRecord : `lsst.afw.table.SourceRecord`
95 Record describing the object being measured. Previously-measured
96 quantities may be retrieved from here, and it will be updated
97 in-place tih the outputs of this plugin.
98 exposure : `lsst.afw.image.ExposureF`
99 The pixel data to be measured, together with the associated PSF,
100 WCS, etc. All other sources in the image should have been replaced
101 by noise according to deblender outputs.
102 """
103 raise NotImplementedError()
104
105 def measureN(self, measCat, exposure):
106 """Measure the properties of blended sources on a single image.
107
108 This operates on all members of a blend family at once. The image may
109 be from a single epoch, or it may be a coadd.
110
111 Parameters
112 ----------
114 Catalog describing the objects (and only those objects) being
115 measured. Previously-measured quantities will be retrieved from
116 here, and it will be updated in-place with the outputs of this
117 plugin.
118 exposure : `lsst.afw.image.ExposureF`
119 The pixel data to be measured, together with the associated PSF,
120 WCS, etc. All other sources in the image should have been replaced
121 by noise according to deblender outputs.
122
123 Notes
124 -----
125 Derived classes that do not implement ``measureN`` should just inherit
126 this disabled version. Derived classes that do implement ``measureN``
127 should additionally add a bool doMeasureN config field to their config
128 class to signal that measureN-mode is available.
129 """
130 raise NotImplementedError()
131
132
134 """Config class for single frame measurement driver task.
135 """
136
137 plugins = SingleFramePlugin.registry.makeField(
138 multi=True,
139 default=["base_PixelFlags",
140 "base_SdssCentroid",
141 "base_NaiveCentroid",
142 "base_SdssShape",
143 "base_GaussianFlux",
144 "base_PsfFlux",
145 "base_CircularApertureFlux",
146 "base_SkyCoord",
147 "base_Variance",
148 "base_Blendedness",
149 "base_LocalBackground",
150 ],
151 doc="Plugins to be run and their configuration"
152 )
153 algorithms = property(lambda self: self.pluginsplugins, doc="backwards-compatibility alias for plugins")
154 undeblended = SingleFramePlugin.registry.makeField(
155 multi=True,
156 default=[],
157 doc="Plugins to run on undeblended image"
158 )
159 loggingInterval = lsst.pex.config.Field(
160 dtype=int,
161 default=600,
162 doc="Interval (in seconds) to log messages (at VERBOSE level) while running measurement plugins.",
163 deprecated="This field is no longer used and will be removed in v25.",
164 )
165
166
168 """A subtask for measuring the properties of sources on a single exposure.
169
170 Parameters
171 ----------
172 schema : `lsst.afw.table.Schema`
173 Schema of the output resultant catalog. Will be updated to provide
174 fields to accept the outputs of plugins which will be executed by this
175 task.
176 algMetadata : `lsst.daf.base.PropertyList`, optional
177 Used to record metadaa about algorithm execution. An empty
178 `lsst.daf.base.PropertyList` will be created if `None`.
179 **kwds
180 Keyword arguments forwarded to `BaseMeasurementTask`.
181 """
182
183 ConfigClass = SingleFrameMeasurementConfig
184
185 NOISE_SEED_MULTIPLIER = "NOISE_SEED_MULTIPLIER"
186 """Name by which the noise seed multiplier is recorded in metadata ('str').
187 """
188
189 NOISE_SOURCE = "NOISE_SOURCE"
190 """Name by which the noise source is recorded in metadata ('str').
191 """
192
193 NOISE_OFFSET = "NOISE_OFFSET"
194 """Name by which the noise offset is recorded in metadata ('str').
195 """
196
197 NOISE_EXPOSURE_ID = "NOISE_EXPOSURE_ID"
198 """Name by which the noise exposire ID is recorded in metadata ('str').
199 """
200
201 def __init__(self, schema, algMetadata=None, **kwds):
202 super(SingleFrameMeasurementTask, self).__init__(algMetadata=algMetadata, **kwds)
203 self.schemaschema = schema
204 self.config.slots.setupSchema(self.schemaschema)
205 self.initializePluginsinitializePlugins(schema=self.schemaschema)
206
207 # Check to see if blendedness is one of the plugins
208 if 'base_Blendedness' in self.pluginsplugins:
209 self.doBlendednessdoBlendedness = True
210 self.blendPluginblendPlugin = self.pluginsplugins['base_Blendedness']
211 else:
212 self.doBlendednessdoBlendedness = False
213
214 @timeMethod
215 def run(self, measCat, exposure, noiseImage=None, exposureId=None, beginOrder=None, endOrder=None):
216 r"""Run single frame measurement over an exposure and source catalog.
217
218 Parameters
219 ----------
221 Catalog to be filled with the results of measurement. Must contain
222 all the `lsst.afw.table.SourceRecord`\ s to be measured (with
223 `lsst.afw.detection.Footprint`\ s attached), and have a schema
224 that is a superset of ``self.schemaschema``.
225 exposure : `lsst.afw.image.ExposureF`
226 Image containing the pixel data to be measured together with
227 associated PSF, WCS, etc.
228 noiseImage : `lsst.afw.image.ImageF`, optional
229 Can be used to specify the a predictable noise replacement field
230 for testing purposes.
231 exposureId : `int`, optional
232 Unique exposure identifier used to calculate the random number
233 generator seed during noise replacement.
234 beginOrder : `float`, optional
235 Start execution order (inclusive): measurements with
236 ``executionOrder < beginOrder`` are not executed. `None` for no
237 limit.
238 endOrder : `float`, optional
239 Final execution order (exclusive): measurements with
240 ``executionOrder >= endOrder`` are not executed. `None` for no
241 limit.
242 """
243 assert measCat.getSchema().contains(self.schemaschema)
244 footprints = {measRecord.getId(): (measRecord.getParent(), measRecord.getFootprint())
245 for measRecord in measCat}
246
247 # noiseReplacer is used to fill the footprints with noise and save
248 # heavy footprints of the source pixels so that they can be restored
249 # one at a time for measurement. After the NoiseReplacer is
250 # constructed, all pixels in the exposure.getMaskedImage() which
251 # belong to objects in measCat will be replaced with noise
252
253 if self.config.doReplaceWithNoise:
254 noiseReplacer = NoiseReplacer(self.config.noiseReplacer, exposure, footprints,
255 noiseImage=noiseImage, log=self.log, exposureId=exposureId)
256 algMetadata = measCat.getMetadata()
257 if algMetadata is not None:
258 algMetadata.addInt(self.NOISE_SEED_MULTIPLIERNOISE_SEED_MULTIPLIER, self.config.noiseReplacer.noiseSeedMultiplier)
259 algMetadata.addString(self.NOISE_SOURCENOISE_SOURCE, self.config.noiseReplacer.noiseSource)
260 algMetadata.addDouble(self.NOISE_OFFSETNOISE_OFFSET, self.config.noiseReplacer.noiseOffset)
261 if exposureId is not None:
262 algMetadata.addLong(self.NOISE_EXPOSURE_IDNOISE_EXPOSURE_ID, exposureId)
263 else:
264 noiseReplacer = DummyNoiseReplacer()
265
266 self.runPluginsrunPlugins(noiseReplacer, measCat, exposure, beginOrder, endOrder)
267
268 def runPlugins(self, noiseReplacer, measCat, exposure, beginOrder=None, endOrder=None):
269 r"""Call the configured measument plugins on an image.
270
271 Parameters
272 ----------
273 noiseReplacer : `NoiseReplacer`
274 Used to fill sources not being measured with noise.
276 Catalog to be filled with the results of measurement. Must contain
277 all the `lsst.afw.table.SourceRecord`\ s to be measured (with
278 `lsst.afw.detection.Footprint`\ s attached), and have a schema
279 that is a superset of ``self.schemaschema``.
280 exposure : `lsst.afw.image.ExposureF`
281 Image containing the pixel data to be measured together with
282 associated PSF, WCS, etc.
283 beginOrder : `float`, optional
284 Start execution order (inclusive): measurements with
285 ``executionOrder < beginOrder`` are not executed. `None` for no
286 limit.
287 endOrder : `float`, optional
288 Final execution order (exclusive): measurements with
289 ``executionOrder >= endOrder`` are not executed. `None` for no
290 limit.
291 """
292 # First, create a catalog of all parentless sources. Loop through all
293 # the parent sources, first processing the children, then the parent.
294 measParentCat = measCat.getChildren(0)
295
296 nMeasCat = len(measCat)
297 nMeasParentCat = len(measParentCat)
298 self.log.info("Measuring %d source%s (%d parent%s, %d child%s) ",
299 nMeasCat, ("" if nMeasCat == 1 else "s"),
300 nMeasParentCat, ("" if nMeasParentCat == 1 else "s"),
301 nMeasCat - nMeasParentCat, ("" if nMeasCat - nMeasParentCat == 1 else "ren"))
302
303 # Wrap the task logger into a period logger
304 periodicLog = PeriodicLogger(self.log)
305
306 childrenIter = measCat.getChildren([measParentRecord.getId() for measParentRecord in measParentCat])
307 for parentIdx, (measParentRecord, measChildCat) in enumerate(zip(measParentCat, childrenIter)):
308 # first get all the children of this parent, insert footprint in
309 # turn, and measure
310 # TODO: skip this loop if there are no plugins configured for
311 # single-object mode
312 for measChildRecord in measChildCat:
313 noiseReplacer.insertSource(measChildRecord.getId())
314 self.callMeasurecallMeasure(measChildRecord, exposure, beginOrder=beginOrder, endOrder=endOrder)
315
316 if self.doBlendednessdoBlendedness:
317 self.blendPluginblendPlugin.cpp.measureChildPixels(exposure.getMaskedImage(), measChildRecord)
318
319 noiseReplacer.removeSource(measChildRecord.getId())
320
321 # Then insert the parent footprint, and measure that
322 noiseReplacer.insertSource(measParentRecord.getId())
323 self.callMeasurecallMeasure(measParentRecord, exposure, beginOrder=beginOrder, endOrder=endOrder)
324
325 if self.doBlendednessdoBlendedness:
326 self.blendPluginblendPlugin.cpp.measureChildPixels(exposure.getMaskedImage(), measParentRecord)
327
328 # Finally, process both parent and child set through measureN
329 self.callMeasureNcallMeasureN(measParentCat[parentIdx:parentIdx+1], exposure,
330 beginOrder=beginOrder, endOrder=endOrder)
331 self.callMeasureNcallMeasureN(measChildCat, exposure, beginOrder=beginOrder, endOrder=endOrder)
332 noiseReplacer.removeSource(measParentRecord.getId())
333 # Log a message if it has been a while since the last log.
334 periodicLog.log("Measurement complete for %d parents (and their children) out of %d",
335 parentIdx + 1, nMeasParentCat)
336
337 # When done, restore the exposure to its original state
338 noiseReplacer.end()
339
340 # Undeblended plugins only fire if we're running everything
341 if endOrder is None:
342 for sourceIndex, source in enumerate(measCat):
343 for plugin in self.undeblendedPluginsundeblendedPlugins.iter():
344 self.doMeasurementdoMeasurement(plugin, source, exposure)
345 # Log a message if it has been a while since the last log.
346 periodicLog.log("Undeblended measurement complete for %d sources out of %d",
347 sourceIndex + 1, nMeasCat)
348
349 # Now we loop over all of the sources one more time to compute the
350 # blendedness metrics
351 if self.doBlendednessdoBlendedness:
352 for source in measCat:
353 self.blendPluginblendPlugin.cpp.measureParentPixels(exposure.getMaskedImage(), source)
354
355 def measure(self, measCat, exposure):
356 """Backwards-compatibility alias for `run`.
357 """
358 self.runrun(measCat, exposure)
table::Key< int > to
Class to describe the properties of a detected object from an image.
Definition: Footprint.h:63
Defines the fields and offsets for a table.
Definition: Schema.h:51
Record class that contains measurements made on a single exposure.
Definition: Source.h:78
Class for storing ordered metadata with comments.
Definition: PropertyList.h:68
Class for storing generic metadata.
Definition: PropertySet.h:66
def doMeasurement(self, plugin, measRecord, *args, **kwds)
def callMeasure(self, measRecord, *args, **kwds)
def callMeasureN(self, measCat, *args, **kwds)
def measure(self, measCat, exposure)
Definition: sfm.py:355
def __init__(self, schema, algMetadata=None, **kwds)
Definition: sfm.py:201
def runPlugins(self, noiseReplacer, measCat, exposure, beginOrder=None, endOrder=None)
Definition: sfm.py:268
def run(self, measCat, exposure, noiseImage=None, exposureId=None, beginOrder=None, endOrder=None)
Definition: sfm.py:215
def measureN(self, measCat, exposure)
Definition: sfm.py:105
def __init__(self, config, name, schema, metadata, logName=None, **kwds)
Definition: sfm.py:84
def measure(self, measRecord, exposure)
Definition: sfm.py:87