23__all__ = [
"AstrometryConfig",
"AstrometryTask"]
26from astropy
import units
31from lsst.utils.timer
import timeMethod
32from .ref_match
import RefMatchTask, RefMatchConfig
33from .fitTanSipWcs
import FitTanSipWcsTask
34from .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
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.
142 exposure whose WCS
is to be fit
143 The following are read only:
146 - filter (may be unset)
147 - detector (
if wcs
is pure tangent; may be absent)
149 The following are updated:
151 - wcs (the initial value
is used
as an initial guess,
and is
155 catalog of sources detected on the exposure
159 result : `lsst.pipe.base.Struct`
162 - ``refCat`` : reference object catalog of objects that overlap the
164 - ``matches`` : astrometric matches
166 - ``scatterOnSky`` : median on-sky separation between reference
167 objects
and sources
in "matches"
168 (`lsst.afw.geom.Angle`)
or `
None`
if config.forceKnownWcs
True
169 - ``matchMeta`` : metadata needed to unpersist matches
173 raise RuntimeError(
"Running matcher task with no refObjLoader set in __init__ or setRefObjLoader")
174 if self.config.forceKnownWcs:
175 res = self.
loadAndMatchloadAndMatch(exposure=exposure, sourceCat=sourceCat)
176 res.scatterOnSky =
None
178 res = self.
solvesolve(exposure=exposure, sourceCat=sourceCat)
182 def solve(self, exposure, sourceCat):
183 """Load reference objects overlapping an exposure, match to sources and
188 result : `lsst.pipe.base.Struct`
189 Result struct with components:
191 - ``refCat`` : reference object catalog of objects that overlap the
192 exposure (
with some margin) (`lsst::afw::table::SimpleCatalog`).
193 - ``matches`` : astrometric matches
195 - ``scatterOnSky`` : median on-sky separation between reference
197 - ``matchMeta`` : metadata needed to unpersist matches
203 If the measured mean on-sky distance between the matched source
and
204 reference objects
is greater than
205 ``self.config.maxMeanDistanceArcsec``.
209 ignores config.forceKnownWcs
212 raise RuntimeError(
"Running matcher task with no refObjLoader set in __init__ or setRefObjLoader")
218 sourceSelection = self.sourceSelector.
run(sourceCat)
220 self.log.
info(
"Purged %d sources, leaving %d good sources",
221 len(sourceCat) - len(sourceSelection.sourceCat),
222 len(sourceSelection.sourceCat))
227 filterName=expMd.filterName,
231 refSelection = self.referenceSelector.
run(loadRes.refCat)
233 matchMeta = self.
refObjLoaderrefObjLoader.getMetadataBox(
236 filterName=expMd.filterName,
241 frame =
int(debug.frame)
243 refCat=refSelection.sourceCat,
244 sourceCat=sourceSelection.sourceCat,
248 title=
"Reference catalog",
253 match_tolerance =
None
254 for i
in range(self.config.maxIter):
258 refCat=refSelection.sourceCat,
260 goodSourceCat=sourceSelection.sourceCat,
261 refFluxField=loadRes.fluxField,
265 match_tolerance=match_tolerance,
267 except Exception
as e:
270 self.log.
info(
"Fit WCS iter %d failed; using previous iteration: %s", iterNum, e)
276 match_tolerance = tryRes.match_tolerance
279 "Match and fit WCS iteration %d: found %d matches with on-sky distance mean "
280 "= %0.3f +- %0.3f arcsec; max match distance = %0.3f arcsec",
281 iterNum, len(tryRes.matches), tryMatchDist.distMean.asArcseconds(),
282 tryMatchDist.distStdDev.asArcseconds(), tryMatchDist.maxMatchDist.asArcseconds())
284 maxMatchDist = tryMatchDist.maxMatchDist
287 if maxMatchDist.asArcseconds() < self.config.minMatchDistanceArcSec:
289 "Max match distance = %0.3f arcsec < %0.3f = config.minMatchDistanceArcSec; "
290 "that's good enough",
291 maxMatchDist.asArcseconds(), self.config.minMatchDistanceArcSec)
293 match_tolerance.maxMatchDist = maxMatchDist
296 "Matched and fit WCS in %d iterations; "
297 "found %d matches with on-sky distance mean and scatter = %0.3f +- %0.3f arcsec",
298 iterNum, len(tryRes.matches), tryMatchDist.distMean.asArcseconds(),
299 tryMatchDist.distStdDev.asArcseconds())
300 if tryMatchDist.distMean.asArcseconds() > self.config.maxMeanDistanceArcsec:
301 raise pipeBase.TaskError(
302 "Fatal astrometry failure detected: mean on-sky distance = %0.3f arcsec > %0.3f "
303 "(maxMeanDistanceArcsec)" %
304 (tryMatchDist.distMean.asArcseconds(), self.config.maxMeanDistanceArcsec))
305 for m
in res.matches:
307 m.second.set(self.
usedKeyusedKey,
True)
308 exposure.setWcs(res.wcs)
311 md = exposure.getMetadata()
312 md[
'SFM_ASTROM_OFFSET_MEAN'] = tryMatchDist.distMean.asArcseconds()
313 md[
'SFM_ASTROM_OFFSET_STD'] = tryMatchDist.distStdDev.asArcseconds()
315 return pipeBase.Struct(
316 refCat=refSelection.sourceCat,
318 scatterOnSky=res.scatterOnSky,
323 def _matchAndFitWcs(self, refCat, sourceCat, goodSourceCat, refFluxField, bbox, wcs, match_tolerance,
325 """Match sources to reference objects and fit a WCS.
330 catalog of reference objects
332 catalog of sources detected on the exposure
334 catalog of down-selected good sources detected on the exposure
336 field of refCat to use
for flux
338 bounding box of exposure
340 initial guess
for WCS of exposure
342 a MatchTolerance object (
or None) specifying
343 internal tolerances to the matcher. See the MatchTolerance
344 definition
in the respective matcher
for the
class definition.
346 exposure whose WCS
is to be fit,
or None; used only
for the debug
351 result : `lsst.pipe.base.Struct`
352 Result struct
with components:
354 - ``matches``: astrometric matches
357 - ``scatterOnSky`` : median on-sky separation between reference
358 objects
and sources
in "matches" (`lsst.afw.geom.Angle`).
363 sourceFluxField =
"slot_%sFlux_instFlux" % (self.config.sourceFluxType)
365 matchRes = self.matcher.matchObjectsToSources(
367 sourceCat=goodSourceCat,
369 sourceFluxField=sourceFluxField,
370 refFluxField=refFluxField,
371 match_tolerance=match_tolerance,
373 self.log.
debug(
"Found %s matches", len(matchRes.matches))
375 frame =
int(debug.frame)
378 sourceCat=matchRes.usableSourceCat,
379 matches=matchRes.matches,
386 if self.config.doMagnitudeOutlierRejection:
389 matches = matchRes.matches
391 self.log.
debug(
"Fitting WCS")
392 fitRes = self.wcsFitter.fitWcs(
401 scatterOnSky = fitRes.scatterOnSky
403 frame =
int(debug.frame)
406 sourceCat=matchRes.usableSourceCat,
411 title=
"Fit TAN-SIP WCS",
414 return pipeBase.Struct(
417 scatterOnSky=scatterOnSky,
418 match_tolerance=matchRes.match_tolerance,
421 def _removeMagnitudeOutliers(self, sourceFluxField, refFluxField, matchesIn):
422 """Remove magnitude outliers, computing a simple zeropoint.
426 sourceFluxField : `str`
427 Field in source catalog
for instrumental fluxes.
429 Field
in reference catalog
for fluxes (nJy).
431 List of source/reference matches input
436 List of source/reference matches
with magnitude
439 nMatch = len(matchesIn)
440 sourceMag = np.zeros(nMatch)
441 refMag = np.zeros(nMatch)
442 for i, match
in enumerate(matchesIn):
443 sourceMag[i] = -2.5*np.log10(match[1][sourceFluxField])
444 refMag[i] = (match[0][refFluxField]*units.nJy).to_value(units.ABmag)
446 deltaMag = refMag - sourceMag
448 goodDelta, = np.where(np.isfinite(deltaMag))
449 zp = np.median(deltaMag[goodDelta])
453 zpSigma = np.clip(scipy.stats.median_abs_deviation(deltaMag[goodDelta], scale=
'normal'),
457 self.log.
info(
"Rough zeropoint from astrometry matches is %.4f +/- %.4f.",
460 goodStars = goodDelta[(np.abs(deltaMag[goodDelta] - zp)
461 <= self.config.magnitudeOutlierRejectionNSigma*zpSigma)]
463 nOutlier = nMatch - goodStars.size
464 self.log.
info(
"Removed %d magnitude outliers out of %d total astrometry matches.",
468 for matchInd
in goodStars:
469 matchesOut.append(matchesIn[matchInd])
A 2-dimensional celestial WCS that transform pixels to ICRS RA/Dec, using the LSST standard for pixel...
A class to contain the data, WCS, and other information needed to describe an image of the sky.
Defines the fields and offsets for a table.
Custom catalog class for record/table subclasses that are guaranteed to have an ID,...
Class for storing ordered metadata with comments.
A class representing an angle.
An integer coordinate rectangle.
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)
Lightweight representation of a geometric match between two records.