lsst.meas.base  13.0-20-g03c8adc+4
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Macros Groups Pages
baseMeasurement.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 #
3 # LSST Data Management System
4 # Copyright 2008-2016 AURA/LSST.
5 #
6 # This product includes software developed by the
7 # LSST Project (http://www.lsst.org/).
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 LSST License Statement and
20 # the GNU General Public License along with this program. If not,
21 # see <https://www.lsstcorp.org/LegalNotices/>.
22 #
23 """Base measurement task, which subclassed by the single frame and forced measurement tasks.
24 """
25 from lsst.log import Log
26 import lsst.pipe.base
27 import lsst.pex.config
28 
29 from .pluginRegistry import PluginMap
30 from .exceptions import FatalAlgorithmError, MeasurementError
31 from .pluginsBase import BasePluginConfig, BasePlugin
32 from .noiseReplacer import NoiseReplacerConfig
33 
34 __all__ = ("BaseMeasurementPluginConfig", "BaseMeasurementPlugin",
35  "BaseMeasurementConfig", "BaseMeasurementTask")
36 
37 # Exceptions that the measurement tasks should always propagate up to their callers
38 FATAL_EXCEPTIONS = (MemoryError, FatalAlgorithmError)
39 
40 
41 class BaseMeasurementPluginConfig(BasePluginConfig):
42  """!
43  Base config class for all measurement plugins
44 
45  Most derived classes will want to override setDefaults() in order to customize
46  the default exceutionOrder.
47 
48  A derived class whose corresponding Plugin class implements measureN() should
49  additionally add a bool doMeasureN field to replace the bool class attribute
50  defined here.
51  """
52 
53  doMeasure = lsst.pex.config.Field(dtype=bool, default=True,
54  doc="whether to run this plugin in single-object mode")
55 
56  doMeasureN = False # replace this class attribute with a Field if measureN-capable
57 
58 
59 class BaseMeasurementPlugin(BasePlugin):
60  '''
61  Base class for all measurement plugins
62 
63  This is class is a placeholder for future behavior which will be shared only between
64  measurement plugins and is implemented for symmetry with the measurement base plugin
65  configuration class
66  '''
67  pass
68 
69 
70 class SourceSlotConfig(lsst.pex.config.Config):
71  """!
72  Slot configuration which assigns a particular named plugin to each of a set of
73  slots. Each slot allows a type of measurement to be fetched from the SourceTable
74  without knowing which algorithm was used to produced the data.
75 
76  NOTE: the default algorithm for each slot must be registered, even if the default is not used.
77  """
78 
79  centroid = lsst.pex.config.Field(dtype=str, default="base_SdssCentroid", optional=True,
80  doc="the name of the centroiding algorithm used to set source x,y")
81  shape = lsst.pex.config.Field(dtype=str, default="base_SdssShape", optional=True,
82  doc="the name of the algorithm used to set source moments parameters")
83  apFlux = lsst.pex.config.Field(dtype=str, default="base_CircularApertureFlux_12_0", optional=True,
84  doc="the name of the algorithm used to set the source aperture flux slot")
85  modelFlux = lsst.pex.config.Field(dtype=str, default="base_GaussianFlux", optional=True,
86  doc="the name of the algorithm used to set the source model flux slot")
87  psfFlux = lsst.pex.config.Field(dtype=str, default="base_PsfFlux", optional=True,
88  doc="the name of the algorithm used to set the source psf flux slot")
89  instFlux = lsst.pex.config.Field(dtype=str, default="base_GaussianFlux", optional=True,
90  doc="the name of the algorithm used to set the source inst flux slot")
91  calibFlux = lsst.pex.config.Field(dtype=str, default="base_CircularApertureFlux_12_0", optional=True,
92  doc="the name of the flux measurement algorithm used for calibration")
93 
94  def setupSchema(self, schema):
95  """Convenience method to setup a Schema's slots according to the config definition.
96 
97  This is defined in the Config class to support use in unit tests without needing
98  to construct a Task object.
99  """
100  aliases = schema.getAliasMap()
101  if self.centroid is not None:
102  aliases.set("slot_Centroid", self.centroid)
103  if self.shape is not None:
104  aliases.set("slot_Shape", self.shape)
105  if self.apFlux is not None:
106  aliases.set("slot_ApFlux", self.apFlux)
107  if self.modelFlux is not None:
108  aliases.set("slot_ModelFlux", self.modelFlux)
109  if self.psfFlux is not None:
110  aliases.set("slot_PsfFlux", self.psfFlux)
111  if self.instFlux is not None:
112  aliases.set("slot_InstFlux", self.instFlux)
113  if self.calibFlux is not None:
114  aliases.set("slot_CalibFlux", self.calibFlux)
115 
116 
117 class BaseMeasurementConfig(lsst.pex.config.Config):
118  """!
119  Base config class for all measurement driver tasks.
120 
121  Subclasses should define the 'plugins' and 'undeblended' registries, e.g.:
122 
123  plugins = PluginBaseClass.registry.makeField(
124  multi=True,
125  default=[],
126  doc="Plugins to be run and their configuration"
127  )
128  undeblended = PluginBaseClass.registry.makeField(
129  multi=True,
130  default=[],
131  doc="Plugins to run on undeblended image"
132  )
133 
134  where PluginBaseClass is the appropriate base class of the plugin
135  (e.g., SingleFramePlugin or ForcedPlugin).
136  """
137 
138  slots = lsst.pex.config.ConfigField(
139  dtype=SourceSlotConfig,
140  doc="Mapping from algorithms to special aliases in Source."
141  )
142 
143  doReplaceWithNoise = lsst.pex.config.Field(
144  dtype=bool, default=True, optional=False,
145  doc='When measuring, replace other detected footprints with noise?')
146 
147  noiseReplacer = lsst.pex.config.ConfigField(
148  dtype=NoiseReplacerConfig,
149  doc="configuration that sets how to replace neighboring sources with noise"
150  )
151  undeblendedPrefix = lsst.pex.config.Field(
152  dtype=str, default="undeblended_",
153  doc="Prefix to give undeblended plugins"
154  )
155 
156  def validate(self):
157  lsst.pex.config.Config.validate(self)
158  if self.slots.centroid is not None and self.slots.centroid not in self.plugins.names:
159  raise ValueError("source centroid slot algorithm is not being run.")
160  if self.slots.shape is not None and self.slots.shape not in self.plugins.names:
161  raise ValueError("source shape slot algorithm '%s' is not being run." % self.slots.shape)
162  for slot in (self.slots.psfFlux, self.slots.apFlux, self.slots.modelFlux,
163  self.slots.instFlux, self.slots.calibFlux):
164  if slot is not None:
165  for name in self.plugins.names:
166  if len(name) <= len(slot) and name == slot[:len(name)]:
167  break
168  else:
169  raise ValueError("source flux slot algorithm '%s' is not being run." % slot)
170 
171 ## @addtogroup LSST_task_documentation
172 ## @{
173 ## @page baseMeasurementTask
174 ## BaseMeasurementTask @copybrief BaseMeasurementTask
175 ## @}
176 
177 
178 class BaseMeasurementTask(lsst.pipe.base.Task):
179  """!
180  Ultimate base class for all measurement tasks.
181 
182  This base class for SingleFrameMeasurementTask and ForcedMeasurementTask mostly exists to share
183  code between the two, and generally should not be used directly.
184  """
185 
186  ConfigClass = BaseMeasurementConfig
187  _DefaultName = "measurement"
188 
189  def __init__(self, algMetadata=None, **kwds):
190  """!
191  Constructor; only called by derived classes.
192 
193  @param[in] algMetadata An lsst.daf.base.PropertyList that will be filled with metadata
194  about the plugins being run. If None, an empty PropertyList will
195  be created.
196  @param[in] **kwds Additional arguments passed to lsst.pipe.base.Task.__init__.
197 
198  This attaches two public attributes to the class for use by derived classes and parent tasks:
199  - plugins: an empty PluginMap, which will eventually contain all active plugins that will by
200  invoked by the run() method (to be filled by subclasses). This should be considered read-only.
201  - algMetadata: a lsst.daf.base.PropertyList that will contain additional information about the
202  active plugins to be saved with the output catalog (to be filled by subclasses).
203  """
204  super(BaseMeasurementTask, self).__init__(**kwds)
205  self.plugins = PluginMap()
206  self.undeblendedPlugins = PluginMap()
207  if algMetadata is None:
208  algMetadata = lsst.daf.base.PropertyList()
209  self.algMetadata = algMetadata
210 
211  def getPluginLogName(self, pluginName):
212  return self.log.getName() + '.' + pluginName
213 
214  def initializePlugins(self, **kwds):
215  """Initialize the plugins (and slots) according to the configuration.
216 
217  Derived class constructors should call this method to fill the self.plugins
218  attribute and add correspond output fields and slot aliases to the output schema.
219 
220  In addition to the attributes added by BaseMeasurementTask.__init__, a self.schema
221  attribute holding the output schema must also be present before this method is called, .
222 
223  Keyword arguments are forwarded directly to plugin constructors, allowing derived
224  classes to use plugins with different signatures.
225  """
226  # Make a place at the beginning for the centroid plugin to run first (because it's an OrderedDict,
227  # adding an empty element in advance means it will get run first when it's reassigned to the
228  # actual Plugin).
229  if self.config.slots.centroid is not None:
230  self.plugins[self.config.slots.centroid] = None
231  # Init the plugins, sorted by execution order. At the same time add to the schema
232  for executionOrder, name, config, PluginClass in sorted(self.config.plugins.apply()):
233  # Pass logName to the plugin if the plugin is marked as using it
234  # The task will use this name to log plugin errors, regardless.
235  if hasattr(PluginClass, "hasLogName") and PluginClass.hasLogName:
236  self.plugins[name] = PluginClass(config, name, metadata=self.algMetadata,
237  logName=self.getPluginLogName(name), **kwds)
238  else:
239  self.plugins[name] = PluginClass(config, name, metadata=self.algMetadata, **kwds)
240 
241  # In rare circumstances (usually tests), the centroid slot not be coming from an algorithm,
242  # which means we'll have added something we don't want to the plugins map, and we should
243  # remove it.
244  if self.config.slots.centroid is not None and self.plugins[self.config.slots.centroid] is None:
245  del self.plugins[self.config.slots.centroid]
246  # Initialize the plugins to run on the undeblended image
247  for executionOrder, name, config, PluginClass in sorted(self.config.undeblended.apply()):
248  undeblendedName = self.config.undeblendedPrefix + name
249  self.undeblendedPlugins[name] = PluginClass(config, undeblendedName, metadata=self.algMetadata,
250  **kwds)
251 
252  def callMeasure(self, measRecord, *args, **kwds):
253  """!
254  Call the measure() method on all plugins, handling exceptions in a consistent way.
255 
256  @param[in,out] measRecord lsst.afw.table.SourceRecord that corresponds to the object being
257  measured, and where outputs should be written.
258  @param[in] *args Positional arguments forwarded to Plugin.measure()
259  @param[in] **kwds Keyword arguments. Two are handled locally:
260  - beginOrder: beginning execution order (inclusive): measurements with
261  executionOrder < beginOrder are not executed. None for no limit.
262  - endOrder: ending execution order (exclusive): measurements with
263  executionOrder >= endOrder are not executed. None for no limit.
264  the rest are forwarded to Plugin.measure()
265 
266  This method can be used with plugins that have different signatures; the only requirement is that
267  'measRecord' be the first argument. Subsequent positional arguments and keyword arguments are
268  forwarded directly to the plugin.
269 
270  This method should be considered "protected"; it is intended for use by derived classes, not users.
271  """
272  beginOrder = kwds.pop("beginOrder", None)
273  endOrder = kwds.pop("endOrder", None)
274  for plugin in self.plugins.iter():
275  if beginOrder is not None and plugin.getExecutionOrder() < beginOrder:
276  continue
277  if endOrder is not None and plugin.getExecutionOrder() >= endOrder:
278  break
279  self.doMeasurement(plugin, measRecord, *args, **kwds)
280 
281  def doMeasurement(self, plugin, measRecord, *args, **kwds):
282  """!
283  Call the measure() method on the nominated plugin, handling exceptions in a consistent way.
284 
285  @param[in] plugin Plugin that will measure
286  @param[in,out] measRecord lsst.afw.table.SourceRecord that corresponds to the object being
287  measured, and where outputs should be written.
288  @param[in] *args Positional arguments forwarded to plugin.measure()
289  @param[in] **kwds Keyword arguments forwarded to plugin.measure()
290 
291  This method can be used with plugins that have different signatures; the only requirement is that
292  the 'plugin' and 'measRecord' be the first two arguments. Subsequent positional arguments and
293  keyword arguments are forwarded directly to the plugin.
294 
295  This method should be considered "protected"; it is intended for use by derived classes, not users.
296  """
297  try:
298  plugin.measure(measRecord, *args, **kwds)
299  except FATAL_EXCEPTIONS:
300  raise
301  except MeasurementError as error:
302  lsst.log.Log.getLogger(self.getPluginLogName(plugin.name)).debug(
303  "MeasurementError in %s.measure on record %s: %s"
304  % (plugin.name, measRecord.getId(), error))
305  plugin.fail(measRecord, error)
306  except Exception as error:
307  lsst.log.Log.getLogger(self.getPluginLogName(plugin.name)).debug(
308  "Exception in %s.measure on record %s: %s"
309  % (plugin.name, measRecord.getId(), error))
310  plugin.fail(measRecord)
311 
312  def callMeasureN(self, measCat, *args, **kwds):
313  """!
314  Call the measureN() method on all plugins, handling exceptions in a consistent way.
315 
316  @param[in,out] measCat lsst.afw.table.SourceCatalog containing records for just
317  the source family to be measured, and where outputs should
318  be written.
319  @param[in] beginOrder beginning execution order (inclusive): measurements with
320  executionOrder < beginOrder are not executed. None for no limit.
321  @param[in] endOrder ending execution order (exclusive): measurements with
322  executionOrder >= endOrder are not executed. None for no limit.
323  @param[in] *args Positional arguments forwarded to Plugin.measure()
324  @param[in] **kwds Keyword arguments. Two are handled locally:
325  - beginOrder: beginning execution order (inclusive): measurements with
326  executionOrder < beginOrder are not executed. None for no limit.
327  - endOrder: ending execution order (exclusive): measurements with
328  executionOrder >= endOrder are not executed. None for no limit.
329  the rest are forwarded to Plugin.measure()
330 
331  This method can be used with plugins that have different signatures; the only requirement is that
332  'measRecord' be the first argument. Subsequent positional arguments and keyword arguments are
333  forwarded directly to the plugin.
334 
335  This method should be considered "protected"; it is intended for use by derived classes, not users.
336  """
337  beginOrder = kwds.pop("beginOrder", None)
338  endOrder = kwds.pop("endOrder", None)
339  for plugin in self.plugins.iterN():
340  if beginOrder is not None and plugin.getExecutionOrder() < beginOrder:
341  continue
342  if endOrder is not None and plugin.getExecutionOrder() >= endOrder:
343  break
344  self.doMeasurementN(plugin, measCat, *args, **kwds)
345 
346  def doMeasurementN(self, plugin, measCat, *args, **kwds):
347  """!
348  Call the measureN() method on the nominated plugin, handling exceptions in a consistent way.
349 
350  @param[in] plugin Plugin that will measure
351  @param[in,out] measCat lsst.afw.table.SourceCatalog containing records for just
352  the source family to be measured, and where outputs should
353  be written.
354  @param[in] *args Positional arguments forwarded to plugin.measureN()
355  @param[in] **kwds Keyword arguments forwarded to plugin.measureN()
356 
357  This method can be used with plugins that have different signatures; the only requirement is that
358  the 'plugin' and 'measCat' be the first two arguments. Subsequent positional arguments and
359  keyword arguments are forwarded directly to the plugin.
360 
361  This method should be considered "protected"; it is intended for use by derived classes, not users.
362  """
363  try:
364  plugin.measureN(measCat, *args, **kwds)
365  except FATAL_EXCEPTIONS:
366  raise
367 
368  except MeasurementError as error:
369  for measRecord in measCat:
370  lsst.log.Log.getLogger(self.getPluginLogName(plugin.name)).debug(
371  "MeasurementError in %s.measureN on records %s-%s: %s"
372  % (plugin.name, measCat[0].getId(), measCat[-1].getId(), error))
373  plugin.fail(measRecord, error)
374  except Exception as error:
375  for measRecord in measCat:
376  plugin.fail(measRecord)
377  lsst.log.Log.getLogger(self.getPluginLogName(plugin.name)).debug(
378  "Exception in %s.measureN on records %s-%s: %s"
379  % (plugin.name, measCat[0].getId(), measCat[-1].getId(), error))
Base config class for all measurement plugins.
def __init__
Constructor; only called by derived classes.
def callMeasure
Call the measure() method on all plugins, handling exceptions in a consistent way.
def doMeasurement
Call the measure() method on the nominated plugin, handling exceptions in a consistent way...
def doMeasurementN
Call the measureN() method on the nominated plugin, handling exceptions in a consistent way...
Ultimate base class for all measurement tasks.
Base config class for all measurement driver tasks.
def callMeasureN
Call the measureN() method on all plugins, handling exceptions in a consistent way.