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

112 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2022-11-06 13:26 -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( 

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

72 dtype=int, 

73 default=2, 

74 ) 

75 samplingSize = pexConfig.Field( 

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

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

78 dtype=float, 

79 default=1, 

80 ) 

81 outlierNSigma = pexConfig.Field( 

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

83 dtype=float, 

84 default=4.0 

85 ) 

86 outlierMaxRemove = pexConfig.Field( 

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

88 dtype=float, 

89 default=0.05 

90 ) 

91 maxSNR = pexConfig.Field( 

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

93 "than this value.", 

94 dtype=float, 

95 default=200.0 

96 ) 

97 zeroWeightMaskBits = pexConfig.ListField( 

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

99 dtype=str, 

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

101 ) 

102 minimumUnmaskedFraction = pexConfig.Field( 

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

104 dtype=float, 

105 default=0.5 

106 ) 

107 interpolant = pexConfig.Field( 

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

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

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

111 "galsim.Quintic, and galsim.SincInterpolant.", 

112 dtype=str, 

113 check=_validateGalsimInterpolant, 

114 default="Lanczos(11)", 

115 ) 

116 

117 def setDefaults(self): 

118 # kernelSize should be at least 25 so that 

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

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

121 # measured correctly 

122 self.kernelSize = 25 

123 self.kernelSizeMin = 11 

124 self.kernelSizeMax = 35 

125 

126 

127def getGoodPixels(maskedImage, zeroWeightMaskBits): 

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

129 

130 Parameters 

131 ---------- 

132 maskedImage : `afw.image.MaskedImage` 

133 PSF candidate postage stamp 

134 zeroWeightMaskBits : `List[str]` 

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

136 

137 Returns 

138 ------- 

139 good : `ndarray` 

140 Index array indicating good pixels. 

141 """ 

142 imArr = maskedImage.image.array 

143 varArr = maskedImage.variance.array 

144 bitmask = maskedImage.mask.getPlaneBitMask(zeroWeightMaskBits) 

145 good = ( 

146 (varArr != 0) 

147 & (np.isfinite(varArr)) 

148 & (np.isfinite(imArr)) 

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

150 ) 

151 return good 

152 

153 

154def computeWeight(maskedImage, maxSNR, good): 

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

156 

157 Parameters 

158 ---------- 

159 maskedImage : `afw.image.MaskedImage` 

160 PSF candidate postage stamp 

161 maxSNR : `float` 

162 Maximum SNR applying variance floor. 

163 good : `ndarray` 

164 Index array indicating good pixels. 

165 

166 Returns 

167 ------- 

168 weightArr : `ndarry` 

169 Array to use for weight. 

170 """ 

171 imArr = maskedImage.image.array 

172 varArr = maskedImage.variance.array 

173 

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

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

176 # signal-free variance. 

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

178 # fit is [1/gain, sky_var] 

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

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

181 

182 applyMaxSNR(imArr, weightArr, good, maxSNR) 

183 return weightArr 

184 

185 

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

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

188 

189 Parameters 

190 ---------- 

191 imArr : `ndarray` 

192 Signal (image) array of stamp. 

193 weightArr : `ndarray` 

194 Weight map array. May be rescaled in place. 

195 good : `ndarray` 

196 Index array of pixels to use when computing SNR. 

197 maxSNR : `float` 

198 Threshold for adjusting variance plane implementing maximum SNR. 

199 """ 

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

201 # code base explaining the calculation. 

202 # 

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

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

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

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

207 # 

208 # F = Sum_i w_i I_i^2 

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

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

211 # 

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

213 # 

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

215 # 

216 # F_noise = Sum_i w_i 1/w_i = Npix 

217 # 

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

219 # should subtract off Npix from the measured F. 

220 # 

221 # The final formula then is: 

222 # 

223 # F = Sum_i w_i I_i^2 

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

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

226 Npix = np.sum(good) 

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

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

229 if SNR > maxSNR: 

230 factor = (maxSNR / SNR)**2 

231 weightArr[good] *= factor 

232 

233 

234def _computeWeightAlternative(maskedImage, maxSNR): 

235 """Alternative algorithm for creating weight map. 

236 

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

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

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

240 that it be used (or be maintained). 

241 """ 

242 imArr = maskedImage.image.array 

243 varArr = maskedImage.variance.array 

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

245 

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

247 # fit is [1/gain, sky_var] 

248 gain = 1./fit[0] 

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

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

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

252 

253 applyMaxSNR(imArr, weightArr, good, maxSNR) 

254 return weightArr 

255 

256 

257class PiffPsfDeterminerTask(BasePsfDeterminerTask): 

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

259 """ 

260 ConfigClass = PiffPsfDeterminerConfig 

261 _DefaultName = "psfDeterminer.Piff" 

262 

263 def determinePsf( 

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

265 ): 

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

267 candidates. 

268 

269 Parameters 

270 ---------- 

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

272 Exposure containing the PSF candidates. 

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

274 A sequence of PSF candidates typically obtained by detecting sources 

275 and then running them through a star selector. 

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

277 A home for interesting tidbits of information. 

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

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

280 

281 Returns 

282 ------- 

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

284 The measured PSF model. 

285 psfCellSet : `None` 

286 Unused by this PsfDeterminer. 

287 """ 

288 kernelSize = int(np.clip( 

289 self.config.kernelSize, 

290 self.config.kernelSizeMin, 

291 self.config.kernelSizeMax 

292 )) 

293 self._validatePsfCandidates(psfCandidateList, kernelSize, self.config.samplingSize) 

294 

295 stars = [] 

296 for candidate in psfCandidateList: 

297 cmi = candidate.getMaskedImage() 

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

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

300 if fracGood < self.config.minimumUnmaskedFraction: 

301 continue 

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

303 

304 bbox = cmi.getBBox() 

305 bds = galsim.BoundsI( 

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

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

308 ) 

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

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

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

312 gsWeight.array[:] = weight 

313 

314 source = candidate.getSource() 

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

316 

317 data = piff.StarData( 

318 gsImage, 

319 image_pos, 

320 weight=gsWeight 

321 ) 

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

323 

324 piffConfig = { 

325 'type': "Simple", 

326 'model': { 

327 'type': 'PixelGrid', 

328 'scale': self.config.samplingSize, 

329 'size': kernelSize, 

330 'interp': self.config.interpolant 

331 }, 

332 'interp': { 

333 'type': 'BasisPolynomial', 

334 'order': self.config.spatialOrder 

335 }, 

336 'outliers': { 

337 'type': 'Chisq', 

338 'nsigma': self.config.outlierNSigma, 

339 'max_remove': self.config.outlierMaxRemove 

340 } 

341 } 

342 

343 piffResult = piff.PSF.process(piffConfig) 

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

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

346 pointing = None 

347 

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

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

350 psf = PiffPsf(drawSize, drawSize, piffResult) 

351 

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

353 if flagKey: 

354 for candidate in psfCandidateList: 

355 source = candidate.getSource() 

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

357 if posd in used_image_pos: 

358 source.set(flagKey, True) 

359 

360 if metadata is not None: 

361 metadata["spatialFitChi2"] = piffResult.chisq 

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

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

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

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

366 

367 return psf, None 

368 

369 def _validatePsfCandidates(self, psfCandidateList, kernelSize, samplingSize): 

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

371 

372 Parameters 

373 ---------- 

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

375 Sequence of psf candidates to check. 

376 kernelSize : `int` 

377 Size of image model to use in PIFF. 

378 samplingSize : `float` 

379 Resolution of the internal PSF model relative to the pixel size. 

380 

381 Raises 

382 ------ 

383 RuntimeError 

384 Raised if any psfCandidate has width or height smaller than 

385 config.kernelSize. 

386 """ 

387 # We can assume all candidates have the same dimensions. 

388 candidate = psfCandidateList[0] 

389 drawSize = int(2*np.floor(0.5*kernelSize/samplingSize) + 1) 

390 if (candidate.getHeight() < drawSize 

391 or candidate.getWidth() < drawSize): 

392 raise RuntimeError("PSF candidates must be at least config.kernelSize/config.samplingSize=" 

393 f"{drawSize} pixels per side; " 

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

395 

396 

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