Coverage for tests/test_diffractionSpikeMask.py: 99%

184 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-26 20:46 +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 

22import os 

23import glob 

24import unittest 

25import unittest.mock 

26 

27import astropy.units as u 

28import numpy as np 

29 

30import lsst.afw.image as afwImage 

31import lsst.afw.table as afwTable 

32import lsst.geom as geom 

33from lsst.meas.algorithms.testUtils import MockReferenceObjectLoaderFromFiles 

34import lsst.meas.base.tests 

35from lsst.pipe.base import Struct 

36from lsst.pipe.tasks.diffractionSpikeMask import DiffractionSpikeMaskTask, DiffractionSpikeMaskConfig 

37from lsst.pipe.tasks.colorterms import Colorterm, ColortermDict, ColortermLibrary 

38import lsst.utils.tests 

39 

40from utils import makeTestVisitInfo 

41 

42 

43TESTDIR = os.path.abspath(os.path.dirname(__file__)) 

44RefCatDir = os.path.join(TESTDIR, "data", "sdssrefcat") 

45 

46testColorterms = ColortermLibrary(data={ 

47 "test*": ColortermDict(data={ 

48 "test-g": Colorterm(primary="g", secondary="r", c0=0.00, c1=0.00), 

49 "test-r": Colorterm(primary="r", secondary="i", c0=0.00, c1=0.00, c2=0.00), 

50 "test-i": Colorterm(primary="i", secondary="z", c0=1.00, c1=0.00, c2=0.00), 

51 "test-z": Colorterm(primary="z", secondary="i", c0=0.00, c1=0.00, c2=0.00), 

52 }) 

53}) 

54 

55 

56class DiffractionSpikeMaskTest(lsst.utils.tests.TestCase): 

57 

58 def setUp(self): 

59 

60 # Load sample input from disk 

61 testDir = os.path.dirname(__file__) 

62 

63 # The .xy.fits file has sources in the range ~ [0,2000],[0,4500] 

64 # which is bigger than the exposure 

65 self.bbox = geom.Box2I(geom.Point2I(0, 0), geom.Extent2I(2048, 4612)) 

66 

67 smallExposure = afwImage.ExposureF(os.path.join(testDir, "data", "v695833-e0-c000-a00.sci.fits")) 

68 self.exposure = afwImage.ExposureF(self.bbox) 

69 self.exposure.setWcs(smallExposure.getWcs()) 

70 self.exposure.setFilter(afwImage.FilterLabel(band="i", physical="test-i")) 

71 self.exposure.info.setVisitInfo(makeTestVisitInfo()) 

72 

73 # Make a reference loader 

74 filenames = sorted(glob.glob(os.path.join(RefCatDir, 'ref_cats', 'cal_ref_cat', '??????.fits'))) 

75 self.refObjLoader = MockReferenceObjectLoaderFromFiles(filenames, htmLevel=8) 

76 

77 def tearDown(self): 

78 del self.exposure 

79 del self.refObjLoader 

80 

81 def test_raiseWithoutLoader(self): 

82 """The task should raise an error if no reference catalog loader is 

83 configured. 

84 """ 

85 config = DiffractionSpikeMaskConfig() 

86 task = DiffractionSpikeMaskTask(config=config) 

87 with self.assertRaises(RuntimeError): 

88 task.run(self.exposure) 

89 

90 def test_loadAndMaskStars(self): 

91 """Run the bright star mask with a selection of reference sources.""" 

92 

93 config = DiffractionSpikeMaskConfig(magnitudeThreshold=16) 

94 task = DiffractionSpikeMaskTask(self.refObjLoader, config=config) 

95 exposure = self.exposure.clone() 

96 # Set the saturated mask plane in half of the image 

97 saturatedMaskBit = exposure.mask.getPlaneBitMask(config.saturatedMaskPlane) 

98 bbox = exposure.getBBox() 

99 bbox.grow(-lsst.geom.Extent2I(0, bbox.height//4)) 

100 exposure[bbox].mask.array |= saturatedMaskBit 

101 brightCat = task.run(exposure=exposure) 

102 self.assertGreater(len(brightCat), 0) 

103 # Verify that the new mask plane has been added 

104 spikeMaskBit = exposure.mask.getPlaneBitMask(config.spikeMask) 

105 # The images should not be modified 

106 self.assertImagesEqual(self.exposure.image, exposure.image) 

107 self.assertImagesEqual(self.exposure.variance, exposure.variance) 

108 # Ensure that the mask has changed 

109 self.assertFloatsNotEqual(self.exposure.mask.array, exposure.mask.array) 

110 

111 # Check that the mask is set for the bright sources inside the image 

112 # Note that the catalog will include bright sources *off* the image that 

113 # have long enough diffraction spikes to overlap the edge of the image 

114 xvals, yvals = exposure.wcs.skyToPixelArray(brightCat[config.raKey], brightCat[config.decKey]) 

115 bbox = exposure.getBBox() 

116 # Shrink the bounding box so that the bbox.contains check below is 

117 # sufficient to avoid errors. 

118 bbox.grow(-2) 

119 points = [geom.Point2D(xv, yv) for xv, yv in zip(xvals, yvals)] 

120 inside = 0 

121 outside = 0 

122 for pt in points: 

123 if bbox.contains(int(pt.getX()), int(pt.getY())): 

124 ptBox = geom.Box2I.makeCenteredBox(pt, geom.Extent2I(3, 3)) 

125 maskSet = exposure[ptBox].mask.array & spikeMaskBit > 0 

126 self.assertTrue(np.all(maskSet)) 

127 inside += 1 

128 else: 

129 outside += 1 

130 self.assertGreater(inside, 0) 

131 self.assertGreater(outside, 0) 

132 

133 def test_noBrightStars(self): 

134 """Run the bright star mask with no bright stars.""" 

135 

136 # Set a very high magnitude limit so that no stars are selected 

137 config = DiffractionSpikeMaskConfig(magnitudeThreshold=0) 

138 task = DiffractionSpikeMaskTask(self.refObjLoader, config=config) 

139 exposure = self.exposure.clone() 

140 brightCat = task.run(exposure=exposure) 

141 self.assertEqual(len(brightCat), 0) 

142 # Verify that the new mask plane has been added 

143 exposure.mask.getPlaneBitMask(config.spikeMask) 

144 # The images should not be modified 

145 self.assertImagesEqual(self.exposure.image, exposure.image) 

146 

147 def _makeLoader(self, stars): 

148 """Make a reference catalog loader that returns the given stars. 

149 

150 Parameters 

151 ---------- 

152 stars : `list` [`tuple`] 

153 ``(x, y, magnitude)`` of each star, with ``x`` and ``y`` in pixels 

154 of ``self.exposure``. 

155 

156 Returns 

157 ------- 

158 refObjLoader : `unittest.mock.Mock` 

159 Loader whose ``loadRegion`` returns a catalog of ``stars``. 

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

161 The catalog of ``stars``. 

162 """ 

163 schema = afwTable.SimpleTable.makeMinimalSchema() 

164 fluxKey = schema.addField("i_flux", type="D", units="nJy") 

165 fluxErrKey = schema.addField("i_fluxErr", type="D", units="nJy") 

166 refCat = afwTable.SimpleCatalog(schema) 

167 for x, y, mag in stars: 

168 record = refCat.addNew() 

169 record.setCoord(self.exposure.wcs.pixelToSky(x, y)) 

170 record.set(fluxKey, (mag*u.ABmag).to_value(u.nJy)) 

171 record.set(fluxErrKey, 1.0) 

172 refObjLoader = unittest.mock.Mock() 

173 refObjLoader.loadRegion.return_value = Struct(refCat=refCat) 

174 return refObjLoader, refCat 

175 

176 def test_spikeRadiiMatchBrightStars(self): 

177 """Faint stars listed ahead of the bright stars in the reference 

178 catalog must not change which bright stars are selected. 

179 """ 

180 config = DiffractionSpikeMaskConfig() 

181 ySize = self.bbox.getHeight() 

182 # Faint stars (spike radius ~25 pixels), followed by a bright star on 

183 # the image with no saturated pixels, and a bright star 150 pixels off 

184 # the image (spike radius ~400 pixels). 

185 stars = [(500, 500*i, 20) for i in range(5)] 

186 stars += [(1000, ySize/2, 10), (-150, ySize/2, 10)] 

187 refObjLoader, refCat = self._makeLoader(stars) 

188 task = DiffractionSpikeMaskTask(refObjLoader, config=config) 

189 exposure = self.exposure.clone() 

190 with self.assertLogs(task.log.name, level="INFO") as logs: 

191 spikeCat = task.run(exposure=exposure) 

192 self.assertEqual(len(spikeCat), 1) 

193 self.assertEqual(spikeCat[0].getId(), refCat[-1].getId()) 

194 self.assertIn("Calculating mask for 1 stars", "\n".join(logs.output)) 

195 spikeMaskBit = exposure.mask.getPlaneBitMask(config.spikeMask) 

196 self.assertGreater(np.count_nonzero(exposure.mask.array & spikeMaskBit), 0) 

197 

198 def test_noSpikeCandidates(self): 

199 """Bright stars that are neither saturated nor close to the image 

200 should not be masked, and the log should say why. 

201 """ 

202 config = DiffractionSpikeMaskConfig() 

203 ySize = self.bbox.getHeight() 

204 stars = [(1000, ySize/2, 10), (-1000, ySize/2, 10)] 

205 refObjLoader, _ = self._makeLoader(stars) 

206 task = DiffractionSpikeMaskTask(refObjLoader, config=config) 

207 exposure = self.exposure.clone() 

208 with self.assertLogs(task.log.name, level="INFO") as logs: 

209 spikeCat = task.run(exposure=exposure) 

210 self.assertEqual(len(spikeCat), 0) 

211 self.assertIn("None of the 2 stars", "\n".join(logs.output)) 

212 self.assertMasksEqual(exposure.mask, self.exposure.mask) 

213 

214 def test_nanSpikeAngle(self): 

215 """A NaN rotation angle should skip masking instead of raising.""" 

216 config = DiffractionSpikeMaskConfig() 

217 stars = [(1000, self.bbox.getHeight()/2, 10)] 

218 refObjLoader, _ = self._makeLoader(stars) 

219 task = DiffractionSpikeMaskTask(refObjLoader, config=config) 

220 exposure = self.exposure.clone() 

221 visitInfo = exposure.visitInfo 

222 exposure.info.setVisitInfo(afwImage.VisitInfo( 

223 id=visitInfo.id, date=visitInfo.date, era=visitInfo.era, 

224 boresightRaDec=visitInfo.boresightRaDec, boresightAzAlt=visitInfo.boresightAzAlt, 

225 boresightRotAngle=geom.Angle(np.nan), rotType=visitInfo.rotType, 

226 observatory=visitInfo.observatory, 

227 )) 

228 exposure.mask.array |= exposure.mask.getPlaneBitMask(config.saturatedMaskPlane) 

229 baseMask = exposure.mask.clone() 

230 with self.assertLogs(task.log.name, level="WARNING") as logs: 

231 spikeCat = task.run(exposure=exposure) 

232 self.assertEqual(len(spikeCat), 0) 

233 self.assertIn("not finite", "\n".join(logs.output)) 

234 self.assertMasksEqual(exposure.mask, baseMask) 

235 

236 def test_maskSources(self): 

237 """Verify that sources on and off the image are masked correctly.""" 

238 task = DiffractionSpikeMaskTask(self.refObjLoader, config=DiffractionSpikeMaskConfig()) 

239 task.set_diffraction_angle(self.exposure) 

240 self.exposure.mask.addMaskPlane(task.config.spikeMask) 

241 

242 xSize, ySize = self.bbox.getDimensions() 

243 x0, y0 = self.bbox.getBegin() 

244 x1, y1 = self.bbox.getEnd() 

245 

246 nBright = 50 

247 rng = np.random.RandomState(3) 

248 xLoc = np.arange(x0 - xSize/4, x1 + xSize/4) 

249 rng.shuffle(xLoc) 

250 xLoc = xLoc[:nBright] 

251 yLoc = np.arange(y0 - ySize/4, y1 + ySize/4) 

252 rng.shuffle(yLoc) 

253 yLoc = yLoc[:nBright] 

254 spikeRadii = np.arange(10, 200) 

255 rng.shuffle(spikeRadii) 

256 spikeRadii = spikeRadii[:nBright] 

257 saturatedBox = geom.Box2I(self.bbox.getBegin(), geom.Extent2I(xSize, ySize//2)) 

258 baseMask = self.exposure.mask.clone() 

259 baseMask[saturatedBox].array |= baseMask.getPlaneBitMask(task.config.saturatedMaskPlane) 

260 # There are four classes of sources: 

261 # 1. Bright sources on the image with saturated cores - masked 

262 # 2. Sources on the image without saturated cores - not masked 

263 # 3. Bright sources off the image with predicted diffraction spikes that 

264 # overlap the image - masked 

265 # 4. Bright sources off the image that are far away enough that any 

266 # diffraction spikes would not overlap the image - not masked 

267 nClass1 = 0 

268 nClass2 = 0 

269 nClass3 = 0 

270 nClass4 = 0 

271 selectedSources = task.selectSources(xLoc, yLoc, spikeRadii, baseMask) 

272 for x, y, r, selected in zip(xLoc, yLoc, spikeRadii, selectedSources): 

273 mask = baseMask.clone() 

274 isInImage = self.bbox.contains(geom.Point2I(x, y)) 

275 # Bright sources on the image with saturated cores. 

276 if isInImage and selected: 

277 nClass1 += 1 

278 task.maskSources([x], [y], [r], mask) 

279 self.assertGreater(np.sum(mask.array & mask.getPlaneBitMask(task.config.spikeMask) > 0), 0) 

280 

281 # Bright sources on the image without saturated cores. 

282 if isInImage and not selected: 

283 nClass2 += 1 

284 # Do *not* run task.maskSources in this case, since these are 

285 # skipped. 

286 

287 # Bright sources off the image that we predict should overlap the 

288 # image, should set the SPIKE mask for some pixels. 

289 if not isInImage and selected: 

290 nClass3 += 1 

291 task.maskSources([x], [y], [r], mask) 

292 self.assertGreater(np.sum(mask.array & mask.getPlaneBitMask(task.config.spikeMask) > 0), 0) 

293 

294 # Sources off the image that are skipped in source selection should 

295 # not change the mask even if we do calculate their SPIKE mask. 

296 if not isInImage and not selected: 

297 nClass4 += 1 

298 task.maskSources([x], [y], [r], mask) 

299 self.assertMasksEqual(mask, baseMask) 

300 # Verify that the test points were sufficient to exercise all classes. 

301 self.assertGreater(nClass1, 0) 

302 self.assertGreater(nClass2, 0) 

303 self.assertGreater(nClass3, 0) 

304 self.assertGreater(nClass4, 0) 

305 

306 

307class MemoryTestCase(lsst.utils.tests.MemoryTestCase): 

308 pass 

309 

310 

311def setup_module(module): 

312 lsst.utils.tests.init() 

313 

314 

315if __name__ == "__main__": 315 ↛ 316line 315 didn't jump to line 316 because the condition on line 315 was never true

316 lsst.utils.tests.init() 

317 unittest.main()