lsst.meas.base  15.0-5-g993f083+3
tests.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 #
3 # LSST Data Management System
4 # Copyright 2008-2015 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 <http://www.lsstcorp.org/LegalNotices/>.
22 #
23 
24 import numpy as np
25 
26 import lsst.afw.table
27 import lsst.afw.image
28 import lsst.afw.detection
29 import lsst.afw.geom
31 
32 from .sfm import SingleFrameMeasurementTask
33 from .forcedMeasurement import ForcedMeasurementTask
34 from . import CentroidResultKey
35 
36 __all__ = ("BlendContext", "TestDataset", "AlgorithmTestCase", "TransformTestCase",
37  "SingleFramePluginTransformSetupHelper", "ForcedPluginTransformSetupHelper",
38  "FluxTransformTestCase", "CentroidTransformTestCase")
39 
40 
42  """!
43  A Python context manager used to add multiple overlapping sources along with a parent source
44  that represents all of them together.
45 
46  This is used as the return value for TestDataset.addBlend(), and this is the only way it should
47  be used. The only public method is addChild().
48  """
49 
50  def __init__(self, owner):
51  self.owner = owner
52  self.parentRecord = self.owner.catalog.addNew()
53  self.parentImage = lsst.afw.image.ImageF(self.owner.exposure.getBBox())
54  self.children = []
55 
56  def __enter__(self):
57  # BlendContext is its own context manager, so we just return self.
58  return self
59 
60  def addChild(self, flux, centroid, shape=None):
61  """!
62  Add a child source to the blend, and return the truth catalog record that corresponds to it.
63 
64  @param[in] flux Total flux of the source to be added.
65  @param[in] centroid Position of the source to be added (lsst.afw.geom.Point2D).
66  @param[in] shape 2nd moments of the source before PSF convolution
67  (lsst.afw.geom.Quadrupole). Note that the truth catalog
68  records post-convolution moments)
69  """
70  record, image = self.owner.addSource(flux, centroid, shape)
71  record.set(self.owner.keys["parent"], self.parentRecord.getId())
72  self.parentImage += image
73  self.children.append((record, image))
74  return record
75 
76  def __exit__(self, type_, value, tb):
77  # We're not using the context manager for any kind of exception safety or guarantees;
78  # we just want the nice "with" statement syntax.
79  if type_ is not None: # exception was raised; just skip all this and let it propagate
80  return
81  # On exit, we need to compute and set the truth values for the parent object.
82  self.parentRecord.set(self.owner.keys["nChild"], len(self.children))
83  # Compute flux from sum of component fluxes
84  flux = 0.0
85  for record, image in self.children:
86  flux += record.get(self.owner.keys["flux"])
87  self.parentRecord.set(self.owner.keys["flux"], flux)
88  # Compute centroid from flux-weighted mean of component centroids
89  x = 0.0
90  y = 0.0
91  for record, image in self.children:
92  w = record.get(self.owner.keys["flux"])/flux
93  x += record.get(self.owner.keys["centroid"].getX())*w
94  y += record.get(self.owner.keys["centroid"].getY())*w
95  self.parentRecord.set(self.owner.keys["centroid"], lsst.afw.geom.Point2D(x, y))
96  # Compute shape from flux-weighted mean of offset component shapes
97  xx = 0.0
98  yy = 0.0
99  xy = 0.0
100  for record, image in self.children:
101  w = record.get(self.owner.keys["flux"])/flux
102  dx = record.get(self.owner.keys["centroid"].getX()) - x
103  dy = record.get(self.owner.keys["centroid"].getY()) - y
104  xx += (record.get(self.owner.keys["shape"].getIxx()) + dx**2)*w
105  yy += (record.get(self.owner.keys["shape"].getIyy()) + dy**2)*w
106  xy += (record.get(self.owner.keys["shape"].getIxy()) + dx*dy)*w
107  self.parentRecord.set(self.owner.keys["shape"], lsst.afw.geom.Quadrupole(xx, yy, xy))
108  # Run detection on the parent image to get the parent Footprint.
109  self.owner._installFootprint(self.parentRecord, self.parentImage)
110  # Create perfect HeavyFootprints for all children; these will need to be modified later to account
111  # for the noise we'll add to the image.
112  deblend = lsst.afw.image.MaskedImageF(self.owner.exposure.getMaskedImage(), True)
113  for record, image in self.children:
114  deblend.getImage().getArray()[:, :] = image.getArray()
115  heavyFootprint = lsst.afw.detection.HeavyFootprintF(self.parentRecord.getFootprint(), deblend)
116  record.setFootprint(heavyFootprint)
117 
118 
120  """!
121  A simulated dataset consisting of a test image and an associated truth catalog.
122 
123  TestDataset creates an idealized image made of pure Gaussians (including a Gaussian PSF),
124  with simple noise and idealized Footprints/HeavyFootprints that simulated the outputs
125  of detection and deblending. Multiple noise realizations can be created from the same
126  underlying sources, allowing uncertainty estimates to be verified via Monte Carlo.
127 
128  Typical usage:
129  @code
130  bbox = lsst.afw.geom.Box2I(lsst.afw.geom.Point2I(0,0), lsst.afw.geom.Point2I(100, 100))
131  dataset = TestDataset(bbox)
132  dataset.addSource(flux=1E5, centroid=lsst.afw.geom.Point2D(25, 26))
133  dataset.addSource(flux=2E5, centroid=lsst.afw.geom.Point2D(75, 24),
134  shape=lsst.afw.geom.Quadrupole(8, 7, 2))
135  with dataset.addBlend() as family:
136  family.addChild(flux=2E5, centroid=lsst.afw.geom.Point2D(50, 72))
137  family.addChild(flux=1.5E5, centroid=lsst.afw.geom.Point2D(51, 74))
138  exposure, catalog = dataset.realize(noise=100.0, schema=TestDataset.makeMinimalSchema())
139  @endcode
140  """
141 
142  @classmethod
144  """Return the minimal schema needed to hold truth catalog fields.
145 
146  When TestDataset.realize() is called, the schema must include at least these fields.
147  Usually it will include additional fields for measurement algorithm outputs, allowing
148  the same catalog to be used for both truth values (the fields from the minimal schema)
149  and the measurements.
150  """
151  if not hasattr(cls, "_schema"):
153  cls.keys = {}
154  cls.keys["parent"] = schema.find("parent").key
155  cls.keys["nChild"] = schema.addField("deblend_nChild", type=np.int32)
156  cls.keys["flux"] = schema.addField("truth_flux", type=np.float64, doc="true flux", units="count")
157  cls.keys["centroid"] = lsst.afw.table.Point2DKey.addFields(
158  schema, "truth", "true simulated centroid", "pixel"
159  )
160  cls.keys["centroid_sigma"] = lsst.afw.table.CovarianceMatrix2fKey.addFields(
161  schema, "truth", ['x', 'y'], "pixel"
162  )
163  cls.keys["centroid_flag"] = schema.addField("truth_flag", type="Flag",
164  doc="set if the object is a star")
166  schema, "truth", "true shape after PSF convolution", lsst.afw.table.CoordinateType.PIXEL
167  )
168  cls.keys["isStar"] = schema.addField("truth_isStar", type="Flag",
169  doc="set if the object is a star")
170  schema.getAliasMap().set("slot_Shape", "truth")
171  schema.getAliasMap().set("slot_Centroid", "truth")
172  schema.getAliasMap().set("slot_ModelFlux", "truth")
173  schema.getCitizen().markPersistent()
174  cls._schema = schema
175  schema = lsst.afw.table.Schema(cls._schema)
176  schema.disconnectAliases()
177  return schema
178 
179  @staticmethod
180  def makePerturbedWcs(oldWcs, minScaleFactor=1.2, maxScaleFactor=1.5,
181  minRotation=None, maxRotation=None,
182  minRefShift=None, maxRefShift=None,
183  minPixShift=2.0, maxPixShift=4.0, randomSeed=1):
184  """!
185  Create a new undistorted TAN WCS that is similar but not identical to another, with random
186  scaling, rotation, and offset (in both pixel position and reference position).
187 
188  The maximum and minimum arguments are interpreted as absolute values for a split
189  range that covers both positive and negative values (as this method is used
190  in testing, it is typically most important to avoid perturbations near zero).
191  Scale factors are treated somewhat differently: the actual scale factor is chosen between
192  minScaleFactor and maxScaleFactor OR (1/maxScaleFactor) and (1/minScaleFactor).
193 
194  The default range for rotation is 30-60 degrees, and the default range for reference shift
195  is 0.5-1.0 arcseconds (these cannot be safely included directly as default values because Angle
196  objects are mutable).
197 
198  The random number generator is primed with the seed given. If ``None``, a seed is
199  automatically chosen.
200  """
201  random_state = np.random.RandomState(randomSeed)
202  if minRotation is None:
203  minRotation = 30.0*lsst.afw.geom.degrees
204  if maxRotation is None:
205  maxRotation = 60.0*lsst.afw.geom.degrees
206  if minRefShift is None:
207  minRefShift = 0.5*lsst.afw.geom.arcseconds
208  if maxRefShift is None:
209  maxRefShift = 1.0*lsst.afw.geom.arcseconds
210 
211  def splitRandom(min1, max1, min2=None, max2=None):
212  if min2 is None:
213  min2 = -max1
214  if max2 is None:
215  max2 = -min1
216  if random_state.uniform() > 0.5:
217  return float(random_state.uniform(min1, max1))
218  else:
219  return float(random_state.uniform(min2, max2))
220  # Generate random perturbations
221  scaleFactor = splitRandom(minScaleFactor, maxScaleFactor, 1.0/maxScaleFactor, 1.0/minScaleFactor)
222  rotation = splitRandom(minRotation.asRadians(), maxRotation.asRadians())*lsst.afw.geom.radians
223  refShiftRa = splitRandom(minRefShift.asRadians(), maxRefShift.asRadians())*lsst.afw.geom.radians
224  refShiftDec = splitRandom(minRefShift.asRadians(), maxRefShift.asRadians())*lsst.afw.geom.radians
225  pixShiftX = splitRandom(minPixShift, maxPixShift)
226  pixShiftY = splitRandom(minPixShift, maxPixShift)
227  # Compute new CD matrix
228  oldTransform = lsst.afw.geom.LinearTransform(oldWcs.getCdMatrix())
229  rTransform = lsst.afw.geom.LinearTransform.makeRotation(rotation)
230  sTransform = lsst.afw.geom.LinearTransform.makeScaling(scaleFactor)
231  newTransform = oldTransform*rTransform*sTransform
232  matrix = newTransform.getMatrix()
233  # Compute new coordinate reference pixel (CRVAL)
234  oldSkyOrigin = oldWcs.getSkyOrigin()
235  newSkyOrigin = lsst.afw.geom.SpherePoint(oldSkyOrigin.getRa() + refShiftRa,
236  oldSkyOrigin.getDec() + refShiftDec)
237  # Compute new pixel reference pixel (CRPIX)
238  oldPixOrigin = oldWcs.getPixelOrigin()
239  newPixOrigin = lsst.afw.geom.Point2D(oldPixOrigin.getX() + pixShiftX,
240  oldPixOrigin.getY() + pixShiftY)
241  return lsst.afw.geom.makeSkyWcs(crpix=newPixOrigin, crval=newSkyOrigin, cdMatrix=matrix)
242 
243  @staticmethod
244  def makeEmptyExposure(bbox, wcs=None, crval=None, cdelt=None, psfSigma=2.0, psfDim=17, fluxMag0=1E12):
245  """!
246  Create an Exposure, with a Calib, Wcs, and Psf, but no pixel values set.
247 
248  @param[in] bbox Bounding box of the image (image coordinates) as returned by makeCatalog.
249  @param[in] wcs New Wcs for the exposure (created from crval and cdelt if None).
250  @param[in] crval afw.geom.SpherePoint: ICRS center of the TAN WCS attached to the image.
251  @param[in] cdelt afw.geom.Angle: pixel scale of the image
252  @param[in] psfSigma Radius (sigma) of the Gaussian PSF attached to the image
253  @param[in] psfDim Width and height of the image's Gaussian PSF attached to the image
254  @param[in] fluxMag0 Flux at magnitude zero (in e-) used to set the Calib of the exposure.
255  """
256  if wcs is None:
257  if crval is None:
258  crval = lsst.afw.geom.SpherePoint(45.0, 45.0, lsst.afw.geom.degrees)
259  if cdelt is None:
260  cdelt = 0.2*lsst.afw.geom.arcseconds
261  crpix = lsst.afw.geom.Box2D(bbox).getCenter()
262  wcs = lsst.afw.geom.makeSkyWcs(crpix=crpix, crval=crval,
263  cdMatrix=lsst.afw.geom.makeCdMatrix(scale=cdelt))
264  exposure = lsst.afw.image.ExposureF(bbox)
265  psf = lsst.afw.detection.GaussianPsf(psfDim, psfDim, psfSigma)
266  calib = lsst.afw.image.Calib()
267  calib.setFluxMag0(fluxMag0)
268  exposure.setWcs(wcs)
269  exposure.setPsf(psf)
270  exposure.setCalib(calib)
271  return exposure
272 
273  @staticmethod
274  def drawGaussian(bbox, flux, ellipse):
275  """!
276  Create an image of an elliptical Gaussian.
277 
278  @param[in,out] bbox Bounding box of image to create.
279  @param[in] flux Total flux of the Gaussian (normalized analytically, not using pixel
280  values)
281  @param[in] ellipse lsst.afw.geom.Ellipse holding the centroid and shape.
282  """
283  x, y = np.meshgrid(np.arange(bbox.getBeginX(), bbox.getEndX()),
284  np.arange(bbox.getBeginY(), bbox.getEndY()))
285  t = ellipse.getGridTransform()
286  xt = t[t.XX] * x + t[t.XY] * y + t[t.X]
287  yt = t[t.YX] * x + t[t.YY] * y + t[t.Y]
288  image = lsst.afw.image.ImageF(bbox)
289  image.getArray()[:, :] = np.exp(-0.5*(xt**2 + yt**2))*flux/(2.0*ellipse.getCore().getArea())
290  return image
291 
292  def __init__(self, bbox, threshold=10.0, exposure=None, **kwds):
293  """!
294  Initialize the dataset.
295 
296  @param[in] bbox Bounding box of the test image.
297  @param[in] threshold Threshold absolute value used to determine footprints for
298  simulated sources. This thresholding will be applied before noise is
299  actually added to images (or before the noise level is even known), so
300  this will necessarily produce somewhat artificial footprints.
301  @param[in] exposure lsst.afw.image.ExposureF test sources should be added to. Ownership should
302  be considered transferred from the caller to the TestDataset.
303  Must have a Gaussian Psf for truth catalog shapes to be exact.
304  @param[in] **kwds Keyword arguments forwarded to makeEmptyExposure if exposure is None.
305  """
306  if exposure is None:
307  exposure = self.makeEmptyExposure(bbox, **kwds)
308  self.threshold = lsst.afw.detection.Threshold(threshold, lsst.afw.detection.Threshold.VALUE)
309  self.exposure = exposure
310  self.psfShape = self.exposure.getPsf().computeShape()
311  self.schema = self.makeMinimalSchema()
313 
314  def _installFootprint(self, record, image):
315  """Create a Footprint for a simulated source and add it to its truth catalog record.
316  """
317  # Run detection on the single-source image
318  fpSet = lsst.afw.detection.FootprintSet(image, self.threshold)
319  # the call below to the FootprintSet ctor is actually a grow operation
320  fpSet = lsst.afw.detection.FootprintSet(fpSet, int(self.psfShape.getDeterminantRadius() + 1.0), True)
321  # Update the full exposure's mask plane to indicate the detection
322  fpSet.setMask(self.exposure.getMaskedImage().getMask(), "DETECTED")
323  # Attach the new footprint to the exposure
324  if len(fpSet.getFootprints()) > 1:
325  raise RuntimeError("Threshold value results in multiple Footprints for a single object")
326  if len(fpSet.getFootprints()) == 0:
327  raise RuntimeError("Threshold value results in zero Footprints for object")
328  record.setFootprint(fpSet.getFootprints()[0])
329 
330  def addSource(self, flux, centroid, shape=None):
331  """!
332  Add a source to the simulation
333 
334  @param[in] flux Total flux of the source to be added.
335  @param[in] centroid Position of the source to be added (lsst.afw.geom.Point2D).
336  @param[in] shape 2nd moments of the source before PSF convolution
337  (lsst.afw.geom.Quadrupole). Note that the truth catalog
338  records post-convolution moments). If None, a point source
339  will be added.
340 
341  @return a truth catalog record and single-source image corresponding to the new source.
342  """
343  # Create and set the truth catalog fields
344  record = self.catalog.addNew()
345  record.set(self.keys["flux"], flux)
346  record.set(self.keys["centroid"], centroid)
347  covariance = np.random.normal(0, 0.1, 4).reshape(2, 2)
348  covariance[0, 1] = covariance[1, 0] # CovarianceMatrixKey assumes symmetric x_y_Cov
349  record.set(self.keys["centroid_sigma"], covariance.astype(np.float32))
350  if shape is None:
351  record.set(self.keys["isStar"], True)
352  fullShape = self.psfShape
353  else:
354  record.set(self.keys["isStar"], False)
355  fullShape = shape.convolve(self.psfShape)
356  record.set(self.keys["shape"], fullShape)
357  # Create an image containing just this source
358  image = self.drawGaussian(self.exposure.getBBox(), flux,
359  lsst.afw.geom.Ellipse(fullShape, centroid))
360  # Generate a footprint for this source
361  self._installFootprint(record, image)
362  # Actually add the source to the full exposure
363  self.exposure.getMaskedImage().getImage().getArray()[:, :] += image.getArray()
364  return record, image
365 
366  def addBlend(self):
367  """!
368  Return a context manager that allows a blend of multiple sources to be added.
369 
370  Example:
371  @code
372  d = TestDataset(...)
373  with d.addBlend() as b:
374  b.addChild(flux1, centroid1)
375  b.addChild(flux2, centroid2, shape2)
376  @endcode
377 
378  Note that nothing stops you from creating overlapping sources just using the addSource() method,
379  but addBlend() is necesssary to create a parent object and deblended HeavyFootprints of the type
380  produced by the detection and deblending pipelines.
381  """
382  return BlendContext(self)
383 
384  def transform(self, wcs, **kwds):
385  """!
386  Create a copy of the dataset transformed to a new WCS, with new Psf and Calib.
387 
388  @param[in] wcs Wcs for the new dataset.
389  @param[in] **kwds Additional keyword arguments passed on to makeEmptyExposure. If not
390  specified, these revert to the defaults for makeEmptyExposure, not the
391  values in the current dataset.
392  """
393  bboxD = lsst.afw.geom.Box2D()
394  xyt = lsst.afw.geom.makeWcsPairTransform(self.exposure.getWcs(), wcs)
395  for corner in lsst.afw.geom.Box2D(self.exposure.getBBox()).getCorners():
396  bboxD.include(xyt.applyForward(lsst.afw.geom.Point2D(corner)))
397  bboxI = lsst.afw.geom.Box2I(bboxD)
398  result = TestDataset(bbox=bboxI, wcs=wcs, **kwds)
399  oldCalib = self.exposure.getCalib()
400  newCalib = result.exposure.getCalib()
401  oldPsfShape = self.exposure.getPsf().computeShape()
402  for record in self.catalog:
403  if record.get(self.keys["nChild"]):
404  raise NotImplementedError("Transforming blended sources in TestDatasets is not supported")
405  magnitude = oldCalib.getMagnitude(record.get(self.keys["flux"]))
406  newFlux = newCalib.getFlux(magnitude)
407  oldCentroid = record.get(self.keys["centroid"])
408  newCentroid = xyt.applyForward(oldCentroid)
409  if record.get(self.keys["isStar"]):
410  newDeconvolvedShape = None
411  else:
412  affine = lsst.afw.geom.linearizeTransform(xyt, oldCentroid)
413  oldFullShape = record.get(self.keys["shape"])
414  oldDeconvolvedShape = lsst.afw.geom.Quadrupole(
415  oldFullShape.getIxx() - oldPsfShape.getIxx(),
416  oldFullShape.getIyy() - oldPsfShape.getIyy(),
417  oldFullShape.getIxy() - oldPsfShape.getIxy(),
418  False
419  )
420  newDeconvolvedShape = oldDeconvolvedShape.transform(affine.getLinear())
421  result.addSource(newFlux, newCentroid, newDeconvolvedShape)
422  return result
423 
424  def realize(self, noise, schema, randomSeed=1):
425  """!
426  Create a simulated with noise and a simulated post-detection catalog with (Heavy)Footprints.
427 
428  @param[in] noise Standard deviation of noise to be added to the exposure. The noise will be
429  Gaussian and constant, appropriate for the sky-limited regime.
430  @param[in] schema Schema of the new catalog to be created. Must start with self.schema (i.e.
431  schema.contains(self.schema) must be True), but typically contains fields for
432  already-configured measurement algorithms as well.
433  @param[in] randomSeed Seed for the random number generator. If None, a seed is chosen automatically.
434 
435  @return a tuple of (exposure, catalog)
436  """
437  random_state = np.random.RandomState(randomSeed)
438  assert schema.contains(self.schema)
439  mapper = lsst.afw.table.SchemaMapper(self.schema)
440  mapper.addMinimalSchema(self.schema, True)
441  exposure = self.exposure.clone()
442  exposure.getMaskedImage().getVariance().getArray()[:, :] = noise**2
443  exposure.getMaskedImage().getImage().getArray()[:, :] \
444  += random_state.randn(exposure.getHeight(), exposure.getWidth())*noise
445  catalog = lsst.afw.table.SourceCatalog(schema)
446  catalog.extend(self.catalog, mapper=mapper)
447  # Loop over sources and generate new HeavyFootprints that divide up the noisy pixels, not the
448  # ideal no-noise pixels.
449  for record in catalog:
450  # parent objects have non-Heavy Footprints, which don't need to be updated after adding noise.
451  if record.getParent() == 0:
452  continue
453  # get flattened arrays that correspond to the no-noise and noisy parent images
454  parent = catalog.find(record.getParent())
455  footprint = parent.getFootprint()
456  parentFluxArrayNoNoise = np.zeros(footprint.getArea(), dtype=np.float32)
457  footprint.spans.flatten(parentFluxArrayNoNoise,
458  self.exposure.getMaskedImage().getImage().getArray(),
459  self.exposure.getXY0())
460  parentFluxArrayNoisy = np.zeros(footprint.getArea(), dtype=np.float32)
461  footprint.spans.flatten(parentFluxArrayNoisy,
462  exposure.getMaskedImage().getImage().getArray(),
463  exposure.getXY0())
464  oldHeavy = record.getFootprint()
465  fraction = (oldHeavy.getImageArray() / parentFluxArrayNoNoise)
466  # n.b. this isn't a copy ctor - it's a copy from a vanilla Footprint, so it doesn't copy
467  # the arrays we don't want to change, and hence we have to do that ourselves below.
468  newHeavy = lsst.afw.detection.HeavyFootprintF(oldHeavy)
469  newHeavy.getImageArray()[:] = parentFluxArrayNoisy*fraction
470  newHeavy.getMaskArray()[:] = oldHeavy.getMaskArray()
471  newHeavy.getVarianceArray()[:] = oldHeavy.getVarianceArray()
472  record.setFootprint(newHeavy)
473  return exposure, catalog
474 
475 
477 
478  def makeSingleFrameMeasurementConfig(self, plugin=None, dependencies=()):
479  """Convenience function to create a Config instance for SingleFrameMeasurementTask
480 
481  The plugin and its dependencies will be the only plugins run, while the Centroid, Shape,
482  and ModelFlux slots will be set to the truth fields generated by the TestDataset class.
483  """
484  config = SingleFrameMeasurementTask.ConfigClass()
485  config.slots.centroid = "truth"
486  config.slots.shape = "truth"
487  config.slots.modelFlux = None
488  config.slots.apFlux = None
489  config.slots.psfFlux = None
490  config.slots.instFlux = None
491  config.slots.calibFlux = None
492  config.plugins.names = (plugin,) + tuple(dependencies)
493  return config
494 
495  def makeSingleFrameMeasurementTask(self, plugin=None, dependencies=(), config=None, schema=None,
496  algMetadata=None):
497  """Convenience function to create a SingleFrameMeasurementTask with a simple configuration.
498  """
499  if config is None:
500  if plugin is None:
501  raise ValueError("Either plugin or config argument must not be None")
502  config = self.makeSingleFrameMeasurementConfig(plugin=plugin, dependencies=dependencies)
503  if schema is None:
504  schema = TestDataset.makeMinimalSchema()
505  # Clear all aliases so only those defined by config are set.
506  schema.setAliasMap(None)
507  if algMetadata is None:
508  algMetadata = lsst.daf.base.PropertyList()
509  return SingleFrameMeasurementTask(schema=schema, algMetadata=algMetadata, config=config)
510 
511  def makeForcedMeasurementConfig(self, plugin=None, dependencies=()):
512  """Convenience function to create a Config instance for ForcedMeasurementTask
513 
514  In addition to the plugins specified in the plugin and dependencies arguments,
515  the TransformedCentroid and TransformedShape plugins will be run and used as the
516  Centroid and Shape slots; these simply transform the reference catalog centroid
517  and shape to the measurement coordinate system.
518  """
519  config = ForcedMeasurementTask.ConfigClass()
520  config.slots.centroid = "base_TransformedCentroid"
521  config.slots.shape = "base_TransformedShape"
522  config.slots.modelFlux = None
523  config.slots.apFlux = None
524  config.slots.psfFlux = None
525  config.slots.instFlux = None
526  config.plugins.names = (plugin,) + tuple(dependencies) + ("base_TransformedCentroid",
527  "base_TransformedShape")
528  return config
529 
530  def makeForcedMeasurementTask(self, plugin=None, dependencies=(), config=None, refSchema=None,
531  algMetadata=None):
532  """Convenience function to create a ForcedMeasurementTask with a simple configuration.
533  """
534  if config is None:
535  if plugin is None:
536  raise ValueError("Either plugin or config argument must not be None")
537  config = self.makeForcedMeasurementConfig(plugin=plugin, dependencies=dependencies)
538  if refSchema is None:
539  refSchema = TestDataset.makeMinimalSchema()
540  if algMetadata is None:
541  algMetadata = lsst.daf.base.PropertyList()
542  return ForcedMeasurementTask(refSchema=refSchema, algMetadata=algMetadata, config=config)
543 
544 
546  """!
547  Base class for testing measurement transformations.
548 
549  We test both that the transform itself operates successfully (fluxes are
550  converted to magnitudes, flags are propagated properly) and that the
551  transform is registered as the default for the appropriate measurement
552  algorithms.
553 
554  In the simple case of one-measurement-per-transformation, the developer
555  need not directly write any tests themselves: simply customizing the class
556  variables is all that is required. More complex measurements (e.g.
557  multiple aperture fluxes) require extra effort.
558  """
559  # The name used for the measurement algorithm; determines the names of the
560  # fields in the resulting catalog. This default should generally be fine,
561  # but subclasses can override if required.
562  name = "MeasurementTransformTest"
563 
564  # These should be customized by subclassing.
565  controlClass = None
566  algorithmClass = None
567  transformClass = None
568 
569  # Flags which may be set by the algorithm being tested. Can be customized
570  # in subclasses.
571  flagNames = ("flag",)
572 
573  # The plugin being tested should be registered under these names for
574  # single frame and forced measurement. Should be customized by
575  # subclassing.
576  singleFramePlugins = ()
577  forcedPlugins = ()
578 
579  def setUp(self):
581  self.calexp = TestDataset.makeEmptyExposure(bbox)
582  self._setupTransform()
583 
584  def tearDown(self):
585  del self.calexp
586  del self.inputCat
587  del self.mapper
588  del self.transform
589  del self.outputCat
590 
591  def _populateCatalog(self, baseNames):
592  records = []
593  for flagValue in (True, False):
594  records.append(self.inputCat.addNew())
595  for baseName in baseNames:
596  for flagName in self.flagNames:
597  if records[-1].schema.join(baseName, flagName) in records[-1].schema:
598  records[-1].set(records[-1].schema.join(baseName, flagName), flagValue)
599  self._setFieldsInRecords(records, baseName)
600 
601  def _checkOutput(self, baseNames):
602  for inSrc, outSrc in zip(self.inputCat, self.outputCat):
603  for baseName in baseNames:
604  self._compareFieldsInRecords(inSrc, outSrc, baseName)
605  for flagName in self.flagNames:
606  keyName = outSrc.schema.join(baseName, flagName)
607  if keyName in inSrc.schema:
608  self.assertEqual(outSrc.get(keyName), inSrc.get(keyName))
609  else:
610  self.assertFalse(keyName in outSrc.schema)
611 
612  def _runTransform(self, doExtend=True):
613  if doExtend:
614  self.outputCat.extend(self.inputCat, mapper=self.mapper)
615  self.transform(self.inputCat, self.outputCat, self.calexp.getWcs(), self.calexp.getCalib())
616 
617  def testTransform(self, baseNames=None):
618  """
619  Test the operation of the transformation on a catalog containing random data.
620 
621  We check that:
622 
623  * An appropriate exception is raised on an attempt to transform between catalogs with different
624  numbers of rows;
625  * Otherwise, all appropriate conversions are properly appled and that flags have been propagated.
626 
627  The `baseNames` argument requires some explanation. This should be an iterable of the leading parts of
628  the field names for each measurement; that is, everything that appears before `_flux`, `_flag`, etc.
629  In the simple case of a single measurement per plugin, this is simply equal to `self.name` (thus
630  measurements are stored as `self.name + "_flux"`, etc). More generally, the developer may specify
631  whatever iterable they require. For example, to handle multiple apertures, we could have
632  `(self.name + "_0", self.name + "_1", ...)`.
633 
634  @param[in] baseNames Iterable of the initial parts of measurement field names.
635  """
636  baseNames = baseNames or [self.name]
637  self._populateCatalog(baseNames)
638  self.assertRaises(lsst.pex.exceptions.LengthError, self._runTransform, False)
639  self._runTransform()
640  self._checkOutput(baseNames)
641 
642  def _checkRegisteredTransform(self, registry, name):
643  # If this is a Python-based transform, we can compare directly; if
644  # it's wrapped C++, we need to compare the wrapped class.
645  self.assertEqual(registry[name].PluginClass.getTransformClass(), self.transformClass)
646 
647  def testRegistration(self):
648  """
649  Test that the transformation is appropriately registered with the relevant measurement algorithms.
650  """
651  for pluginName in self.singleFramePlugins:
652  self._checkRegisteredTransform(lsst.meas.base.SingleFramePlugin.registry, pluginName)
653  for pluginName in self.forcedPlugins:
654  self._checkRegisteredTransform(lsst.meas.base.ForcedPlugin.registry, pluginName)
655 
656 
658 
659  def _setupTransform(self):
660  self.control = self.controlClass()
662  # Trick algorithms that depend on the slot centroid or alias into thinking they've been defined;
663  # it doesn't matter for this test since we won't actually use the plugins for anything besides
664  # defining the schema.
665  inputSchema.getAliasMap().set("slot_Centroid", "dummy")
666  inputSchema.getAliasMap().set("slot_Shape", "dummy")
667  self.algorithmClass(self.control, self.name, inputSchema)
668  inputSchema.getAliasMap().erase("slot_Centroid")
669  inputSchema.getAliasMap().erase("slot_Shape")
672  self.transform = self.transformClass(self.control, self.name, self.mapper)
673  self.outputCat = lsst.afw.table.BaseCatalog(self.mapper.getOutputSchema())
674 
675 
677 
678  def _setupTransform(self):
679  self.control = self.controlClass()
682  # Trick algorithms that depend on the slot centroid or alias into thinking they've been defined;
683  # it doesn't matter for this test since we won't actually use the plugins for anything besides
684  # defining the schema.
685  inputMapper.editOutputSchema().getAliasMap().set("slot_Centroid", "dummy")
686  inputMapper.editOutputSchema().getAliasMap().set("slot_Shape", "dummy")
687  self.algorithmClass(self.control, self.name, inputMapper, lsst.daf.base.PropertyList())
688  inputMapper.editOutputSchema().getAliasMap().erase("slot_Centroid")
689  inputMapper.editOutputSchema().getAliasMap().erase("slot_Shape")
690  self.inputCat = lsst.afw.table.SourceCatalog(inputMapper.getOutputSchema())
691  self.mapper = lsst.afw.table.SchemaMapper(inputMapper.getOutputSchema())
692  self.transform = self.transformClass(self.control, self.name, self.mapper)
693  self.outputCat = lsst.afw.table.BaseCatalog(self.mapper.getOutputSchema())
694 
695 
697 
698  def _setFieldsInRecords(self, records, name):
699  for record in records:
700  record[record.schema.join(name, 'flux')] = np.random.random()
701  record[record.schema.join(name, 'fluxSigma')] = np.random.random()
702 
703  # Negative fluxes should be converted to NaNs.
704  assert len(records) > 1
705  records[0][record.schema.join(name, 'flux')] = -1
706 
707  def _compareFieldsInRecords(self, inSrc, outSrc, name):
708  fluxName, fluxSigmaName = inSrc.schema.join(name, 'flux'), inSrc.schema.join(name, 'fluxSigma')
709  if inSrc[fluxName] > 0:
710  mag, magErr = self.calexp.getCalib().getMagnitude(inSrc[fluxName], inSrc[fluxSigmaName])
711  self.assertEqual(outSrc[outSrc.schema.join(name, 'mag')], mag)
712  self.assertEqual(outSrc[outSrc.schema.join(name, 'magErr')], magErr)
713  else:
714  self.assertTrue(np.isnan(outSrc[outSrc.schema.join(name, 'mag')]))
715  self.assertTrue(np.isnan(outSrc[outSrc.schema.join(name, 'magErr')]))
716 
717 
719 
720  def _setFieldsInRecords(self, records, name):
721  for record in records:
722  record[record.schema.join(name, 'x')] = np.random.random()
723  record[record.schema.join(name, 'y')] = np.random.random()
724  # Some algorithms set no errors; some set only sigma on x & y; some provide
725  # a full covariance matrix. Set only those which exist in the schema.
726  for fieldSuffix in ('xSigma', 'ySigma', 'x_y_Cov'):
727  fieldName = record.schema.join(name, fieldSuffix)
728  if fieldName in record.schema:
729  record[fieldName] = np.random.random()
730 
731  def _compareFieldsInRecords(self, inSrc, outSrc, name):
732  centroidResultKey = CentroidResultKey(inSrc.schema[self.name])
733  centroidResult = centroidResultKey.get(inSrc)
734 
735  coord = lsst.afw.table.CoordKey(outSrc.schema[self.name]).get(outSrc)
736  coordTruth = self.calexp.getWcs().pixelToSky(centroidResult.getCentroid())
737  self.assertEqual(coordTruth, coord)
738 
739  # If the centroid has an associated uncertainty matrix, the coordinate
740  # must have one too, and vice versa.
741  try:
742  coordErr = lsst.afw.table.CovarianceMatrix2fKey(outSrc.schema[self.name],
743  ["ra", "dec"]).get(outSrc)
745  self.assertFalse(centroidResultKey.getCentroidErr().isValid())
746  else:
747  transform = self.calexp.getWcs().linearizePixelToSky(coordTruth, lsst.afw.geom.radians)
748  coordErrTruth = np.dot(np.dot(transform.getLinear().getMatrix(),
749  centroidResult.getCentroidErr()),
750  transform.getLinear().getMatrix().transpose())
751  np.testing.assert_array_almost_equal(np.array(coordErrTruth), coordErr)
def _runTransform(self, doExtend=True)
Definition: tests.py:612
def makeSingleFrameMeasurementConfig(self, plugin=None, dependencies=())
Definition: tests.py:478
def transform(self, wcs, kwds)
Create a copy of the dataset transformed to a new WCS, with new Psf and Calib.
Definition: tests.py:384
def __init__(self, bbox, threshold=10.0, exposure=None, kwds)
Initialize the dataset.
Definition: tests.py:292
def _checkOutput(self, baseNames)
Definition: tests.py:601
A subtask for measuring the properties of sources on a single exposure, using an existing "reference"...
A subtask for measuring the properties of sources on a single exposure.
Definition: sfm.py:152
def addBlend(self)
Return a context manager that allows a blend of multiple sources to be added.
Definition: tests.py:366
def makeEmptyExposure(bbox, wcs=None, crval=None, cdelt=None, psfSigma=2.0, psfDim=17, fluxMag0=1E12)
Create an Exposure, with a Calib, Wcs, and Psf, but no pixel values set.
Definition: tests.py:244
static LinearTransform makeScaling(double s)
def makeSingleFrameMeasurementTask(self, plugin=None, dependencies=(), config=None, schema=None, algMetadata=None)
Definition: tests.py:496
def realize(self, noise, schema, randomSeed=1)
Create a simulated with noise and a simulated post-detection catalog with (Heavy)Footprints.
Definition: tests.py:424
AffineTransform linearizeTransform(TransformPoint2ToPoint2 const &original, Point2D const &inPoint)
def makePerturbedWcs(oldWcs, minScaleFactor=1.2, maxScaleFactor=1.5, minRotation=None, maxRotation=None, minRefShift=None, maxRefShift=None, minPixShift=2.0, maxPixShift=4.0, randomSeed=1)
Create a new undistorted TAN WCS that is similar but not identical to another, with random scaling...
Definition: tests.py:183
def __init__(self, owner)
Definition: tests.py:50
def testTransform(self, baseNames=None)
Definition: tests.py:617
def drawGaussian(bbox, flux, ellipse)
Create an image of an elliptical Gaussian.
Definition: tests.py:274
static LinearTransform makeRotation(Angle t)
def _installFootprint(self, record, image)
Definition: tests.py:314
static QuadrupoleKey addFields(Schema &schema, std::string const &name, std::string const &doc, CoordinateType coordType=CoordinateType::PIXEL)
def _checkRegisteredTransform(self, registry, name)
Definition: tests.py:642
def _populateCatalog(self, baseNames)
Definition: tests.py:591
def addSource(self, flux, centroid, shape=None)
Add a source to the simulation.
Definition: tests.py:330
static Schema makeMinimalSchema()
A simulated dataset consisting of a test image and an associated truth catalog.
Definition: tests.py:119
def makeForcedMeasurementTask(self, plugin=None, dependencies=(), config=None, refSchema=None, algMetadata=None)
Definition: tests.py:531
std::shared_ptr< TransformPoint2ToPoint2 > makeWcsPairTransform(SkyWcs const &src, SkyWcs const &dst)
std::shared_ptr< SkyWcs > makeSkyWcs(Point2D const &crpix, SpherePoint const &crval, Eigen::Matrix2d const &cdMatrix, std::string const &projection="TAN")
def addChild(self, flux, centroid, shape=None)
Add a child source to the blend, and return the truth catalog record that corresponds to it...
Definition: tests.py:60
Eigen::Matrix2d makeCdMatrix(Angle const &scale, Angle const &orientation=0 *degrees, bool flipX=false)
Base class for testing measurement transformations.
Definition: tests.py:545
def __exit__(self, type_, value, tb)
Definition: tests.py:76
def makeForcedMeasurementConfig(self, plugin=None, dependencies=())
Definition: tests.py:511
A Python context manager used to add multiple overlapping sources along with a parent source that rep...
Definition: tests.py:41