23 __all__ = [
"AstrometryConfig",
"AstrometryTask"]
26 from astropy
import units
31 from lsst.utils.timer
import timeMethod
32 from .ref_match
import RefMatchTask, RefMatchConfig
33 from .fitTanSipWcs
import FitTanSipWcsTask
34 from .display
import displayAstrometry
38 """Config for AstrometryTask.
40 wcsFitter = pexConfig.ConfigurableField(
41 target=FitTanSipWcsTask,
44 forceKnownWcs = pexConfig.Field(
46 doc=
"If True then load reference objects and match sources but do not fit a WCS; "
47 "this simply controls whether 'run' calls 'solve' or 'loadAndMatch'",
50 maxIter = pexConfig.RangeField(
51 doc=
"maximum number of iterations of match sources and fit WCS"
52 "ignored if not fitting a WCS",
57 minMatchDistanceArcSec = pexConfig.RangeField(
58 doc=
"the match distance below which further iteration is pointless (arcsec); "
59 "ignored if not fitting a WCS",
64 maxMeanDistanceArcsec = pexConfig.RangeField(
65 doc=
"Maximum mean on-sky distance (in arcsec) between matched source and rerference "
66 "objects post-fit. A mean distance greater than this threshold raises a TaskError "
67 "and the WCS fit is considered a failure. The default is set to the maximum tolerated "
68 "by the external global calibration (e.g. jointcal) step for conceivable recovery. "
69 "Appropriate value will be dataset and workflow dependent.",
74 doMagnitudeOutlierRejection = pexConfig.Field(
76 doc=(
"If True then a rough zeropoint will be computed from matched sources "
77 "and outliers will be rejected in the iterations."),
80 magnitudeOutlierRejectionNSigma = pexConfig.Field(
82 doc=(
"Number of sigma (measured from the distribution) in magnitude "
83 "for a potential reference/source match to be rejected during "
101 """Match an input source catalog with objects from a reference catalog and
104 This task is broken into two main subasks: matching and WCS fitting which
105 are very interactive. The matching here can be considered in part a first
106 pass WCS fitter due to the fitter's sensitivity to outliers.
110 refObjLoader : `lsst.meas.algorithms.ReferenceLoader`
111 A reference object loader object
112 schema : `lsst.afw.table.Schema`
113 Used to set "calib_astrometry_used" flag in output source catalog.
115 additional keyword arguments for pipe_base
116 `lsst.pipe.base.Task.__init__`
118 ConfigClass = AstrometryConfig
119 _DefaultName =
"astrometricSolver"
121 def __init__(self, refObjLoader, schema=None, **kwargs):
122 RefMatchTask.__init__(self, refObjLoader, **kwargs)
124 if schema
is not None:
125 self.
usedKeyusedKey = schema.addField(
"calib_astrometry_used", type=
"Flag",
126 doc=
"set if source was used in astrometric calibration")
130 self.makeSubtask(
"wcsFitter")
133 def run(self, sourceCat, exposure):
134 """Load reference objects, match sources and optionally fit a WCS.
136 This is a thin layer around solve or loadAndMatch, depending on
137 config.forceKnownWcs.
141 exposure : `lsst.afw.image.Exposure`
142 exposure whose WCS is to be fit
143 The following are read only:
146 - photoCalib (may be absent)
147 - filter (may be unset)
148 - detector (if wcs is pure tangent; may be absent)
150 The following are updated:
152 - wcs (the initial value is used as an initial guess, and is
155 sourceCat : `lsst.afw.table.SourceCatalog`
156 catalog of sources detected on the exposure
160 result : `lsst.pipe.base.Struct`
163 - ``refCat`` : reference object catalog of objects that overlap the
164 exposure (with some margin) (`lsst.afw.table.SimpleCatalog`).
165 - ``matches`` : astrometric matches
166 (`list` of `lsst.afw.table.ReferenceMatch`).
167 - ``scatterOnSky`` : median on-sky separation between reference
168 objects and sources in "matches"
169 (`lsst.afw.geom.Angle`) or `None` if config.forceKnownWcs True
170 - ``matchMeta`` : metadata needed to unpersist matches
171 (`lsst.daf.base.PropertyList`)
174 raise RuntimeError(
"Running matcher task with no refObjLoader set in __init__ or setRefObjLoader")
175 if self.config.forceKnownWcs:
176 res = self.
loadAndMatchloadAndMatch(exposure=exposure, sourceCat=sourceCat)
177 res.scatterOnSky =
None
179 res = self.
solvesolve(exposure=exposure, sourceCat=sourceCat)
183 def solve(self, exposure, sourceCat):
184 """Load reference objects overlapping an exposure, match to sources and
189 result : `lsst.pipe.base.Struct`
190 Result struct with components:
192 - ``refCat`` : reference object catalog of objects that overlap the
193 exposure (with some margin) (`lsst::afw::table::SimpleCatalog`).
194 - ``matches`` : astrometric matches
195 (`list` of `lsst.afw.table.ReferenceMatch`).
196 - ``scatterOnSky`` : median on-sky separation between reference
197 objects and sources in "matches" (`lsst.geom.Angle`)
198 - ``matchMeta`` : metadata needed to unpersist matches
199 (`lsst.daf.base.PropertyList`)
204 If the measured mean on-sky distance between the matched source and
205 reference objects is greater than
206 ``self.config.maxMeanDistanceArcsec``.
210 ignores config.forceKnownWcs
213 raise RuntimeError(
"Running matcher task with no refObjLoader set in __init__ or setRefObjLoader")
219 sourceSelection = self.sourceSelector.
run(sourceCat)
221 self.log.
info(
"Purged %d sources, leaving %d good sources",
222 len(sourceCat) - len(sourceSelection.sourceCat),
223 len(sourceSelection.sourceCat))
228 filterName=expMd.filterName,
229 photoCalib=expMd.photoCalib,
233 refSelection = self.referenceSelector.
run(loadRes.refCat)
235 matchMeta = self.
refObjLoaderrefObjLoader.getMetadataBox(
238 filterName=expMd.filterName,
239 photoCalib=expMd.photoCalib,
244 frame = int(debug.frame)
246 refCat=refSelection.sourceCat,
247 sourceCat=sourceSelection.sourceCat,
251 title=
"Reference catalog",
256 match_tolerance =
None
257 for i
in range(self.config.maxIter):
261 refCat=refSelection.sourceCat,
263 goodSourceCat=sourceSelection.sourceCat,
264 refFluxField=loadRes.fluxField,
268 match_tolerance=match_tolerance,
270 except Exception
as e:
273 self.log.
info(
"Fit WCS iter %d failed; using previous iteration: %s", iterNum, e)
279 match_tolerance = tryRes.match_tolerance
282 "Match and fit WCS iteration %d: found %d matches with on-sky distance mean "
283 "= %0.3f +- %0.3f arcsec; max match distance = %0.3f arcsec",
284 iterNum, len(tryRes.matches), tryMatchDist.distMean.asArcseconds(),
285 tryMatchDist.distStdDev.asArcseconds(), tryMatchDist.maxMatchDist.asArcseconds())
287 maxMatchDist = tryMatchDist.maxMatchDist
290 if maxMatchDist.asArcseconds() < self.config.minMatchDistanceArcSec:
292 "Max match distance = %0.3f arcsec < %0.3f = config.minMatchDistanceArcSec; "
293 "that's good enough",
294 maxMatchDist.asArcseconds(), self.config.minMatchDistanceArcSec)
296 match_tolerance.maxMatchDist = maxMatchDist
299 "Matched and fit WCS in %d iterations; "
300 "found %d matches with on-sky distance mean and scatter = %0.3f +- %0.3f arcsec",
301 iterNum, len(tryRes.matches), tryMatchDist.distMean.asArcseconds(),
302 tryMatchDist.distStdDev.asArcseconds())
303 if tryMatchDist.distMean.asArcseconds() > self.config.maxMeanDistanceArcsec:
304 raise pipeBase.TaskError(
305 "Fatal astrometry failure detected: mean on-sky distance = %0.3f arcsec > %0.3f "
306 "(maxMeanDistanceArcsec)" %
307 (tryMatchDist.distMean.asArcseconds(), self.config.maxMeanDistanceArcsec))
308 for m
in res.matches:
310 m.second.set(self.
usedKeyusedKey,
True)
311 exposure.setWcs(res.wcs)
314 md = exposure.getMetadata()
315 md[
'SFM_ASTROM_OFFSET_MEAN'] = tryMatchDist.distMean.asArcseconds()
316 md[
'SFM_ASTROM_OFFSET_STD'] = tryMatchDist.distStdDev.asArcseconds()
318 return pipeBase.Struct(
319 refCat=refSelection.sourceCat,
321 scatterOnSky=res.scatterOnSky,
326 def _matchAndFitWcs(self, refCat, sourceCat, goodSourceCat, refFluxField, bbox, wcs, match_tolerance,
328 """Match sources to reference objects and fit a WCS.
332 refCat : `lsst.afw.table.SimpleCatalog`
333 catalog of reference objects
334 sourceCat : `lsst.afw.table.SourceCatalog`
335 catalog of sources detected on the exposure
336 goodSourceCat : `lsst.afw.table.SourceCatalog`
337 catalog of down-selected good sources detected on the exposure
339 field of refCat to use for flux
340 bbox : `lsst.geom.Box2I`
341 bounding box of exposure
342 wcs : `lsst.afw.geom.SkyWcs`
343 initial guess for WCS of exposure
344 match_tolerance : `lsst.meas.astrom.MatchTolerance`
345 a MatchTolerance object (or None) specifying
346 internal tolerances to the matcher. See the MatchTolerance
347 definition in the respective matcher for the class definition.
348 exposure : `lsst.afw.image.Exposure`
349 exposure whose WCS is to be fit, or None; used only for the debug
354 result : `lsst.pipe.base.Struct`
355 Result struct with components:
357 - ``matches``: astrometric matches
358 (`list` of `lsst.afw.table.ReferenceMatch`).
359 - ``wcs``: the fit WCS (lsst.afw.geom.SkyWcs).
360 - ``scatterOnSky`` : median on-sky separation between reference
361 objects and sources in "matches" (`lsst.afw.geom.Angle`).
366 sourceFluxField =
"slot_%sFlux_instFlux" % (self.config.sourceFluxType)
368 matchRes = self.matcher.matchObjectsToSources(
370 sourceCat=goodSourceCat,
372 sourceFluxField=sourceFluxField,
373 refFluxField=refFluxField,
374 match_tolerance=match_tolerance,
376 self.log.
debug(
"Found %s matches", len(matchRes.matches))
378 frame = int(debug.frame)
381 sourceCat=matchRes.usableSourceCat,
382 matches=matchRes.matches,
389 if self.config.doMagnitudeOutlierRejection:
392 matches = matchRes.matches
394 self.log.
debug(
"Fitting WCS")
395 fitRes = self.wcsFitter.fitWcs(
404 scatterOnSky = fitRes.scatterOnSky
406 frame = int(debug.frame)
409 sourceCat=matchRes.usableSourceCat,
414 title=
"Fit TAN-SIP WCS",
417 return pipeBase.Struct(
420 scatterOnSky=scatterOnSky,
421 match_tolerance=matchRes.match_tolerance,
424 def _removeMagnitudeOutliers(self, sourceFluxField, refFluxField, matchesIn):
425 """Remove magnitude outliers, computing a simple zeropoint.
429 sourceFluxField : `str`
430 Field in source catalog for instrumental fluxes.
432 Field in reference catalog for fluxes (nJy).
433 matchesIn : `list` [`lsst.afw.table.ReferenceMatch`]
434 List of source/reference matches input
438 matchesOut : `list` [`lsst.afw.table.ReferenceMatch`]
439 List of source/reference matches with magnitude
442 nMatch = len(matchesIn)
443 sourceMag = np.zeros(nMatch)
444 refMag = np.zeros(nMatch)
445 for i, match
in enumerate(matchesIn):
446 sourceMag[i] = -2.5*np.log10(match[1][sourceFluxField])
447 refMag[i] = (match[0][refFluxField]*units.nJy).to_value(units.ABmag)
449 deltaMag = refMag - sourceMag
451 goodDelta, = np.where(np.isfinite(deltaMag))
452 zp = np.median(deltaMag[goodDelta])
456 zpSigma = np.clip(scipy.stats.median_abs_deviation(deltaMag[goodDelta], scale=
'normal'),
460 self.log.
info(
"Rough zeropoint from astrometry matches is %.4f +/- %.4f.",
463 goodStars = goodDelta[(np.abs(deltaMag[goodDelta] - zp)
464 <= self.config.magnitudeOutlierRejectionNSigma*zpSigma)]
466 nOutlier = nMatch - goodStars.size
467 self.log.
info(
"Removed %d magnitude outliers out of %d total astrometry matches.",
471 for matchInd
in goodStars:
472 matchesOut.append(matchesIn[matchInd])
def solve(self, exposure, sourceCat)
def _removeMagnitudeOutliers(self, sourceFluxField, refFluxField, matchesIn)
def _matchAndFitWcs(self, refCat, sourceCat, goodSourceCat, refFluxField, bbox, wcs, match_tolerance, exposure=None)
def run(self, sourceCat, exposure)
def __init__(self, refObjLoader, schema=None, **kwargs)
def _computeMatchStatsOnSky(self, matchList)
def loadAndMatch(self, exposure, sourceCat)
def _getExposureMetadata(self, exposure)
def displayAstrometry(refCat=None, sourceCat=None, distortedCentroidKey=None, bbox=None, exposure=None, matches=None, frame=1, title="", pause=True)