Coverage for python/lsst/pipe/tasks/diffractionSpikeMask.py: 90%

160 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-26 07:22 +0000

1# This file is part of pipe_tasks. 

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 

23__all__ = ["DiffractionSpikeMaskConfig", "DiffractionSpikeMaskTask"] 

24 

25 

26import math 

27import numpy as np 

28import astropy.units as u 

29 

30import lsst.afw.geom as afwGeom 

31from lsst.afw.image import abMagErrFromFluxErr 

32import lsst.afw.table as afwTable 

33import lsst.geom 

34from lsst.pex.config import Config, ConfigField, Field 

35from lsst.pipe.base import Struct, Task 

36from lsst.meas.algorithms import getRefFluxField, LoadReferenceObjectsConfig 

37from lsst.utils.timer import timeMethod 

38import lsst.sphgeom 

39from .colorterms import ColortermLibrary 

40 

41 

42class DiffractionSpikeMaskConfig(Config): 

43 """Config for BrightStarMaskTask. 

44 """ 

45 refObjLoader = ConfigField(dtype=LoadReferenceObjectsConfig, 

46 doc="Configuration of reference object loader") 

47 applyColorTerms = Field( 

48 dtype=bool, 

49 default=False, 

50 doc=("Apply photometric color terms to reference stars?\n" 

51 "`True`: attempt to apply color terms; fail if color term data is " 

52 "not available for the specified reference catalog and filter.\n" 

53 "`False`: do not apply color terms."), 

54 optional=True, 

55 ) 

56 colorterms = ConfigField( 

57 dtype=ColortermLibrary, 

58 doc="Library of photometric reference catalog name: color term dict" 

59 " (see also applyColorTerms).", 

60 ) 

61 photoCatName = Field( 

62 dtype=str, 

63 optional=True, 

64 doc=("Name of photometric reference catalog; used to select a color" 

65 " term dict in colorterms. See also applyColorTerms."), 

66 ) 

67 raKey = Field( 

68 dtype=str, 

69 default="coord_ra", 

70 doc="RA column name in the reference catalog.", 

71 ) 

72 decKey = Field( 

73 dtype=str, 

74 default="coord_dec", 

75 doc="Declination column name in the reference catalog.", 

76 ) 

77 angleMargin = Field( 

78 dtype=float, 

79 default=60., 

80 doc="Margin outside the exposure bounding box to include bright " 

81 "sources. In arcseconds.", 

82 ) 

83 magnitudeThreshold = Field( 

84 dtype=float, 

85 default=15, 

86 doc="Threshold magnitude for treating a star from the reference catalog" 

87 " as bright.", 

88 ) 

89 diffractAngle = Field( 

90 dtype=float, 

91 default=45, 

92 doc="Angle in degrees of the location of diffraction spikes with " 

93 "respect to camera at 0 rotation angle.", 

94 ) 

95 spikeAspectRatio = Field( 

96 dtype=float, 

97 default=10, 

98 doc="Ratio of the length of a diffraction spike to it's width in the" 

99 " core of the star.", 

100 ) 

101 magSlope = Field( 

102 dtype=float, 

103 default=-0.12, 

104 doc="Slope of the fit for the log(spike length) as a function of" 

105 " magnitude.", 

106 ) 

107 magOffset = Field( 

108 dtype=float, 

109 default=3.8, 

110 doc="Intercept of the fit for the log(spike length) as a function of" 

111 " magnitude.", 

112 ) 

113 fallbackMagnitude = Field( 

114 dtype=float, 

115 default=12., 

116 doc="Default magnitude to use for sources in the reference catalog" 

117 " with missing magnitudes that land in regions of saturated pixels.", 

118 ) 

119 fallbackFluxField = Field( 

120 dtype=str, 

121 default="phot_g_mean", 

122 doc="Fallback flux field in the reference catalog to use for sources" 

123 " that don't have measurements in the science image's band.", 

124 ) 

125 spikeMask = Field( 

126 dtype=str, 

127 default="SPIKE", 

128 doc="Name of the mask plane indicating likely contamination from" 

129 " a diffraction spike.", 

130 ) 

131 saturatedMaskPlane = Field( 

132 dtype=str, 

133 default="SAT", 

134 doc="Name of the mask plane indicating a saturated pixel.", 

135 ) 

136 

137 

138class DiffractionSpikeMaskTask(Task): 

139 """Load a reference catalog to identify bright stars that are likely to be 

140 saturated and have visible diffraction spikes that need to be masked. 

141 

142 Attributes 

143 ---------- 

144 angles : `numpy.ndarray` 

145 Expected angles of diffraction spikes for bright sources. 

146 refObjLoader : `lsst.meas.algorithms.ReferenceObjectLoader` 

147 An instance of a reference object loader. 

148 """ 

149 ConfigClass = DiffractionSpikeMaskConfig 

150 _DefaultName = "diffractionSpikeMask" 

151 

152 def __init__(self, refObjLoader=None, **kwargs): 

153 Task.__init__(self, **kwargs) 

154 self.refObjLoader = refObjLoader 

155 

156 def setRefObjLoader(self, refObjLoader): 

157 """Set the reference object loader for the task. 

158 

159 Parameters 

160 ---------- 

161 refObjLoader : `lsst.meas.algorithms.ReferenceObjectLoader` 

162 An instance of a reference object loader. 

163 """ 

164 self.refObjLoader = refObjLoader 

165 

166 @timeMethod 

167 def run(self, exposure): 

168 """Load reference objects and mask bright stars on an exposure. 

169 

170 Parameters 

171 ---------- 

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

173 Science exposure to set the SPIKE plane. Will be modified in place. 

174 

175 Returns 

176 ------- 

177 spikeCat : `lsst.afw.table.SimpleCatalog` 

178 The entries from the reference catalog selected as stars with 

179 diffraction spikes. 

180 """ 

181 if self.refObjLoader is None: 

182 raise RuntimeError("Running diffraction spike mask task with no refObjLoader set in" 

183 " __init__ or setRefObjLoader") 

184 # First set the angles of the diffraction spikes from the exposure 

185 # metadata. 

186 self.set_diffraction_angle(exposure) 

187 filterLabel = exposure.getFilter() 

188 region = getRegion(exposure, lsst.sphgeom.Angle.fromDegrees(self.config.angleMargin/3600.)) 

189 refCat = self.refObjLoader.loadRegion(region, filterLabel.bandLabel).refCat 

190 mask = exposure.mask 

191 mask.addMaskPlane(self.config.spikeMask) 

192 if not np.all(np.isfinite(self.angles)): 

193 self.log.warning("Diffraction spike angle is not finite; check the boresight rotation and" 

194 " parallactic angles. Not masking diffraction spikes.") 

195 return afwTable.SimpleCatalog(refCat.schema) 

196 

197 # Mask any sources with known or estimated magnitudes for the current 

198 # filter, including sources off of the image which may have diffraction 

199 # spikes that extend onto the image. 

200 magnitudes = self.extractMagnitudes(refCat, filterLabel).refMag 

201 radii = self.calculateReferenceRadius(magnitudes) 

202 bright = (magnitudes < self.config.magnitudeThreshold) 

203 

204 nBright = np.count_nonzero(bright) 

205 

206 if nBright > 0: 

207 xvals, yvals = exposure.wcs.skyToPixelArray(refCat[bright][self.config.raKey], 

208 refCat[bright][self.config.decKey]) 

209 spikeCandidates = self.selectSources(xvals, yvals, radii[bright], mask) 

210 nSpike = np.count_nonzero(spikeCandidates) 

211 else: 

212 nSpike = 0 

213 if nSpike > 0: 

214 self.log.info("Calculating mask for %d stars brighter than magnitude %f", nSpike, 

215 self.config.magnitudeThreshold) 

216 self.maskSources(xvals[spikeCandidates], 

217 yvals[spikeCandidates], 

218 radii[bright][spikeCandidates], 

219 mask) 

220 else: 

221 if nBright == 0: 

222 self.log.info("Not masking diffraction spikes; no bright stars found in the reference " 

223 "catalog.") 

224 else: 

225 self.log.info("None of the %d stars brighter than magnitude %f are saturated on the image" 

226 " or have spikes reaching it; not masking diffraction spikes.", nBright, 

227 self.config.magnitudeThreshold) 

228 return afwTable.SimpleCatalog(refCat.schema) 

229 

230 return refCat[bright][spikeCandidates].copy(deep=True) 

231 

232 def selectSources(self, xvals, yvals, spikeRadii, mask): 

233 """Select saturated sources, and bright sources that are off the image. 

234 

235 Parameters 

236 ---------- 

237 xvals, yvals : `numpy.ndarray` 

238 Array of x- and y-values of bright sources to mask. 

239 mask : `lsst.afw.image.Mask` 

240 The mask plane of the image to set the SPIKE mask plane. 

241 spikeRadii : `numpy.ndarray` 

242 Predicted lengths in pixels of the diffraction spikes for each 

243 bright source. 

244 

245 Returns 

246 ------- 

247 candidates : `numpy.ndarray` 

248 Array of boolean flags indicating whether the given coordinates 

249 should have a diffraction spike mask calculated. 

250 """ 

251 candidates = np.zeros(len(xvals), dtype=bool) 

252 saturatedBitMask = mask.getPlaneBitMask(self.config.saturatedMaskPlane) 

253 bbox = mask.getBBox() 

254 projection = np.max([abs(np.cos(np.deg2rad(self.angles))), 

255 abs(np.sin(np.deg2rad(self.angles)))]) 

256 

257 for i, (x, y, r) in enumerate(zip(xvals, yvals, spikeRadii)): 

258 srcBox = lsst.geom.Box2I.makeCenteredBox(lsst.geom.Point2D(x, y), lsst.geom.Extent2I(3, 3)) 

259 if bbox.contains(srcBox): 

260 candidates[i] = np.all((mask[srcBox].array & saturatedBitMask) > 0) 

261 else: 

262 # If the candidate bright source is off the image, only make a 

263 # model for it if the diffraction spikes are long enough. 

264 candidates[i] = boxSeparation(bbox, x, y) < r*projection 

265 return candidates 

266 

267 def maskSources(self, xvals, yvals, spikeRadii, mask): 

268 """Apply the SPIKE mask for a given set of coordinates. The mask plane 

269 will be modified in place. 

270 

271 Parameters 

272 ---------- 

273 xvals, yvals : `numpy.ndarray` 

274 Array of x- and y-values of bright sources to mask. 

275 spikeRadii : `numpy.ndarray` 

276 Array of radius values for each bright source. 

277 mask : `lsst.afw.image.Mask` 

278 The mask plane of the image to set the SPIKE mask plane. 

279 """ 

280 bbox = mask.getBBox() 

281 for x, y, r in zip(xvals, yvals, spikeRadii): 

282 maskSingle = self.makeSingleMask(x, y, r) 

283 singleBBox = maskSingle.getBBox() 

284 if bbox.overlaps(singleBBox): 

285 singleBBox = singleBBox.clippedTo(bbox) 

286 mask[singleBBox] |= maskSingle[singleBBox] 

287 

288 def makeSingleMask(self, x, y, r): 

289 """Create a mask plane centered on a single source with the BRIGHT mask 

290 set. This mask does not have to be fully contained in the bounding box 

291 of the mask of the science image. 

292 

293 Parameters 

294 ---------- 

295 x, y : `float` 

296 Coordinates of the source to be masked. 

297 r : `float` 

298 Expected length of a diffraction spike for a source with a 

299 magnitude 

300 

301 Returns 

302 ------- 

303 mask : `lsst.afw.image.Mask` 

304 A mask plane centered on the single source being modeled. 

305 """ 

306 polygons = [] 

307 for angle in self.angles: 

308 # Model the diffraction spike as an isosceles triangle with a long 

309 # side along the spike and a short base. For efficiency, model the 

310 # diffraction spike in the opposite direction at the same time, 

311 # so the overall shape is a narrow diamond with equal length sides. 

312 xLong = np.cos(np.deg2rad(angle))*r 

313 yLong = np.sin(np.deg2rad(angle))*r 

314 xShort = -np.sin(np.deg2rad(angle))*r/self.config.spikeAspectRatio 

315 yShort = np.cos(np.deg2rad(angle))*r/self.config.spikeAspectRatio 

316 

317 corners = [lsst.geom.Point2D(x + xLong, y + yLong), 

318 lsst.geom.Point2D(x + xShort, y + yShort), 

319 lsst.geom.Point2D(x - xLong, y - yLong), 

320 lsst.geom.Point2D(x - xShort, y - yShort)] 

321 polygons.append(afwGeom.Polygon(corners)) 

322 # Combine all of the polygons into a single region 

323 polygon = polygons[0] 

324 for poly in polygons[1:]: 

325 polygon = polygon.unionSingle(poly) 

326 bbox = lsst.geom.Box2I(polygon.getBBox()) 

327 polyImage = polygon.createImage(bbox).array 

328 mask = lsst.afw.image.Mask(bbox) 

329 mask.array[polyImage > 0] = mask.getPlaneBitMask(self.config.spikeMask) 

330 return mask 

331 

332 def set_diffraction_angle(self, exposure): 

333 """Calculate the angle of diffration spikes on the image given the 

334 camera rotation. 

335 

336 Parameters 

337 ---------- 

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

339 The exposure to calculate the expected angle of diffraction spikes. 

340 """ 

341 angle = (exposure.visitInfo.boresightParAngle.asDegrees() 

342 - exposure.visitInfo.boresightRotAngle.asDegrees() 

343 + self.config.diffractAngle) 

344 self.angles = np.array([angle, angle + 90]) % 360 

345 

346 def calculateReferenceRadius(self, magnitudes): 

347 """Calculate the size of the region to mask for each bright star. 

348 

349 Parameters 

350 ---------- 

351 magnitudes : `numpy.ndarray` 

352 Magnitudes of the bright stars. 

353 

354 Returns 

355 ------- 

356 radii : `numpy.ndarray` 

357 Array of radius values for the given magnitudes. 

358 """ 

359 # In pixels 

360 radii = [10**(self.config.magSlope*magnitude + self.config.magOffset) for magnitude in magnitudes] 

361 return np.array(radii) 

362 

363 def extractMagnitudes(self, refCat, filterLabel): 

364 """Extract magnitude and magnitude error arrays from the given catalog. 

365 

366 Parameters 

367 ---------- 

368 refCat : `lsst.afw.table.SimpleCatalog` 

369 The input reference catalog. 

370 filterLabel : `str` 

371 Label of filter being calibrated. 

372 

373 Returns 

374 ------- 

375 result : `lsst.pipe.base.Struct` 

376 Results as a struct with attributes: 

377 

378 ``refMag`` 

379 Reference magnitude (`np.array`). 

380 ``refMagErr`` 

381 Reference magnitude error (`np.array`). 

382 ``refFluxFieldList`` 

383 A list of field names of the reference catalog used for fluxes (1 or 2 strings) (`list`). 

384 """ 

385 refSchema = refCat.schema 

386 

387 if self.config.applyColorTerms: 387 ↛ 388line 387 didn't jump to line 388 because the condition on line 387 was never true

388 self.log.info("Applying color terms for filter=%r, config.photoCatName=%s", 

389 filterLabel.physicalLabel, self.config.photoCatName) 

390 colorterm = self.config.colorterms.getColorterm(filterLabel.physicalLabel, 

391 self.config.photoCatName, 

392 doRaise=True) 

393 

394 refMagArr, refMagErrArr = colorterm.getCorrectedMagnitudes(refCat) 

395 fluxFieldList = [getRefFluxField(refSchema, filt) for filt in (colorterm.primary, 

396 colorterm.secondary)] 

397 else: 

398 self.log.info("Not applying color terms.") 

399 colorterm = None 

400 

401 fluxFieldList = [getRefFluxField(refSchema, filterLabel.bandLabel)] 

402 fluxField = getRefFluxField(refSchema, filterLabel.bandLabel) 

403 fluxKey = refSchema.find(fluxField).key 

404 refFluxArr = np.array(refCat.get(fluxKey)) 

405 

406 try: 

407 fluxErrKey = refSchema.find(fluxField + "Err").key 

408 refFluxErrArr = np.array(refCat.get(fluxErrKey)) 

409 except KeyError: 

410 # Reference catalogue may not have flux uncertainties; HACK DM-2308 

411 self.log.warning("Reference catalog does not have flux uncertainties for %s;" 

412 " using sqrt(flux).", fluxField) 

413 refFluxErrArr = np.sqrt(refFluxArr) 

414 

415 refMagArr = u.Quantity(refFluxArr, u.nJy).to_value(u.ABmag) 

416 # HACK convert to Jy until we have a replacement for this (DM-16903) 

417 refMagErrArr = abMagErrFromFluxErr(refFluxErrArr*1e-9, refFluxArr*1e-9) 

418 # Not all sources in the reference catalog will have flux measurements 

419 # in the current band. Since we are only masking sources use a fallback 

420 # flux measurement in these cases to get an approximate magnitude to 

421 # check for bright sources and to set the size of the mask. 

422 badMagnitudes = np.isnan(refMagArr) 

423 if np.count_nonzero(badMagnitudes): 423 ↛ 424line 423 didn't jump to line 424 because the condition on line 423 was never true

424 fluxName = f"{self.config.fallbackFluxField}_flux" 

425 # If the configured fallback flux field is missing, skip it. 

426 try: 

427 fallbackFluxKey = refSchema.find(fluxName).key 

428 except KeyError: 

429 self.log.warning(f"Field {fluxName} not found in photometric reference catalog." 

430 " Not masking bright stars with missing magnitudes.") 

431 else: 

432 fallbackFluxArr = np.array(refCat.get(fallbackFluxKey)) 

433 fallbackMagArr = u.Quantity(fallbackFluxArr[badMagnitudes], u.nJy).to_value(u.ABmag) 

434 refMagArr[badMagnitudes] = fallbackMagArr 

435 

436 return Struct( 

437 refMag=refMagArr, 

438 refMagErr=refMagErrArr, 

439 refFluxFieldList=fluxFieldList, 

440 ) 

441 

442 

443def getRegion(exposure, margin=None): 

444 """Calculate an enveloping region for an exposure. 

445 

446 Parameters 

447 ---------- 

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

449 Exposure object with calibrated WCS. 

450 margin : `lsst.sphgeom.Angle`, optional 

451 Grow the surrounding region of the exposure by this amount, in order to 

452 mask the diffraction spikes of stars off the image. 

453 

454 Returns 

455 ------- 

456 region : `lsst.sphgeom.Region` 

457 Region enveloping an exposure. 

458 """ 

459 # Bounding box needs to be a `Box2D` not a `Box2I` for `wcs.pixelToSky()` 

460 bbox = lsst.geom.Box2D(exposure.getBBox()) 

461 wcs = exposure.getWcs() 

462 

463 region = lsst.sphgeom.ConvexPolygon([pp.getVector() for pp in wcs.pixelToSky(bbox.getCorners())]) 

464 if margin is not None: 464 ↛ 475line 464 didn't jump to line 475 because the condition on line 464 was always true

465 # This is an ad-hoc, approximate implementation. It should be good 

466 # enough for catalog loading, but is not a general-purpose solution. 

467 center = lsst.geom.SpherePoint(region.getCentroid()) 

468 corners = [lsst.geom.SpherePoint(c) for c in region.getVertices()] 

469 # Approximate the region as a Euclidian square 

470 # geom.Angle(sphgeom.Angle) converter not pybind-wrapped??? 

471 diagonal_margin = lsst.geom.Angle(margin.asRadians() * math.sqrt(2.0)) 

472 padded = [c.offset(center.bearingTo(c), diagonal_margin) for c in corners] 

473 return lsst.sphgeom.ConvexPolygon.convexHull([c.getVector() for c in padded]) 

474 

475 return region 

476 

477 

478def boxSeparation(bbox, x, y): 

479 """Return the minimum horizontal or vertical distance from a point to the 

480 outside edge of a bounding box. 

481 

482 Parameters 

483 ---------- 

484 bbox : `lsst.geom.Box2I` 

485 The bounding box to check. 

486 x, y : `float` 

487 Coordinates of the point. 

488 

489 Returns 

490 ------- 

491 distance : `float` 

492 The distance in pixels by which the point is outside the box, or 0 if 

493 it is inside. 

494 """ 

495 

496 x0, y0 = bbox.getBegin() 

497 x1, y1 = bbox.getEnd() 

498 dx = 0 if x0 <= x <= x1 else min(abs(x0 - x), abs(x - x1)) 

499 dy = 0 if y0 <= y <= y1 else min(abs(y0 - y), abs(y - y1)) 

500 return max(dx, dy)