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

138 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2023-09-12 10:59 +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/>. 

21 

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

23 

24import numpy as np 

25import piff 

26import galsim 

27import re 

28 

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 

35 

36 

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

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

39 

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 

51 

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) 

63 

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 

69 

70 

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 ) 

123 

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 

131 

132 

133def getGoodPixels(maskedImage, zeroWeightMaskBits): 

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

135 

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. 

142 

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 

158 

159 

160def computeWeight(maskedImage, maxSNR, good): 

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

162 

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. 

171 

172 Returns 

173 ------- 

174 weightArr : `ndarry` 

175 Array to use for weight. 

176 """ 

177 imArr = maskedImage.image.array 

178 varArr = maskedImage.variance.array 

179 

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] 

187 

188 applyMaxSNR(imArr, weightArr, good, maxSNR) 

189 return weightArr 

190 

191 

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

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

194 

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 

238 

239 

240def _computeWeightAlternative(maskedImage, maxSNR): 

241 """Alternative algorithm for creating weight map. 

242 

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) 

251 

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] 

258 

259 applyMaxSNR(imArr, weightArr, good, maxSNR) 

260 return weightArr 

261 

262 

263class PiffPsfDeterminerTask(BasePsfDeterminerTask): 

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

265 """ 

266 ConfigClass = PiffPsfDeterminerConfig 

267 _DefaultName = "psfDeterminer.Piff" 

268 

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. 

274 

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. 

286 

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() 

302 

303 scale = exposure.getWcs().getPixelScale().asArcseconds() 

304 match self.config.useCoordinates: 

305 case 'field': 

306 detector = exposure.getDetector() 

307 pix_to_field = detector.getTransform(PIXELS, FIELD_ANGLE) 

308 gswcs = UVWcsWrapper(pix_to_field) 

309 pointing = None 

310 case 'sky': 

311 gswcs = CelestialWcsWrapper(exposure.getWcs()) 

312 skyOrigin = exposure.getWcs().getSkyOrigin() 

313 ra = skyOrigin.getLongitude().asDegrees() 

314 dec = skyOrigin.getLatitude().asDegrees() 

315 pointing = galsim.CelestialCoord( 

316 ra*galsim.degrees, 

317 dec*galsim.degrees 

318 ) 

319 case 'pixel': 

320 gswcs = galsim.PixelScale(scale) 

321 pointing = None 

322 

323 stars = [] 

324 for candidate in psfCandidateList: 

325 cmi = candidate.getMaskedImage(stampSize, stampSize) 

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

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

328 if fracGood < self.config.minimumUnmaskedFraction: 

329 continue 

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

331 

332 bbox = cmi.getBBox() 

333 bds = galsim.BoundsI( 

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

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

336 ) 

337 gsImage = galsim.Image(bds, wcs=gswcs, dtype=float) 

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

339 gsWeight = galsim.Image(bds, wcs=gswcs, dtype=float) 

340 gsWeight.array[:] = weight 

341 

342 source = candidate.getSource() 

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

344 

345 data = piff.StarData( 

346 gsImage, 

347 image_pos, 

348 weight=gsWeight, 

349 pointing=pointing 

350 ) 

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

352 

353 piffConfig = { 

354 'type': "Simple", 

355 'model': { 

356 'type': 'PixelGrid', 

357 'scale': scale * self.config.samplingSize, 

358 'size': stampSize, 

359 'interp': self.config.interpolant 

360 }, 

361 'interp': { 

362 'type': 'BasisPolynomial', 

363 'order': self.config.spatialOrder 

364 }, 

365 'outliers': { 

366 'type': 'Chisq', 

367 'nsigma': self.config.outlierNSigma, 

368 'max_remove': self.config.outlierMaxRemove 

369 } 

370 } 

371 

372 piffResult = piff.PSF.process(piffConfig) 

373 wcs = {0: gswcs} 

374 

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

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

377 

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

379 if flagKey: 

380 for candidate in psfCandidateList: 

381 source = candidate.getSource() 

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

383 if posd in used_image_pos: 

384 source.set(flagKey, True) 

385 

386 if metadata is not None: 

387 metadata["spatialFitChi2"] = piffResult.chisq 

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

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

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

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

392 

393 if not self.config.debugStarData: 

394 for star in piffResult.stars: 

395 # Remove large data objects from the stars 

396 del star.fit.params 

397 del star.fit.params_var 

398 del star.fit.A 

399 del star.fit.b 

400 del star.data.image 

401 del star.data.weight 

402 del star.data.orig_weight 

403 

404 return PiffPsf(drawSize, drawSize, piffResult), None 

405 

406 

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