Coverage for python/lsst/meas/extensions/piff/piffPsfDeterminer.py: 19%
144 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-01 10:54 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-01 10:54 +0000
1# This file is part of meas_extensions_piff.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
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 GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
22__all__ = ["PiffPsfDeterminerConfig", "PiffPsfDeterminerTask"]
24import numpy as np
25import piff
26import galsim
27import re
29from lsst.afw.cameraGeom import PIXELS, FIELD_ANGLE
30import lsst.pex.config as pexConfig
31import lsst.meas.algorithms as measAlg
32from lsst.meas.algorithms.psfDeterminer import BasePsfDeterminerTask
33from .piffPsf import PiffPsf
34from .wcs_wrapper import CelestialWcsWrapper, UVWcsWrapper
37def _validateGalsimInterpolant(name: str) -> bool:
38 """A helper function to validate the GalSim interpolant at config time.
40 Parameters
41 ----------
42 name : str
43 The name of the interpolant to use from GalSim. Valid options are:
44 galsim.Lanczos(N) or Lancsos(N), where N is a positive integer
45 galsim.Linear
46 galsim.Cubic
47 galsim.Quintic
48 galsim.Delta
49 galsim.Nearest
50 galsim.SincInterpolant
52 Returns
53 -------
54 is_valid : bool
55 Whether the provided interpolant name is valid.
56 """
57 # First, check if ``name`` is a valid Lanczos interpolant.
58 for pattern in (re.compile(r"Lanczos\(\d+\)"), re.compile(r"galsim.Lanczos\(\d+\)"),):
59 match = re.match(pattern, name) # Search from the start of the string.
60 if match is not None:
61 # Check that the pattern is also the end of the string.
62 return match.end() == len(name)
64 # If not, check if ``name`` is any other valid GalSim interpolant.
65 names = {f"galsim.{interp}" for interp in
66 ("Cubic", "Delta", "Linear", "Nearest", "Quintic", "SincInterpolant")
67 }
68 return name in names
71class PiffPsfDeterminerConfig(BasePsfDeterminerTask.ConfigClass):
72 spatialOrder = pexConfig.Field[int](
73 doc="specify spatial order for PSF kernel creation",
74 default=2,
75 )
76 samplingSize = pexConfig.Field[float](
77 doc="Resolution of the internal PSF model relative to the pixel size; "
78 "e.g. 0.5 is equal to 2x oversampling",
79 default=1,
80 )
81 outlierNSigma = pexConfig.Field[float](
82 doc="n sigma for chisq outlier rejection",
83 default=4.0
84 )
85 outlierMaxRemove = pexConfig.Field[float](
86 doc="Max fraction of stars to remove as outliers each iteration",
87 default=0.05
88 )
89 maxSNR = pexConfig.Field[float](
90 doc="Rescale the weight of bright stars such that their SNR is less "
91 "than this value.",
92 default=200.0
93 )
94 zeroWeightMaskBits = pexConfig.ListField[str](
95 doc="List of mask bits for which to set pixel weights to zero.",
96 default=['BAD', 'CR', 'INTRP', 'SAT', 'SUSPECT', 'NO_DATA']
97 )
98 minimumUnmaskedFraction = pexConfig.Field[float](
99 doc="Minimum fraction of unmasked pixels required to use star.",
100 default=0.5
101 )
102 interpolant = pexConfig.Field[str](
103 doc="GalSim interpolant name for Piff to use. "
104 "Options include 'Lanczos(N)', where N is an integer, along with "
105 "galsim.Cubic, galsim.Delta, galsim.Linear, galsim.Nearest, "
106 "galsim.Quintic, and galsim.SincInterpolant.",
107 check=_validateGalsimInterpolant,
108 default="Lanczos(11)",
109 )
110 debugStarData = pexConfig.Field[bool](
111 doc="Include star images used for fitting in PSF model object.",
112 default=False
113 )
114 useCoordinates = pexConfig.ChoiceField[str](
115 doc="Which spatial coordinates to regress against in PSF modeling.",
116 allowed=dict(
117 pixel='Regress against pixel coordinates',
118 field='Regress against field angles',
119 sky='Regress against RA/Dec'
120 ),
121 default='pixel'
122 )
124 def setDefaults(self):
125 super().setDefaults()
126 # stampSize should be at least 25 so that
127 # i) aperture flux with 12 pixel radius can be compared to PSF flux.
128 # ii) fake sources injected to match the 12 pixel aperture flux get
129 # measured correctly
130 self.stampSize = 25
133def getGoodPixels(maskedImage, zeroWeightMaskBits):
134 """Compute an index array indicating good pixels to use.
136 Parameters
137 ----------
138 maskedImage : `afw.image.MaskedImage`
139 PSF candidate postage stamp
140 zeroWeightMaskBits : `List[str]`
141 List of mask bits for which to set pixel weights to zero.
143 Returns
144 -------
145 good : `ndarray`
146 Index array indicating good pixels.
147 """
148 imArr = maskedImage.image.array
149 varArr = maskedImage.variance.array
150 bitmask = maskedImage.mask.getPlaneBitMask(zeroWeightMaskBits)
151 good = (
152 (varArr != 0)
153 & (np.isfinite(varArr))
154 & (np.isfinite(imArr))
155 & ((maskedImage.mask.array & bitmask) == 0)
156 )
157 return good
160def computeWeight(maskedImage, maxSNR, good):
161 """Derive a weight map without Poisson variance component due to signal.
163 Parameters
164 ----------
165 maskedImage : `afw.image.MaskedImage`
166 PSF candidate postage stamp
167 maxSNR : `float`
168 Maximum SNR applying variance floor.
169 good : `ndarray`
170 Index array indicating good pixels.
172 Returns
173 -------
174 weightArr : `ndarry`
175 Array to use for weight.
176 """
177 imArr = maskedImage.image.array
178 varArr = maskedImage.variance.array
180 # Fit a straight line to variance vs (sky-subtracted) signal.
181 # The evaluate that line at zero signal to get an estimate of the
182 # signal-free variance.
183 fit = np.polyfit(imArr[good], varArr[good], deg=1)
184 # fit is [1/gain, sky_var]
185 weightArr = np.zeros_like(imArr, dtype=float)
186 weightArr[good] = 1./fit[1]
188 applyMaxSNR(imArr, weightArr, good, maxSNR)
189 return weightArr
192def applyMaxSNR(imArr, weightArr, good, maxSNR):
193 """Rescale weight of bright stars to cap the computed SNR.
195 Parameters
196 ----------
197 imArr : `ndarray`
198 Signal (image) array of stamp.
199 weightArr : `ndarray`
200 Weight map array. May be rescaled in place.
201 good : `ndarray`
202 Index array of pixels to use when computing SNR.
203 maxSNR : `float`
204 Threshold for adjusting variance plane implementing maximum SNR.
205 """
206 # We define the SNR value following Piff. Here's the comment from that
207 # code base explaining the calculation.
208 #
209 # The S/N value that we use will be the weighted total flux where the
210 # weight function is the star's profile itself. This is the maximum S/N
211 # value that any flux measurement can possibly produce, which will be
212 # closer to an in-practice S/N than using all the pixels equally.
213 #
214 # F = Sum_i w_i I_i^2
215 # var(F) = Sum_i w_i^2 I_i^2 var(I_i)
216 # = Sum_i w_i I_i^2 <--- Assumes var(I_i) = 1/w_i
217 #
218 # S/N = F / sqrt(var(F))
219 #
220 # Note that if the image is pure noise, this will produce a "signal" of
221 #
222 # F_noise = Sum_i w_i 1/w_i = Npix
223 #
224 # So for a more accurate estimate of the S/N of the actual star itself, one
225 # should subtract off Npix from the measured F.
226 #
227 # The final formula then is:
228 #
229 # F = Sum_i w_i I_i^2
230 # S/N = (F-Npix) / sqrt(F)
231 F = np.sum(weightArr[good]*imArr[good]**2, dtype=float)
232 Npix = np.sum(good)
233 SNR = 0.0 if F < Npix else (F-Npix)/np.sqrt(F)
234 # rescale weight of bright stars. Essentially makes an error floor.
235 if SNR > maxSNR:
236 factor = (maxSNR / SNR)**2
237 weightArr[good] *= factor
240def _computeWeightAlternative(maskedImage, maxSNR):
241 """Alternative algorithm for creating weight map.
243 This version is equivalent to that used by Piff internally. The weight map
244 it produces tends to leave a residual when removing the Poisson component
245 due to the signal. We leave it here as a reference, but without intending
246 that it be used (or be maintained).
247 """
248 imArr = maskedImage.image.array
249 varArr = maskedImage.variance.array
250 good = (varArr != 0) & np.isfinite(varArr) & np.isfinite(imArr)
252 fit = np.polyfit(imArr[good], varArr[good], deg=1)
253 # fit is [1/gain, sky_var]
254 gain = 1./fit[0]
255 varArr[good] -= imArr[good] / gain
256 weightArr = np.zeros_like(imArr, dtype=float)
257 weightArr[good] = 1./varArr[good]
259 applyMaxSNR(imArr, weightArr, good, maxSNR)
260 return weightArr
263class PiffPsfDeterminerTask(BasePsfDeterminerTask):
264 """A measurePsfTask PSF estimator using Piff as the implementation.
265 """
266 ConfigClass = PiffPsfDeterminerConfig
267 _DefaultName = "psfDeterminer.Piff"
269 def determinePsf(
270 self, exposure, psfCandidateList, metadata=None, flagKey=None
271 ):
272 """Determine a Piff PSF model for an exposure given a list of PSF
273 candidates.
275 Parameters
276 ----------
277 exposure : `lsst.afw.image.Exposure`
278 Exposure containing the PSF candidates.
279 psfCandidateList : `list` of `lsst.meas.algorithms.PsfCandidate`
280 A sequence of PSF candidates typically obtained by detecting sources
281 and then running them through a star selector.
282 metadata : `lsst.daf.base import PropertyList` or `None`, optional
283 A home for interesting tidbits of information.
284 flagKey : `str` or `None`, optional
285 Schema key used to mark sources actually used in PSF determination.
287 Returns
288 -------
289 psf : `lsst.meas.extensions.piff.PiffPsf`
290 The measured PSF model.
291 psfCellSet : `None`
292 Unused by this PsfDeterminer.
293 """
294 if self.config.stampSize:
295 stampSize = self.config.stampSize
296 if stampSize > psfCandidateList[0].getWidth():
297 self.log.warning("stampSize is larger than the PSF candidate size. Using candidate size.")
298 stampSize = psfCandidateList[0].getWidth()
299 else: # TODO: Only the if block should stay after DM-36311
300 self.log.debug("stampSize not set. Using candidate size.")
301 stampSize = psfCandidateList[0].getWidth()
303 self._validatePsfCandidates(psfCandidateList, stampSize)
305 scale = exposure.getWcs().getPixelScale().asArcseconds()
306 match self.config.useCoordinates:
307 case 'field':
308 detector = exposure.getDetector()
309 pix_to_field = detector.getTransform(PIXELS, FIELD_ANGLE)
310 gswcs = UVWcsWrapper(pix_to_field)
311 pointing = None
312 case 'sky':
313 gswcs = CelestialWcsWrapper(exposure.getWcs())
314 skyOrigin = exposure.getWcs().getSkyOrigin()
315 ra = skyOrigin.getLongitude().asDegrees()
316 dec = skyOrigin.getLatitude().asDegrees()
317 pointing = galsim.CelestialCoord(
318 ra*galsim.degrees,
319 dec*galsim.degrees
320 )
321 case 'pixel':
322 gswcs = galsim.PixelScale(scale)
323 pointing = None
325 stars = []
326 for candidate in psfCandidateList:
327 cmi = candidate.getMaskedImage(stampSize, stampSize)
328 good = getGoodPixels(cmi, self.config.zeroWeightMaskBits)
329 fracGood = np.sum(good)/good.size
330 if fracGood < self.config.minimumUnmaskedFraction:
331 continue
332 weight = computeWeight(cmi, self.config.maxSNR, good)
334 bbox = cmi.getBBox()
335 bds = galsim.BoundsI(
336 galsim.PositionI(*bbox.getMin()),
337 galsim.PositionI(*bbox.getMax())
338 )
339 gsImage = galsim.Image(bds, wcs=gswcs, dtype=float)
340 gsImage.array[:] = cmi.image.array
341 gsWeight = galsim.Image(bds, wcs=gswcs, dtype=float)
342 gsWeight.array[:] = weight
344 source = candidate.getSource()
345 image_pos = galsim.PositionD(source.getX(), source.getY())
347 data = piff.StarData(
348 gsImage,
349 image_pos,
350 weight=gsWeight,
351 pointing=pointing
352 )
353 stars.append(piff.Star(data, None))
355 piffConfig = {
356 'type': "Simple",
357 'model': {
358 'type': 'PixelGrid',
359 'scale': scale * self.config.samplingSize,
360 'size': stampSize,
361 'interp': self.config.interpolant
362 },
363 'interp': {
364 'type': 'BasisPolynomial',
365 'order': self.config.spatialOrder
366 },
367 'outliers': {
368 'type': 'Chisq',
369 'nsigma': self.config.outlierNSigma,
370 'max_remove': self.config.outlierMaxRemove
371 }
372 }
374 piffResult = piff.PSF.process(piffConfig)
375 wcs = {0: gswcs}
377 piffResult.fit(stars, wcs, pointing, logger=self.log)
378 drawSize = 2*np.floor(0.5*stampSize/self.config.samplingSize) + 1
380 used_image_pos = [s.image_pos for s in piffResult.stars]
381 if flagKey:
382 for candidate in psfCandidateList:
383 source = candidate.getSource()
384 posd = galsim.PositionD(source.getX(), source.getY())
385 if posd in used_image_pos:
386 source.set(flagKey, True)
388 if metadata is not None:
389 metadata["spatialFitChi2"] = piffResult.chisq
390 metadata["numAvailStars"] = len(stars)
391 metadata["numGoodStars"] = len(piffResult.stars)
392 metadata["avgX"] = np.mean([p.x for p in piffResult.stars])
393 metadata["avgY"] = np.mean([p.y for p in piffResult.stars])
395 if not self.config.debugStarData:
396 for star in piffResult.stars:
397 # Remove large data objects from the stars
398 del star.fit.params
399 del star.fit.params_var
400 del star.fit.A
401 del star.fit.b
402 del star.data.image
403 del star.data.weight
404 del star.data.orig_weight
406 return PiffPsf(drawSize, drawSize, piffResult), None
408 # TODO: DM-36311: This method can be removed.
409 @staticmethod
410 def _validatePsfCandidates(psfCandidateList, stampSize):
411 """Raise if psfCandidates are smaller than the configured kernelSize.
413 Parameters
414 ----------
415 psfCandidateList : `list` of `lsst.meas.algorithms.PsfCandidate`
416 Sequence of psf candidates to check.
417 stampSize : `int`
418 Size of image model to use in PIFF.
420 Raises
421 ------
422 RuntimeError
423 Raised if any psfCandidate has width or height smaller than
424 ``stampSize``.
425 """
426 # All candidates will necessarily have the same dimensions.
427 candidate = psfCandidateList[0]
428 if (candidate.getHeight() < stampSize
429 or candidate.getWidth() < stampSize):
430 raise RuntimeError(f"PSF candidates must be at least {stampSize=} pixels per side; "
431 f"found {candidate.getWidth()}x{candidate.getHeight()}."
432 )
435measAlg.psfDeterminerRegistry.register("piff", PiffPsfDeterminerTask)