23 __all__ = [
"AstrometryConfig",
"AstrometryTask"]
26 from astropy
import units
31 from .ref_match
import RefMatchTask, RefMatchConfig
32 from .fitTanSipWcs
import FitTanSipWcsTask
33 from .display
import displayAstrometry
37 """Config for AstrometryTask.
39 wcsFitter = pexConfig.ConfigurableField(
40 target=FitTanSipWcsTask,
43 forceKnownWcs = pexConfig.Field(
45 doc=
"If True then load reference objects and match sources but do not fit a WCS; "
46 "this simply controls whether 'run' calls 'solve' or 'loadAndMatch'",
49 maxIter = pexConfig.RangeField(
50 doc=
"maximum number of iterations of match sources and fit WCS"
51 "ignored if not fitting a WCS",
56 minMatchDistanceArcSec = pexConfig.RangeField(
57 doc=
"the match distance below which further iteration is pointless (arcsec); "
58 "ignored if not fitting a WCS",
63 doMagnitudeOutlierRejection = pexConfig.Field(
65 doc=(
"If True then a rough zeropoint will be computed from matched sources "
66 "and outliers will be rejected in the iterations."),
69 magnitudeOutlierRejectionNSigma = pexConfig.Field(
71 doc=(
"Number of sigma (measured from the distribution) in magnitude "
72 "for a potential reference/source match to be rejected during "
90 """Match an input source catalog with objects from a reference catalog and
93 This task is broken into two main subasks: matching and WCS fitting which
94 are very interactive. The matching here can be considered in part a first
95 pass WCS fitter due to the fitter's sensitivity to outliers.
99 refObjLoader : `lsst.meas.algorithms.ReferenceLoader`
100 A reference object loader object
101 schema : `lsst.afw.table.Schema`
102 Used to set "calib_astrometry_used" flag in output source catalog.
104 additional keyword arguments for pipe_base
105 `lsst.pipe.base.Task.__init__`
107 ConfigClass = AstrometryConfig
108 _DefaultName =
"astrometricSolver"
110 def __init__(self, refObjLoader, schema=None, **kwargs):
111 RefMatchTask.__init__(self, refObjLoader, **kwargs)
113 if schema
is not None:
114 self.
usedKeyusedKey = schema.addField(
"calib_astrometry_used", type=
"Flag",
115 doc=
"set if source was used in astrometric calibration")
119 self.makeSubtask(
"wcsFitter")
122 def run(self, sourceCat, exposure):
123 """Load reference objects, match sources and optionally fit a WCS.
125 This is a thin layer around solve or loadAndMatch, depending on
126 config.forceKnownWcs.
130 exposure : `lsst.afw.image.Exposure`
131 exposure whose WCS is to be fit
132 The following are read only:
135 - photoCalib (may be absent)
136 - filter (may be unset)
137 - detector (if wcs is pure tangent; may be absent)
139 The following are updated:
141 - wcs (the initial value is used as an initial guess, and is
144 sourceCat : `lsst.afw.table.SourceCatalog`
145 catalog of sources detected on the exposure
149 result : `lsst.pipe.base.Struct`
152 - ``refCat`` : reference object catalog of objects that overlap the
153 exposure (with some margin) (`lsst.afw.table.SimpleCatalog`).
154 - ``matches`` : astrometric matches
155 (`list` of `lsst.afw.table.ReferenceMatch`).
156 - ``scatterOnSky`` : median on-sky separation between reference
157 objects and sources in "matches"
158 (`lsst.afw.geom.Angle`) or `None` if config.forceKnownWcs True
159 - ``matchMeta`` : metadata needed to unpersist matches
160 (`lsst.daf.base.PropertyList`)
163 raise RuntimeError(
"Running matcher task with no refObjLoader set in __init__ or setRefObjLoader")
164 if self.config.forceKnownWcs:
165 res = self.
loadAndMatchloadAndMatch(exposure=exposure, sourceCat=sourceCat)
166 res.scatterOnSky =
None
168 res = self.
solvesolve(exposure=exposure, sourceCat=sourceCat)
172 def solve(self, exposure, sourceCat):
173 """Load reference objects overlapping an exposure, match to sources and
178 result : `lsst.pipe.base.Struct`
179 Result struct with components:
181 - ``refCat`` : reference object catalog of objects that overlap the
182 exposure (with some margin) (`lsst::afw::table::SimpleCatalog`).
183 - ``matches`` : astrometric matches
184 (`list` of `lsst.afw.table.ReferenceMatch`).
185 - ``scatterOnSky`` : median on-sky separation between reference
186 objects and sources in "matches" (`lsst.geom.Angle`)
187 - ``matchMeta`` : metadata needed to unpersist matches
188 (`lsst.daf.base.PropertyList`)
192 ignores config.forceKnownWcs
195 raise RuntimeError(
"Running matcher task with no refObjLoader set in __init__ or setRefObjLoader")
201 sourceSelection = self.sourceSelector.
run(sourceCat)
203 self.log.
info(
"Purged %d sources, leaving %d good sources" %
204 (len(sourceCat) - len(sourceSelection.sourceCat),
205 len(sourceSelection.sourceCat)))
210 filterName=expMd.filterName,
211 photoCalib=expMd.photoCalib,
215 refSelection = self.referenceSelector.
run(loadRes.refCat)
217 matchMeta = self.
refObjLoaderrefObjLoader.getMetadataBox(
220 filterName=expMd.filterName,
221 photoCalib=expMd.photoCalib,
226 frame = int(debug.frame)
228 refCat=refSelection.sourceCat,
229 sourceCat=sourceSelection.sourceCat,
233 title=
"Reference catalog",
238 match_tolerance =
None
239 for i
in range(self.config.maxIter):
243 refCat=refSelection.sourceCat,
245 goodSourceCat=sourceSelection.sourceCat,
246 refFluxField=loadRes.fluxField,
250 match_tolerance=match_tolerance,
252 except Exception
as e:
255 self.log.
info(
"Fit WCS iter %d failed; using previous iteration: %s" % (iterNum, e))
261 match_tolerance = tryRes.match_tolerance
264 "Match and fit WCS iteration %d: found %d matches with scatter = %0.3f +- %0.3f arcsec; "
265 "max match distance = %0.3f arcsec",
266 iterNum, len(tryRes.matches), tryMatchDist.distMean.asArcseconds(),
267 tryMatchDist.distStdDev.asArcseconds(), tryMatchDist.maxMatchDist.asArcseconds())
269 maxMatchDist = tryMatchDist.maxMatchDist
272 if maxMatchDist.asArcseconds() < self.config.minMatchDistanceArcSec:
274 "Max match distance = %0.3f arcsec < %0.3f = config.minMatchDistanceArcSec; "
275 "that's good enough",
276 maxMatchDist.asArcseconds(), self.config.minMatchDistanceArcSec)
278 match_tolerance.maxMatchDist = maxMatchDist
281 "Matched and fit WCS in %d iterations; "
282 "found %d matches with scatter = %0.3f +- %0.3f arcsec" %
283 (iterNum, len(tryRes.matches), tryMatchDist.distMean.asArcseconds(),
284 tryMatchDist.distStdDev.asArcseconds()))
285 for m
in res.matches:
287 m.second.set(self.
usedKeyusedKey,
True)
288 exposure.setWcs(res.wcs)
291 md = exposure.getMetadata()
292 md[
'SFM_ASTROM_OFFSET_MEAN'] = tryMatchDist.distMean.asArcseconds()
293 md[
'SFM_ASTROM_OFFSET_STD'] = tryMatchDist.distStdDev.asArcseconds()
295 return pipeBase.Struct(
296 refCat=refSelection.sourceCat,
298 scatterOnSky=res.scatterOnSky,
303 def _matchAndFitWcs(self, refCat, sourceCat, goodSourceCat, refFluxField, bbox, wcs, match_tolerance,
305 """Match sources to reference objects and fit a WCS.
309 refCat : `lsst.afw.table.SimpleCatalog`
310 catalog of reference objects
311 sourceCat : `lsst.afw.table.SourceCatalog`
312 catalog of sources detected on the exposure
313 goodSourceCat : `lsst.afw.table.SourceCatalog`
314 catalog of down-selected good sources detected on the exposure
316 field of refCat to use for flux
317 bbox : `lsst.geom.Box2I`
318 bounding box of exposure
319 wcs : `lsst.afw.geom.SkyWcs`
320 initial guess for WCS of exposure
321 match_tolerance : `lsst.meas.astrom.MatchTolerance`
322 a MatchTolerance object (or None) specifying
323 internal tolerances to the matcher. See the MatchTolerance
324 definition in the respective matcher for the class definition.
325 exposure : `lsst.afw.image.Exposure`
326 exposure whose WCS is to be fit, or None; used only for the debug
331 result : `lsst.pipe.base.Struct`
332 Result struct with components:
334 - ``matches``: astrometric matches
335 (`list` of `lsst.afw.table.ReferenceMatch`).
336 - ``wcs``: the fit WCS (lsst.afw.geom.SkyWcs).
337 - ``scatterOnSky`` : median on-sky separation between reference
338 objects and sources in "matches" (`lsst.afw.geom.Angle`).
343 sourceFluxField =
"slot_%sFlux_instFlux" % (self.config.sourceFluxType)
345 matchRes = self.matcher.matchObjectsToSources(
347 sourceCat=goodSourceCat,
349 sourceFluxField=sourceFluxField,
350 refFluxField=refFluxField,
351 match_tolerance=match_tolerance,
353 self.log.
debug(
"Found %s matches", len(matchRes.matches))
355 frame = int(debug.frame)
358 sourceCat=matchRes.usableSourceCat,
359 matches=matchRes.matches,
366 if self.config.doMagnitudeOutlierRejection:
369 matches = matchRes.matches
371 self.log.
debug(
"Fitting WCS")
372 fitRes = self.wcsFitter.fitWcs(
381 scatterOnSky = fitRes.scatterOnSky
383 frame = int(debug.frame)
386 sourceCat=matchRes.usableSourceCat,
391 title=
"Fit TAN-SIP WCS",
394 return pipeBase.Struct(
397 scatterOnSky=scatterOnSky,
398 match_tolerance=matchRes.match_tolerance,
401 def _removeMagnitudeOutliers(self, sourceFluxField, refFluxField, matchesIn):
402 """Remove magnitude outliers, computing a simple zeropoint.
406 sourceFluxField : `str`
407 Field in source catalog for instrumental fluxes.
409 Field in reference catalog for fluxes (nJy).
410 matchesIn : `list` [`lsst.afw.table.ReferenceMatch`]
411 List of source/reference matches input
415 matchesOut : `list` [`lsst.afw.table.ReferenceMatch`]
416 List of source/reference matches with magnitude
419 nMatch = len(matchesIn)
420 sourceMag = np.zeros(nMatch)
421 refMag = np.zeros(nMatch)
422 for i, match
in enumerate(matchesIn):
423 sourceMag[i] = -2.5*np.log10(match[1][sourceFluxField])
424 refMag[i] = (match[0][refFluxField]*units.nJy).to_value(units.ABmag)
426 deltaMag = refMag - sourceMag
428 goodDelta, = np.where(np.isfinite(deltaMag))
429 zp = np.median(deltaMag[goodDelta])
433 zpSigma = np.clip(scipy.stats.median_abs_deviation(deltaMag[goodDelta], scale=
'normal'),
437 self.log.
info(
"Rough zeropoint from astrometry matches is %.4f +/- %.4f.",
440 goodStars = goodDelta[(np.abs(deltaMag[goodDelta] - zp)
441 <= self.config.magnitudeOutlierRejectionNSigma*zpSigma)]
443 nOutlier = nMatch - goodStars.size
444 self.log.
info(
"Removed %d magnitude outliers out of %d total astrometry matches.",
448 for matchInd
in goodStars:
449 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)