Coverage for python/lsst/meas/extensions/piff/piffPsfDeterminer.py: 21%

117 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2022-11-12 03:00 -0800

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/>. 

21 

22__all__ = ["PiffPsfDeterminerConfig", "PiffPsfDeterminerTask"] 

23 

24import numpy as np 

25import piff 

26import galsim 

27import re 

28 

29import lsst.pex.config as pexConfig 

30import lsst.meas.algorithms as measAlg 

31from lsst.meas.algorithms.psfDeterminer import BasePsfDeterminerTask 

32from .piffPsf import PiffPsf 

33 

34 

35def _validateGalsimInterpolant(name: str) -> bool: 

36 """A helper function to validate the GalSim interpolant at config time. 

37 

38 Parameters 

39 ---------- 

40 name : str 

41 The name of the interpolant to use from GalSim. Valid options are: 

42 galsim.Lanczos(N) or Lancsos(N), where N is a positive integer 

43 galsim.Linear 

44 galsim.Cubic 

45 galsim.Quintic 

46 galsim.Delta 

47 galsim.Nearest 

48 galsim.SincInterpolant 

49 

50 Returns 

51 ------- 

52 is_valid : bool 

53 Whether the provided interpolant name is valid. 

54 """ 

55 # First, check if ``name`` is a valid Lanczos interpolant. 

56 for pattern in (re.compile(r"Lanczos\(\d+\)"), re.compile(r"galsim.Lanczos\(\d+\)"),): 

57 match = re.match(pattern, name) # Search from the start of the string. 

58 if match is not None: 

59 # Check that the pattern is also the end of the string. 

60 return match.end() == len(name) 

61 

62 # If not, check if ``name`` is any other valid GalSim interpolant. 

63 names = {f"galsim.{interp}" for interp in 

64 ("Cubic", "Delta", "Linear", "Nearest", "Quintic", "SincInterpolant") 

65 } 

66 return name in names 

67 

68 

69class PiffPsfDeterminerConfig(BasePsfDeterminerTask.ConfigClass): 

70 spatialOrder = pexConfig.Field[int]( 

71 doc="specify spatial order for PSF kernel creation", 

72 default=2, 

73 ) 

74 samplingSize = pexConfig.Field[float]( 

75 doc="Resolution of the internal PSF model relative to the pixel size; " 

76 "e.g. 0.5 is equal to 2x oversampling", 

77 default=1, 

78 ) 

79 outlierNSigma = pexConfig.Field[float]( 

80 doc="n sigma for chisq outlier rejection", 

81 default=4.0 

82 ) 

83 outlierMaxRemove = pexConfig.Field[float]( 

84 doc="Max fraction of stars to remove as outliers each iteration", 

85 default=0.05 

86 ) 

87 maxSNR = pexConfig.Field[float]( 

88 doc="Rescale the weight of bright stars such that their SNR is less " 

89 "than this value.", 

90 default=200.0 

91 ) 

92 zeroWeightMaskBits = pexConfig.ListField[str]( 

93 doc="List of mask bits for which to set pixel weights to zero.", 

94 default=['BAD', 'CR', 'INTRP', 'SAT', 'SUSPECT', 'NO_DATA'] 

95 ) 

96 minimumUnmaskedFraction = pexConfig.Field[float]( 

97 doc="Minimum fraction of unmasked pixels required to use star.", 

98 default=0.5 

99 ) 

100 interpolant = pexConfig.Field[str]( 

101 doc="GalSim interpolant name for Piff to use. " 

102 "Options include 'Lanczos(N)', where N is an integer, along with " 

103 "galsim.Cubic, galsim.Delta, galsim.Linear, galsim.Nearest, " 

104 "galsim.Quintic, and galsim.SincInterpolant.", 

105 check=_validateGalsimInterpolant, 

106 default="Lanczos(11)", 

107 ) 

108 

109 def setDefaults(self): 

110 super().setDefaults() 

111 # stampSize should be at least 25 so that 

112 # i) aperture flux with 12 pixel radius can be compared to PSF flux. 

113 # ii) fake sources injected to match the 12 pixel aperture flux get 

114 # measured correctly 

115 self.stampSize = 25 

116 

117 

118def getGoodPixels(maskedImage, zeroWeightMaskBits): 

119 """Compute an index array indicating good pixels to use. 

120 

121 Parameters 

122 ---------- 

123 maskedImage : `afw.image.MaskedImage` 

124 PSF candidate postage stamp 

125 zeroWeightMaskBits : `List[str]` 

126 List of mask bits for which to set pixel weights to zero. 

127 

128 Returns 

129 ------- 

130 good : `ndarray` 

131 Index array indicating good pixels. 

132 """ 

133 imArr = maskedImage.image.array 

134 varArr = maskedImage.variance.array 

135 bitmask = maskedImage.mask.getPlaneBitMask(zeroWeightMaskBits) 

136 good = ( 

137 (varArr != 0) 

138 & (np.isfinite(varArr)) 

139 & (np.isfinite(imArr)) 

140 & ((maskedImage.mask.array & bitmask) == 0) 

141 ) 

142 return good 

143 

144 

145def computeWeight(maskedImage, maxSNR, good): 

146 """Derive a weight map without Poisson variance component due to signal. 

147 

148 Parameters 

149 ---------- 

150 maskedImage : `afw.image.MaskedImage` 

151 PSF candidate postage stamp 

152 maxSNR : `float` 

153 Maximum SNR applying variance floor. 

154 good : `ndarray` 

155 Index array indicating good pixels. 

156 

157 Returns 

158 ------- 

159 weightArr : `ndarry` 

160 Array to use for weight. 

161 """ 

162 imArr = maskedImage.image.array 

163 varArr = maskedImage.variance.array 

164 

165 # Fit a straight line to variance vs (sky-subtracted) signal. 

166 # The evaluate that line at zero signal to get an estimate of the 

167 # signal-free variance. 

168 fit = np.polyfit(imArr[good], varArr[good], deg=1) 

169 # fit is [1/gain, sky_var] 

170 weightArr = np.zeros_like(imArr, dtype=float) 

171 weightArr[good] = 1./fit[1] 

172 

173 applyMaxSNR(imArr, weightArr, good, maxSNR) 

174 return weightArr 

175 

176 

177def applyMaxSNR(imArr, weightArr, good, maxSNR): 

178 """Rescale weight of bright stars to cap the computed SNR. 

179 

180 Parameters 

181 ---------- 

182 imArr : `ndarray` 

183 Signal (image) array of stamp. 

184 weightArr : `ndarray` 

185 Weight map array. May be rescaled in place. 

186 good : `ndarray` 

187 Index array of pixels to use when computing SNR. 

188 maxSNR : `float` 

189 Threshold for adjusting variance plane implementing maximum SNR. 

190 """ 

191 # We define the SNR value following Piff. Here's the comment from that 

192 # code base explaining the calculation. 

193 # 

194 # The S/N value that we use will be the weighted total flux where the 

195 # weight function is the star's profile itself. This is the maximum S/N 

196 # value that any flux measurement can possibly produce, which will be 

197 # closer to an in-practice S/N than using all the pixels equally. 

198 # 

199 # F = Sum_i w_i I_i^2 

200 # var(F) = Sum_i w_i^2 I_i^2 var(I_i) 

201 # = Sum_i w_i I_i^2 <--- Assumes var(I_i) = 1/w_i 

202 # 

203 # S/N = F / sqrt(var(F)) 

204 # 

205 # Note that if the image is pure noise, this will produce a "signal" of 

206 # 

207 # F_noise = Sum_i w_i 1/w_i = Npix 

208 # 

209 # So for a more accurate estimate of the S/N of the actual star itself, one 

210 # should subtract off Npix from the measured F. 

211 # 

212 # The final formula then is: 

213 # 

214 # F = Sum_i w_i I_i^2 

215 # S/N = (F-Npix) / sqrt(F) 

216 F = np.sum(weightArr[good]*imArr[good]**2, dtype=float) 

217 Npix = np.sum(good) 

218 SNR = 0.0 if F < Npix else (F-Npix)/np.sqrt(F) 

219 # rescale weight of bright stars. Essentially makes an error floor. 

220 if SNR > maxSNR: 

221 factor = (maxSNR / SNR)**2 

222 weightArr[good] *= factor 

223 

224 

225def _computeWeightAlternative(maskedImage, maxSNR): 

226 """Alternative algorithm for creating weight map. 

227 

228 This version is equivalent to that used by Piff internally. The weight map 

229 it produces tends to leave a residual when removing the Poisson component 

230 due to the signal. We leave it here as a reference, but without intending 

231 that it be used (or be maintained). 

232 """ 

233 imArr = maskedImage.image.array 

234 varArr = maskedImage.variance.array 

235 good = (varArr != 0) & np.isfinite(varArr) & np.isfinite(imArr) 

236 

237 fit = np.polyfit(imArr[good], varArr[good], deg=1) 

238 # fit is [1/gain, sky_var] 

239 gain = 1./fit[0] 

240 varArr[good] -= imArr[good] / gain 

241 weightArr = np.zeros_like(imArr, dtype=float) 

242 weightArr[good] = 1./varArr[good] 

243 

244 applyMaxSNR(imArr, weightArr, good, maxSNR) 

245 return weightArr 

246 

247 

248class PiffPsfDeterminerTask(BasePsfDeterminerTask): 

249 """A measurePsfTask PSF estimator using Piff as the implementation. 

250 """ 

251 ConfigClass = PiffPsfDeterminerConfig 

252 _DefaultName = "psfDeterminer.Piff" 

253 

254 def determinePsf( 

255 self, exposure, psfCandidateList, metadata=None, flagKey=None 

256 ): 

257 """Determine a Piff PSF model for an exposure given a list of PSF 

258 candidates. 

259 

260 Parameters 

261 ---------- 

262 exposure : `lsst.afw.image.Exposure` 

263 Exposure containing the PSF candidates. 

264 psfCandidateList : `list` of `lsst.meas.algorithms.PsfCandidate` 

265 A sequence of PSF candidates typically obtained by detecting sources 

266 and then running them through a star selector. 

267 metadata : `lsst.daf.base import PropertyList` or `None`, optional 

268 A home for interesting tidbits of information. 

269 flagKey : `str` or `None`, optional 

270 Schema key used to mark sources actually used in PSF determination. 

271 

272 Returns 

273 ------- 

274 psf : `lsst.meas.extensions.piff.PiffPsf` 

275 The measured PSF model. 

276 psfCellSet : `None` 

277 Unused by this PsfDeterminer. 

278 """ 

279 if self.config.stampSize: 

280 stampSize = self.config.stampSize 

281 if stampSize > psfCandidateList[0].getWidth(): 

282 self.log.warning("stampSize is larger than the PSF candidate size. Using candidate size.") 

283 stampSize = psfCandidateList[0].getWidth() 

284 else: # TODO: Only the if block should stay after DM-36311 

285 self.log.debug("stampSize not set. Using candidate size.") 

286 stampSize = psfCandidateList[0].getWidth() 

287 

288 self._validatePsfCandidates(psfCandidateList, stampSize) 

289 

290 stars = [] 

291 for candidate in psfCandidateList: 

292 cmi = candidate.getMaskedImage(stampSize, stampSize) 

293 good = getGoodPixels(cmi, self.config.zeroWeightMaskBits) 

294 fracGood = np.sum(good)/good.size 

295 if fracGood < self.config.minimumUnmaskedFraction: 

296 continue 

297 weight = computeWeight(cmi, self.config.maxSNR, good) 

298 

299 bbox = cmi.getBBox() 

300 bds = galsim.BoundsI( 

301 galsim.PositionI(*bbox.getMin()), 

302 galsim.PositionI(*bbox.getMax()) 

303 ) 

304 gsImage = galsim.Image(bds, scale=1.0, dtype=float) 

305 gsImage.array[:] = cmi.image.array 

306 gsWeight = galsim.Image(bds, scale=1.0, dtype=float) 

307 gsWeight.array[:] = weight 

308 

309 source = candidate.getSource() 

310 image_pos = galsim.PositionD(source.getX(), source.getY()) 

311 

312 data = piff.StarData( 

313 gsImage, 

314 image_pos, 

315 weight=gsWeight 

316 ) 

317 stars.append(piff.Star(data, None)) 

318 

319 piffConfig = { 

320 'type': "Simple", 

321 'model': { 

322 'type': 'PixelGrid', 

323 'scale': self.config.samplingSize, 

324 'size': stampSize, 

325 'interp': self.config.interpolant 

326 }, 

327 'interp': { 

328 'type': 'BasisPolynomial', 

329 'order': self.config.spatialOrder 

330 }, 

331 'outliers': { 

332 'type': 'Chisq', 

333 'nsigma': self.config.outlierNSigma, 

334 'max_remove': self.config.outlierMaxRemove 

335 } 

336 } 

337 

338 piffResult = piff.PSF.process(piffConfig) 

339 # Run on a single CCD, and in image coords rather than sky coords. 

340 wcs = {0: galsim.PixelScale(1.0)} 

341 pointing = None 

342 

343 piffResult.fit(stars, wcs, pointing, logger=self.log) 

344 drawSize = 2*np.floor(0.5*stampSize/self.config.samplingSize) + 1 

345 psf = PiffPsf(drawSize, drawSize, piffResult) 

346 

347 used_image_pos = [s.image_pos for s in piffResult.stars] 

348 if flagKey: 

349 for candidate in psfCandidateList: 

350 source = candidate.getSource() 

351 posd = galsim.PositionD(source.getX(), source.getY()) 

352 if posd in used_image_pos: 

353 source.set(flagKey, True) 

354 

355 if metadata is not None: 

356 metadata["spatialFitChi2"] = piffResult.chisq 

357 metadata["numAvailStars"] = len(stars) 

358 metadata["numGoodStars"] = len(piffResult.stars) 

359 metadata["avgX"] = np.mean([p.x for p in piffResult.stars]) 

360 metadata["avgY"] = np.mean([p.y for p in piffResult.stars]) 

361 

362 return psf, None 

363 

364 # TODO: DM-36311: This method can be removed. 

365 @staticmethod 

366 def _validatePsfCandidates(psfCandidateList, stampSize): 

367 """Raise if psfCandidates are smaller than the configured kernelSize. 

368 

369 Parameters 

370 ---------- 

371 psfCandidateList : `list` of `lsst.meas.algorithms.PsfCandidate` 

372 Sequence of psf candidates to check. 

373 stampSize : `int` 

374 Size of image model to use in PIFF. 

375 

376 Raises 

377 ------ 

378 RuntimeError 

379 Raised if any psfCandidate has width or height smaller than 

380 ``stampSize``. 

381 """ 

382 # All candidates will necessarily have the same dimensions. 

383 candidate = psfCandidateList[0] 

384 if (candidate.getHeight() < stampSize 

385 or candidate.getWidth() < stampSize): 

386 raise RuntimeError(f"PSF candidates must be at least {stampSize=} pixels per side; " 

387 f"found {candidate.getWidth()}x{candidate.getHeight()}." 

388 ) 

389 

390 

391measAlg.psfDeterminerRegistry.register("piff", PiffPsfDeterminerTask)