LSSTApplications  11.0-13-gbb96280,12.1.rc1,12.1.rc1+1,12.1.rc1+2,12.1.rc1+5,12.1.rc1+8,12.1.rc1-1-g06d7636+1,12.1.rc1-1-g253890b+5,12.1.rc1-1-g3d31b68+7,12.1.rc1-1-g3db6b75+1,12.1.rc1-1-g5c1385a+3,12.1.rc1-1-g83b2247,12.1.rc1-1-g90cb4cf+6,12.1.rc1-1-g91da24b+3,12.1.rc1-2-g3521f8a,12.1.rc1-2-g39433dd+4,12.1.rc1-2-g486411b+2,12.1.rc1-2-g4c2be76,12.1.rc1-2-gc9c0491,12.1.rc1-2-gda2cd4f+6,12.1.rc1-3-g3391c73+2,12.1.rc1-3-g8c1bd6c+1,12.1.rc1-3-gcf4b6cb+2,12.1.rc1-4-g057223e+1,12.1.rc1-4-g19ed13b+2,12.1.rc1-4-g30492a7
LSSTDataManagementBasePackage
astrometry.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2008-2016 AURA/LSST.
4 #
5 # This product includes software developed by the
6 # LSST Project (http://www.lsst.org/).
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the LSST License Statement and
19 # the GNU General Public License along with this program. If not,
20 # see <https://www.lsstcorp.org/LegalNotices/>.
21 #
22 from __future__ import absolute_import, division, print_function
23 from builtins import range
24 
25 from lsst.afw.image.utils import getDistortedWcs
26 import lsst.afw.geom as afwGeom
27 import lsst.afw.math as afwMath
28 import lsst.pex.config as pexConfig
29 import lsst.pipe.base as pipeBase
30 from .matchOptimisticB import MatchOptimisticBTask
31 from .fitTanSipWcs import FitTanSipWcsTask
32 from .display import displayAstrometry
33 from .astromLib import makeMatchStatistics
34 from .createMatchMetadata import createMatchMetadata
35 
36 
37 class AstrometryConfig(pexConfig.Config):
38  matcher = pexConfig.ConfigurableField(
39  target=MatchOptimisticBTask,
40  doc="reference object/source matcher",
41  )
42  wcsFitter = pexConfig.ConfigurableField(
43  target=FitTanSipWcsTask,
44  doc="WCS fitter",
45  )
46  forceKnownWcs = pexConfig.Field(
47  dtype=bool,
48  doc="If True then load reference objects and match sources but do not fit a WCS; " +
49  " this simply controls whether 'run' calls 'solve' or 'loadAndMatch'",
50  default=False,
51  )
52  maxIter = pexConfig.RangeField(
53  doc="maximum number of iterations of match sources and fit WCS" +
54  "ignored if not fitting a WCS",
55  dtype=int,
56  default=3,
57  min=1,
58  )
59  matchDistanceSigma = pexConfig.RangeField(
60  doc="the maximum match distance is set to "
61  " mean_match_distance + matchDistanceSigma*std_dev_match_distance; " +
62  "ignored if not fitting a WCS",
63  dtype=float,
64  default=2,
65  min=0,
66  )
67  minMatchDistanceArcSec = pexConfig.RangeField(
68  doc="the match distance below which further iteration is pointless (arcsec); "
69  "ignored if not fitting a WCS",
70  dtype=float,
71  default=0.001,
72  min=0,
73  )
74 
75 # The following block adds links to this task from the Task Documentation page.
76 ## \addtogroup LSST_task_documentation
77 ## \{
78 ## \page measAstrom_astrometryTask
79 ## \ref AstrometryTask_ "AstrometryTask"
80 ## Match an input source catalog with objects from a reference catalog and solve for the WCS
81 ## \}
82 
83 
84 class AstrometryTask(pipeBase.Task):
85  """!Match an input source catalog with objects from a reference catalog and solve for the WCS
86 
87  @anchor AstrometryTask_
88 
89  @section meas_astrom_astrometry_Contents Contents
90 
91  - @ref meas_astrom_astrometry_Purpose
92  - @ref meas_astrom_astrometry_Initialize
93  - @ref meas_astrom_astrometry_IO
94  - @ref meas_astrom_astrometry_Config
95  - @ref meas_astrom_astrometry_Example
96  - @ref meas_astrom_astrometry_Debug
97 
98  @section meas_astrom_astrometry_Purpose Description
99 
100  Match input sourceCat with a reference catalog and solve for the Wcs
101 
102  There are three steps, each performed by different subtasks:
103  - Find position reference stars that overlap the exposure
104  - Match sourceCat to position reference stars
105  - Fit a WCS based on the matches
106 
107  @section meas_astrom_astrometry_Initialize Task initialisation
108 
109  @copydoc \_\_init\_\_
110 
111  @section meas_astrom_astrometry_IO Invoking the Task
112 
113  @copydoc run
114 
115  @copydoc loadAndMatch
116 
117  @section meas_astrom_astrometry_Config Configuration parameters
118 
119  See @ref AstrometryConfig
120 
121  @section meas_astrom_astrometry_Example A complete example of using AstrometryTask
122 
123  See \ref meas_photocal_photocal_Example.
124 
125  @section meas_astrom_astrometry_Debug Debug variables
126 
127  The @link lsst.pipe.base.cmdLineTask.CmdLineTask command line task@endlink interface supports a
128  flag @c -d to import @b debug.py from your @c PYTHONPATH; see @ref baseDebug for more about
129  @b debug.py files.
130 
131  The available variables in AstrometryTask are:
132  <DL>
133  <DT> @c display (bool)
134  <DD> If True display information at three stages: after finding reference objects,
135  after matching sources to reference objects, and after fitting the WCS; defaults to False
136  <DT> @c frame (int)
137  <DD> ds9 frame to use to display the reference objects; the next two frames are used
138  to display the match list and the results of the final WCS; defaults to 0
139  </DL>
140 
141  To investigate the @ref meas_astrom_astrometry_Debug, put something like
142  @code{.py}
143  import lsstDebug
144  def DebugInfo(name):
145  debug = lsstDebug.getInfo(name) # N.b. lsstDebug.Info(name) would call us recursively
146  if name == "lsst.meas.astrom.astrometry":
147  debug.display = True
148 
149  return debug
150 
151  lsstDebug.Info = DebugInfo
152  @endcode
153  into your debug.py file and run this task with the @c --debug flag.
154  """
155  ConfigClass = AstrometryConfig
156  _DefaultName = "astrometricSolver"
157 
158  def __init__(self, refObjLoader, schema=None, **kwargs):
159  """!Construct an AstrometryTask
160 
161  @param[in] refObjLoader A reference object loader object
162  @param[in] schema ignored; available for compatibility with an older astrometry task
163  @param[in] kwargs additional keyword arguments for pipe_base Task.\_\_init\_\_
164  """
165  pipeBase.Task.__init__(self, **kwargs)
166  self.refObjLoader = refObjLoader
167  self.makeSubtask("matcher")
168  self.makeSubtask("wcsFitter")
169 
170  @pipeBase.timeMethod
171  def run(self, exposure, sourceCat):
172  """!Load reference objects, match sources and optionally fit a WCS
173 
174  This is a thin layer around solve or loadAndMatch, depending on config.forceKnownWcs
175 
176  @param[in,out] exposure exposure whose WCS is to be fit
177  The following are read only:
178  - bbox
179  - calib (may be absent)
180  - filter (may be unset)
181  - detector (if wcs is pure tangent; may be absent)
182  The following are updated:
183  - wcs (the initial value is used as an initial guess, and is required)
184  @param[in] sourceCat catalog of sources detected on the exposure (an lsst.afw.table.SourceCatalog)
185  @return an lsst.pipe.base.Struct with these fields:
186  - refCat reference object catalog of objects that overlap the exposure (with some margin)
187  (an lsst::afw::table::SimpleCatalog)
188  - matches list of reference object/source matches (an lsst.afw.table.ReferenceMatchVector)
189  - scatterOnSky median on-sky separation between reference objects and sources in "matches"
190  (an lsst.afw.geom.Angle), or None if config.forceKnownWcs True
191  - matchMeta metadata needed to unpersist matches (an lsst.daf.base.PropertyList)
192  """
193  if self.config.forceKnownWcs:
194  res = self.loadAndMatch(exposure=exposure, sourceCat=sourceCat)
195  res.scatterOnSky = None
196  else:
197  res = self.solve(exposure=exposure, sourceCat=sourceCat)
198  return res
199 
200  @pipeBase.timeMethod
201  def loadAndMatch(self, exposure, sourceCat):
202  """!Load reference objects overlapping an exposure and match to sources detected on that exposure
203 
204  @param[in] exposure exposure that the sources overlap
205  @param[in] sourceCat catalog of sources detected on the exposure (an lsst.afw.table.SourceCatalog)
206 
207  @return an lsst.pipe.base.Struct with these fields:
208  - refCat reference object catalog of objects that overlap the exposure (with some margin)
209  (an lsst::afw::table::SimpleCatalog)
210  - matches list of reference object/source matches (an lsst.afw.table.ReferenceMatchVector)
211  - matchMeta metadata needed to unpersist matches (an lsst.daf.base.PropertyList)
212 
213  @note ignores config.forceKnownWcs, config.maxIter, config.matchDistanceSigma
214  and config.minMatchDistanceArcSec
215  """
216  import lsstDebug
217  debug = lsstDebug.Info(__name__)
218 
219  matchMeta = createMatchMetadata(exposure, border=self.refObjLoader.config.pixelMargin)
220  expMd = self._getExposureMetadata(exposure)
221 
222  loadRes = self.refObjLoader.loadPixelBox(
223  bbox=expMd.bbox,
224  wcs=expMd.wcs,
225  filterName=expMd.filterName,
226  calib=expMd.calib,
227  )
228 
229  matchRes = self.matcher.matchObjectsToSources(
230  refCat=loadRes.refCat,
231  sourceCat=sourceCat,
232  wcs=expMd.wcs,
233  refFluxField=loadRes.fluxField,
234  maxMatchDist=None,
235  )
236 
237  distStats = self._computeMatchStatsOnSky(matchRes.matches)
238  self.log.info(
239  "Found %d matches with scatter = %0.3f +- %0.3f arcsec; " %
240  (len(matchRes.matches), distStats.distMean.asArcseconds(), distStats.distStdDev.asArcseconds())
241  )
242 
243  if debug.display:
244  frame = int(debug.frame)
246  refCat=loadRes.refCat,
247  sourceCat=sourceCat,
248  matches=matchRes.matches,
249  exposure=exposure,
250  bbox=expMd.bbox,
251  frame=frame,
252  title="Matches",
253  )
254 
255  return pipeBase.Struct(
256  refCat=loadRes.refCat,
257  matches=matchRes.matches,
258  matchMeta=matchMeta,
259  )
260 
261  @pipeBase.timeMethod
262  def solve(self, exposure, sourceCat):
263  """!Load reference objects overlapping an exposure, match to sources and fit a WCS
264 
265  @return an lsst.pipe.base.Struct with these fields:
266  - refCat reference object catalog of objects that overlap the exposure (with some margin)
267  (an lsst::afw::table::SimpleCatalog)
268  - matches list of reference object/source matches (an lsst.afw.table.ReferenceMatchVector)
269  - scatterOnSky median on-sky separation between reference objects and sources in "matches"
270  (an lsst.afw.geom.Angle)
271  - matchMeta metadata needed to unpersist matches (an lsst.daf.base.PropertyList)
272 
273  @note ignores config.forceKnownWcs
274  """
275  import lsstDebug
276  debug = lsstDebug.Info(__name__)
277 
278  matchMeta = createMatchMetadata(exposure, border=self.refObjLoader.config.pixelMargin)
279  expMd = self._getExposureMetadata(exposure)
280 
281  loadRes = self.refObjLoader.loadPixelBox(
282  bbox=expMd.bbox,
283  wcs=expMd.wcs,
284  filterName=expMd.filterName,
285  calib=expMd.calib,
286  )
287  if debug.display:
288  frame = int(debug.frame)
290  refCat=loadRes.refCat,
291  sourceCat=sourceCat,
292  exposure=exposure,
293  bbox=expMd.bbox,
294  frame=frame,
295  title="Reference catalog",
296  )
297 
298  res = None
299  wcs = expMd.wcs
300  maxMatchDist = None
301  for i in range(self.config.maxIter):
302  iterNum = i + 1
303  try:
304  tryRes = self._matchAndFitWcs( # refCat, sourceCat, refFluxField, bbox, wcs, exposure=None
305  refCat=loadRes.refCat,
306  sourceCat=sourceCat,
307  refFluxField=loadRes.fluxField,
308  bbox=expMd.bbox,
309  wcs=wcs,
310  exposure=exposure,
311  maxMatchDist=maxMatchDist,
312  )
313  except Exception as e:
314  # if we have had a succeessful iteration then use that; otherwise fail
315  if i > 0:
316  self.log.info("Fit WCS iter %d failed; using previous iteration: %s" % (iterNum, e))
317  iterNum -= 1
318  break
319  else:
320  raise
321 
322  tryMatchDist = self._computeMatchStatsOnSky(tryRes.matches)
323  self.log.debug(
324  "Match and fit WCS iteration %d: found %d matches with scatter = %0.3f +- %0.3f arcsec; "
325  "max match distance = %0.3f arcsec",
326  iterNum, len(tryRes.matches), tryMatchDist.distMean.asArcseconds(),
327  tryMatchDist.distStdDev.asArcseconds(), tryMatchDist.maxMatchDist.asArcseconds())
328  if maxMatchDist is not None:
329  if tryMatchDist.maxMatchDist >= maxMatchDist:
330  self.log.debug(
331  "Iteration %d had no better maxMatchDist; using previous iteration", iterNum)
332  iterNum -= 1
333  break
334 
335  maxMatchDist = tryMatchDist.maxMatchDist
336  res = tryRes
337  wcs = res.wcs
338  if tryMatchDist.maxMatchDist.asArcseconds() < self.config.minMatchDistanceArcSec:
339  self.log.debug(
340  "Max match distance = %0.3f arcsec < %0.3f = config.minMatchDistanceArcSec; "
341  "that's good enough",
342  tryMatchDist.maxMatchDist.asArcseconds(), self.config.minMatchDistanceArcSec)
343  break
344 
345  self.log.info(
346  "Matched and fit WCS in %d iterations; "
347  "found %d matches with scatter = %0.3f +- %0.3f arcsec" %
348  (iterNum, len(tryRes.matches), tryMatchDist.distMean.asArcseconds(),
349  tryMatchDist.distStdDev.asArcseconds()))
350 
351  exposure.setWcs(res.wcs)
352 
353  return pipeBase.Struct(
354  refCat=loadRes.refCat,
355  matches=res.matches,
356  scatterOnSky=res.scatterOnSky,
357  matchMeta=matchMeta,
358  )
359 
360  def _computeMatchStatsOnSky(self, matchList):
361  """Compute on-sky radial distance statistics for a match list
362 
363  @param[in] matchList list of matches between reference object and sources;
364  the distance field is the only field read and it must be set to distance in radians
365 
366  @return a pipe_base Struct containing these fields:
367  - distMean clipped mean of on-sky radial separation
368  - distStdDev clipped standard deviation of on-sky radial separation
369  - maxMatchDist distMean + self.config.matchDistanceSigma*distStdDev
370  """
371  distStatsInRadians = makeMatchStatistics(matchList, afwMath.MEANCLIP | afwMath.STDEVCLIP)
372  distMean = distStatsInRadians.getValue(afwMath.MEANCLIP)*afwGeom.radians
373  distStdDev = distStatsInRadians.getValue(afwMath.STDEVCLIP)*afwGeom.radians
374  return pipeBase.Struct(
375  distMean=distMean,
376  distStdDev=distStdDev,
377  maxMatchDist=distMean + self.config.matchDistanceSigma*distStdDev,
378  )
379 
380  def _getExposureMetadata(self, exposure):
381  """!Extract metadata from an exposure
382 
383  @return an lsst.pipe.base.Struct containing the following exposure metadata:
384  - bbox: parent bounding box
385  - wcs: WCS (an lsst.afw.image.Wcs)
386  - calib calibration (an lsst.afw.image.Calib), or None if unknown
387  - filterName: name of filter, or None if unknown
388  """
389  exposureInfo = exposure.getInfo()
390  filterName = exposureInfo.getFilter().getName() or None
391  if filterName == "_unknown_":
392  filterName = None
393  return pipeBase.Struct(
394  bbox=exposure.getBBox(),
395  wcs=getDistortedWcs(exposureInfo, log=self.log),
396  calib=exposureInfo.getCalib() if exposureInfo.hasCalib() else None,
397  filterName=filterName,
398  )
399 
400  @pipeBase.timeMethod
401  def _matchAndFitWcs(self, refCat, sourceCat, refFluxField, bbox, wcs, maxMatchDist=None,
402  exposure=None):
403  """!Match sources to reference objects and fit a WCS
404 
405  @param[in] refCat catalog of reference objects
406  @param[in] sourceCat catalog of sources detected on the exposure (an lsst.afw.table.SourceCatalog)
407  @param[in] refFluxField field of refCat to use for flux
408  @param[in] bbox bounding box of exposure (an lsst.afw.geom.Box2I)
409  @param[in] wcs initial guess for WCS of exposure (an lsst.afw.image.Wcs)
410  @param[in] maxMatchDist maximum on-sky distance between reference objects and sources
411  (an lsst.afw.geom.Angle); if None then use the matcher's default
412  @param[in] exposure exposure whose WCS is to be fit, or None; used only for the debug display
413 
414  @return an lsst.pipe.base.Struct with these fields:
415  - matches list of reference object/source matches (an lsst.afw.table.ReferenceMatchVector)
416  - wcs the fit WCS (an lsst.afw.image.Wcs)
417  - scatterOnSky median on-sky separation between reference objects and sources in "matches"
418  (an lsst.afw.geom.Angle)
419  """
420  import lsstDebug
421  debug = lsstDebug.Info(__name__)
422  matchRes = self.matcher.matchObjectsToSources(
423  refCat=refCat,
424  sourceCat=sourceCat,
425  wcs=wcs,
426  refFluxField=refFluxField,
427  maxMatchDist=maxMatchDist,
428  )
429  self.log.debug("Found %s matches", len(matchRes.matches))
430  if debug.display:
431  frame = int(debug.frame)
433  refCat=refCat,
434  sourceCat=matchRes.usableSourceCat,
435  matches=matchRes.matches,
436  exposure=exposure,
437  bbox=bbox,
438  frame=frame + 1,
439  title="Initial WCS",
440  )
441 
442  self.log.debug("Fitting WCS")
443  fitRes = self.wcsFitter.fitWcs(
444  matches=matchRes.matches,
445  initWcs=wcs,
446  bbox=bbox,
447  refCat=refCat,
448  sourceCat=sourceCat,
449  )
450  fitWcs = fitRes.wcs
451  scatterOnSky = fitRes.scatterOnSky
452  if debug.display:
453  frame = int(debug.frame)
455  refCat=refCat,
456  sourceCat=matchRes.usableSourceCat,
457  matches=matchRes.matches,
458  exposure=exposure,
459  bbox=bbox,
460  frame=frame + 2,
461  title="Fit TAN-SIP WCS",
462  )
463 
464  return pipeBase.Struct(
465  matches=matchRes.matches,
466  wcs=fitWcs,
467  scatterOnSky=scatterOnSky,
468  )
def _matchAndFitWcs
Match sources to reference objects and fit a WCS.
Definition: astrometry.py:402
def _getExposureMetadata
Extract metadata from an exposure.
Definition: astrometry.py:380
def __init__
Construct an AstrometryTask.
Definition: astrometry.py:158
def getDistortedWcs
Get a WCS from an exposureInfo, with distortion terms if possible.
Definition: utils.py:48
def run
Load reference objects, match sources and optionally fit a WCS.
Definition: astrometry.py:171
afw::math::Statistics makeMatchStatistics(std::vector< MatchT > const &matchList, int const flags, afw::math::StatisticsControl const &sctrl)
def solve
Load reference objects overlapping an exposure, match to sources and fit a WCS.
Definition: astrometry.py:262
Match an input source catalog with objects from a reference catalog and solve for the WCS...
Definition: astrometry.py:84
def loadAndMatch
Load reference objects overlapping an exposure and match to sources detected on that exposure...
Definition: astrometry.py:201