Coverage for tests/test_dipoleFitter.py: 98%

148 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-13 09:48 +0000

1# 

2# LSST Data Management System 

3# Copyright 2008-2017 AURA/LSST. 

4# 

5# This product includes software developed by the 

6# LSST Project (http://www.lsst.org/). 

7# 

8# This program is free software: you can redistribute it and/or modify 

9# it under the terms of the GNU General Public License as published by 

10# the Free Software Foundation, either version 3 of the License, or 

11# (at your option) any later version. 

12# 

13# This program is distributed in the hope that it will be useful, 

14# but WITHOUT ANY WARRANTY; without even the implied warranty of 

15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

16# GNU General Public License for more details. 

17# 

18# You should have received a copy of the LSST License Statement and 

19# the GNU General Public License along with this program. If not, 

20# see <https://www.lsstcorp.org/LegalNotices/>. 

21 

22"""Tests of the DipoleFitAlgorithm and its related tasks and plugins. 

23 

24Each test generates a fake image with two synthetic dipoles as input data. 

25""" 

26import unittest 

27 

28import numpy as np 

29 

30import lsst.utils.tests 

31import lsst.afw.detection as afwDetection 

32import lsst.afw.table as afwTable 

33from lsst.ip.diffim.dipoleFitTask import (DipoleFitAlgorithm, DipoleFitTask) 

34import utils 

35 

36 

37def reversePeaks(footprint): 

38 """Reverse the order of the peaks of a footprint. 

39 

40 Parameters 

41 ---------- 

42 footprint : `lsst.afw.detection.Footprint` 

43 Footprint to modify in place. 

44 """ 

45 peaks = footprint.getPeaks() 

46 reordered = afwDetection.PeakCatalog(peaks.table) 

47 reordered.extend(list(peaks)[::-1]) 

48 peaks.clear() 

49 footprint.setPeakCatalog(reordered) 

50 

51 

52class DipoleTestImage: 

53 """Create a test dipole image and store the parameters used to make it, 

54 for comparison with the fitted results. 

55 

56 Parameters 

57 ---------- 

58 xc, yc : `list` [`float`] 

59 x, y coordinate (pixels) of center(s) of input dipole(s). 

60 flux: `list` [`float`] 

61 Flux(es) of input dipole(s). 

62 gradientParams : `tuple` 

63 Tuple with three parameters for linear background gradient. 

64 offsets : `list` [`float`] 

65 Pixel coordinates between lobes of dipoles. 

66 """ 

67 

68 def __init__(self, xc=None, yc=None, flux=None, offsets=None, gradientParams=None, edgeWidth=None): 

69 self.xc = xc if xc is not None else [65.3, 24.2] 

70 self.yc = yc if yc is not None else [38.6, 78.5] 

71 self.offsets = offsets if offsets is not None else np.array([-2., 2.]) 

72 self.flux = flux if flux is not None else [2500., 2345.] 

73 self.gradientParams = gradientParams if gradientParams is not None else [10., 3., 5.] 

74 self.edgeWidth = edgeWidth if edgeWidth is not None else 8 

75 

76 # The default tolerance for comparisons of fitted parameters with input values. 

77 # Given the noise in the input images (default noise value of 2.), this is a 

78 # useful test of algorithm robustness, and will guard against future regressions. 

79 self.rtol = 0.01 

80 

81 self.generateTestImage() 

82 

83 def generateTestImage(self): 

84 self.testImage = utils.DipoleTestImage( 

85 w=100, h=100, 

86 xcenPos=self.xc + self.offsets, 

87 ycenPos=self.yc + self.offsets, 

88 xcenNeg=self.xc - self.offsets, 

89 ycenNeg=self.yc - self.offsets, 

90 flux=self.flux, fluxNeg=self.flux, 

91 noise=2., # Note the input noise - this affects the relative tolerances used. 

92 gradientParams=self.gradientParams, 

93 edgeWidth=self.edgeWidth) 

94 

95 

96class DipoleFitTest(lsst.utils.tests.TestCase): 

97 """A test case for separately testing the dipole fit algorithm 

98 directly, and the single frame measurement. 

99 

100 In each test, create a simulated diffim with two dipoles, noise, 

101 and a linear background gradient in the pre-sub images then 

102 compare the input fluxes/centroids with the fitted results. 

103 """ 

104 

105 def testDipoleAlgorithm(self): 

106 """Test the dipole fitting algorithm directly (fitDipole()). 

107 

108 Test that the resulting fluxes/centroids are very close to the 

109 input values for both dipoles in the image. 

110 """ 

111 dipoleTestImage = DipoleTestImage() 

112 catalog = dipoleTestImage.testImage.detectDipoleSources(minBinSize=32) 

113 

114 for s in catalog: 

115 fp = s.getFootprint() 

116 self.assertTrue(len(fp.getPeaks()) == 2) 

117 

118 self._checkAlgorithmOutput(dipoleTestImage, catalog) 

119 

120 def testDipoleAlgorithmNegativePeakFirst(self): 

121 """Test that the fit is the same when the negative peak of each dipole 

122 comes before the positive peak. 

123 """ 

124 dipoleTestImage = DipoleTestImage() 

125 catalog = dipoleTestImage.testImage.detectDipoleSources(minBinSize=32) 

126 

127 for s in catalog: 

128 reversePeaks(s.getFootprint()) 

129 self.assertLess(s.getFootprint().getPeaks()[0].getPeakValue(), 0) 

130 

131 self._checkAlgorithmOutput(dipoleTestImage, catalog) 

132 

133 def _checkAlgorithmOutput(self, dipoleTestImage, catalog): 

134 """Fit each dipole in ``catalog`` and compare the resulting 

135 fluxes/centroids with the input values. 

136 

137 Parameters 

138 ---------- 

139 dipoleTestImage : `DipoleTestImage` 

140 Image that was generated for the test. 

141 catalog : `lsst.afw.table.SourceCatalog` 

142 Sources detected on the test image. 

143 """ 

144 # Display (plot) the output dipole thumbnails with matplotlib. 

145 display = False 

146 # Be verbose during fitting, including the lmfit internal details. 

147 verbose = False 

148 

149 rtol = dipoleTestImage.rtol 

150 offsets = dipoleTestImage.offsets 

151 testImage = dipoleTestImage.testImage 

152 for i, s in enumerate(catalog): 

153 alg = DipoleFitAlgorithm(testImage.diffim, testImage.posImage, testImage.negImage) 

154 result, _ = alg.fitDipole( 

155 s, rel_weight=0.5, separateNegParams=False, 

156 verbose=verbose, display=display) 

157 

158 self.assertFloatsAlmostEqual((result.posFlux.instFlux + abs(result.negFlux.instFlux))/2., 

159 dipoleTestImage.flux[i], rtol=rtol) 

160 self.assertFloatsAlmostEqual(result.posCentroid.x, dipoleTestImage.xc[i] + offsets[i], rtol=rtol) 

161 self.assertFloatsAlmostEqual(result.posCentroid.y, dipoleTestImage.yc[i] + offsets[i], rtol=rtol) 

162 self.assertFloatsAlmostEqual(result.negCentroid.x, dipoleTestImage.xc[i] - offsets[i], rtol=rtol) 

163 self.assertFloatsAlmostEqual(result.negCentroid.y, dipoleTestImage.yc[i] - offsets[i], rtol=rtol) 

164 

165 def _runDetection(self, dipoleTestImage, maxFootprintArea=None, editFootprint=None): 

166 """Run 'diaSource' detection on the diffim, including merging of 

167 positive and negative sources. 

168 

169 Then run DipoleFitTask on the image and return the resulting catalog. 

170 If ``editFootprint`` is given, it is called with the footprint of 

171 each source before the sources are measured. 

172 """ 

173 # Create the various tasks and schema -- avoid code reuse. 

174 testImage = dipoleTestImage.testImage 

175 detectTask, schema = testImage.detectDipoleSources(doMerge=False, minBinSize=32) 

176 

177 config = DipoleFitTask.ConfigClass() 

178 # Also run the older C++ DipoleFlux algorithm for comparison purposes. 

179 config.plugins.names |= ["ip_diffim_PsfDipoleFlux"] 

180 if maxFootprintArea: 

181 config.plugins["ip_diffim_DipoleFit"].maxFootprintArea = maxFootprintArea 

182 measureTask = DipoleFitTask(schema=schema, config=config) 

183 

184 table = afwTable.SourceTable.make(schema) 

185 detectResult = detectTask.run(table, testImage.diffim) 

186 fpSet = detectResult.positive 

187 fpSet.merge(detectResult.negative, 2, 2, False) 

188 sources = afwTable.SourceCatalog(table) 

189 fpSet.makeSources(sources) 

190 if editFootprint is not None: 

191 for source in sources: 

192 editFootprint(source.getFootprint()) 

193 

194 measureTask.run(sources, testImage.diffim, testImage.posImage, testImage.negImage) 

195 return sources 

196 

197 def _checkTaskOutput(self, dipoleTestImage, sources, noPreImages=False): 

198 """Compare the fluxes/centroids in `sources` are entered 

199 into the correct slots of the catalog, and have values that 

200 are very close to the input values for both dipoles in the 

201 image. 

202 

203 Also test that the resulting fluxes are close to those 

204 generated by the existing ip_diffim_DipoleMeasurement task 

205 (PsfDipoleFit). 

206 

207 Parameters 

208 ---------- 

209 dipoleTestImage : `DipoleTestImage` 

210 Image that was generated for the test. 

211 sources : `lsst.afw.table.SourceCatalog` 

212 Source catalog measured on the test image. 

213 noPreImages : bool, optional 

214 Set to True if there were no positive/negative images generated 

215 for the test, to use much looser uncertainty tolerances. 

216 """ 

217 rtol = dipoleTestImage.rtol 

218 offsets = dipoleTestImage.offsets 

219 for i, record in enumerate(sources): 

220 self.assertFloatsAlmostEqual((record['ip_diffim_DipoleFit_pos_instFlux'] 

221 + abs(record['ip_diffim_DipoleFit_neg_instFlux']))/2., 

222 dipoleTestImage.flux[i], rtol=rtol) 

223 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_pos_x'], 

224 dipoleTestImage.xc[i] + offsets[i], rtol=rtol) 

225 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_pos_y'], 

226 dipoleTestImage.yc[i] + offsets[i], rtol=rtol) 

227 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_neg_x'], 

228 dipoleTestImage.xc[i] - offsets[i], rtol=rtol) 

229 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_neg_y'], 

230 dipoleTestImage.yc[i] - offsets[i], rtol=rtol) 

231 

232 # check uncertainties 

233 # TODO: how to compute the correct uncertainty to test here? 

234 # self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_instFluxErr'], 

235 # ???, rtol=rtol) 

236 # emperical uncertainty values: not clear how to compute proper expected values. 

237 with self.subTest(i=repr(i), type="pos_xErr"): 

238 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_pos_xErr'], 

239 .53*record["base_SdssCentroid_xErr"], 

240 rtol=0.1 if not noPreImages else 0.5) 

241 with self.subTest(i=repr(i), type="pos_yErr"): 

242 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_pos_yErr'], 

243 .53*record["base_SdssCentroid_yErr"], 

244 rtol=0.1 if not noPreImages else 0.5) 

245 with self.subTest(i=repr(i), type="neg_xErr"): 

246 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_neg_xErr'], 

247 .53*record["base_SdssCentroid_xErr"], 

248 rtol=0.1 if not noPreImages else 0.5) 

249 with self.subTest(i=repr(i), type="neg_yErr"): 

250 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_neg_yErr'], 

251 .53*record["base_SdssCentroid_yErr"], 

252 rtol=0.1 if not noPreImages else 0.5) 

253 # NOTE: these are smaller than the positive/negative uncertainties, 

254 # because the of those covariance is negative! 

255 with self.subTest(i=repr(i), type="xErr"): 

256 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_xErr'], 

257 .34*record["base_SdssCentroid_xErr"], 

258 rtol=0.06 if not noPreImages else 0.5) 

259 with self.subTest(i=repr(i), type="yErr"): 

260 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_yErr'], 

261 .35*record["base_SdssCentroid_yErr"], 

262 rtol=0.06 if not noPreImages else 0.5) 

263 

264 # Note this is dependent on the noise (variance) being realistic in the image. 

265 # otherwise it throws off the chi2 estimate, which is used for classification: 

266 self.assertTrue(record['ip_diffim_DipoleFit_classification']) 

267 

268 # compare to the original ip_diffim_PsfDipoleFlux measurements 

269 # result2 = record.extract("ip_diffim_PsfDipoleFlux*") 

270 self.assertFloatsAlmostEqual((record['ip_diffim_DipoleFit_pos_instFlux'] 

271 + abs(record['ip_diffim_DipoleFit_neg_instFlux']))/2., 

272 (record['ip_diffim_PsfDipoleFlux_pos_instFlux'] 

273 + abs(record['ip_diffim_PsfDipoleFlux_neg_instFlux']))/2., 

274 rtol=rtol) 

275 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_pos_x'], 

276 record['ip_diffim_PsfDipoleFlux_pos_centroid_x'], 

277 rtol=rtol) 

278 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_pos_y'], 

279 record['ip_diffim_PsfDipoleFlux_pos_centroid_y'], 

280 rtol=rtol) 

281 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_neg_x'], 

282 record['ip_diffim_PsfDipoleFlux_neg_centroid_x'], 

283 rtol=rtol) 

284 self.assertFloatsAlmostEqual(record['ip_diffim_DipoleFit_neg_y'], 

285 record['ip_diffim_PsfDipoleFlux_neg_centroid_y'], 

286 rtol=rtol) 

287 

288 def testDipoleTask(self): 

289 """Test the dipole fitting singleFramePlugin. 

290 

291 Test that the resulting fluxes/centroids are entered into the 

292 correct slots of the catalog, and have values that are very 

293 close to the input values for both dipoles in the image. 

294 

295 Also test that the resulting fluxes are close to those 

296 generated by the existing ip_diffim_DipoleMeasurement task 

297 (PsfDipoleFit). 

298 """ 

299 dipoleTestImage = DipoleTestImage() 

300 sources = self._runDetection(dipoleTestImage) 

301 self._checkTaskOutput(dipoleTestImage, sources) 

302 

303 def testDipoleTaskExtraPeak(self): 

304 """Test that a dipole is fit when a faint positive peak comes after 

305 the peaks of its two lobes. 

306 """ 

307 def addFaintPeak(footprint): 

308 peak = footprint.getPeaks()[0] 

309 footprint.addPeak(peak.getFx() + 1, peak.getFy(), 0.01*peak.getPeakValue()) 

310 

311 dipoleTestImage = DipoleTestImage() 

312 sources = self._runDetection(dipoleTestImage, editFootprint=addFaintPeak) 

313 

314 for i, record in enumerate(sources): 

315 peakValues = [peak.getPeakValue() for peak in record.getFootprint().getPeaks()] 

316 self.assertEqual(list(np.sign(peakValues)), [1, -1, 1]) 

317 self.assertFloatsAlmostEqual((record['ip_diffim_DipoleFit_pos_instFlux'] 

318 + abs(record['ip_diffim_DipoleFit_neg_instFlux']))/2., 

319 dipoleTestImage.flux[i], rtol=dipoleTestImage.rtol) 

320 self.assertTrue(record['ip_diffim_DipoleFit_classification']) 

321 

322 def testDipoleTaskNoPosImage(self): 

323 """Test the dipole fitting singleFramePlugin in the case where no 

324 `posImage` is provided. It should be the same as above because 

325 `posImage` can be constructed from `diffim+negImage`. 

326 

327 Test that the resulting fluxes/centroids are entered into the 

328 correct slots of the catalog, and have values that are very 

329 close to the input values for both dipoles in the image. 

330 

331 Also test that the resulting fluxes are close to those 

332 generated by the existing ip_diffim_DipoleMeasurement task 

333 (PsfDipoleFit). 

334 """ 

335 dipoleTestImage = DipoleTestImage() 

336 dipoleTestImage.testImage.posImage = None 

337 sources = self._runDetection(dipoleTestImage) 

338 self._checkTaskOutput(dipoleTestImage, sources) 

339 

340 def testDipoleTaskNoNegImage(self): 

341 """Test the dipole fitting singleFramePlugin in the case where no 

342 `negImage` is provided. It should be the same as above because 

343 `negImage` can be constructed from `posImage-diffim`. 

344 

345 Test that the resulting fluxes/centroids are entered into the 

346 correct slots of the catalog, and have values that are very 

347 close to the input values for both dipoles in the image. 

348 

349 Also test that the resulting fluxes are close to those 

350 generated by the existing ip_diffim_DipoleMeasurement task 

351 (PsfDipoleFit). 

352 """ 

353 dipoleTestImage = DipoleTestImage() 

354 dipoleTestImage.testImage.negImage = None 

355 sources = self._runDetection(dipoleTestImage) 

356 self._checkTaskOutput(dipoleTestImage, sources) 

357 

358 def testDipoleTaskNoPreSubImages(self): 

359 """Test the dipole fitting singleFramePlugin in the case where no 

360 pre-subtraction data (`posImage` or `negImage`) are provided. 

361 In this case it just fits a dipole model to the diffim 

362 (dipole) image alone. Note that this test will only pass for 

363 widely-separated dipoles. 

364 

365 Test that the resulting fluxes/centroids are entered into the 

366 correct slots of the catalog, and have values that are very 

367 close to the input values for both dipoles in the image. 

368 

369 Also test that the resulting fluxes are close to those 

370 generated by the existing ip_diffim_DipoleMeasurement task 

371 (PsfDipoleFit). 

372 """ 

373 dipoleTestImage = DipoleTestImage() 

374 dipoleTestImage.testImage.posImage = dipoleTestImage.testImage.negImage = None 

375 sources = self._runDetection(dipoleTestImage) 

376 self._checkTaskOutput(dipoleTestImage, sources, noPreImages=True) 

377 

378 def testDipoleEdge(self): 

379 """Test the too-close-to-image-edge scenario for dipole fitting 

380 singleFramePlugin. 

381 

382 Test that the dipoles which are too close to the edge are 

383 not detected. 

384 """ 

385 

386 # with no edge, and masks growing due to convolution, 

387 # we should not detect any dipole sources 

388 # (If we were to keep the original mask instead, as in DM-45318 that 

389 # was subsequently canceled in DM-47385, we will detect 2 sources) 

390 dipoleTestImage = DipoleTestImage(xc=[5.3, 4.8], yc=[4.6, 86.5], flux=[200, 210], edgeWidth=0) 

391 sources = self._runDetection(dipoleTestImage) 

392 self.assertEqual(len(sources), 0) 

393 

394 # with a wide edge we should not detect any sources 

395 dipoleTestImage = DipoleTestImage(xc=[5.3, 4.8], yc=[4.6, 86.5], flux=[200, 210], edgeWidth=20) 

396 sources = self._runDetection(dipoleTestImage) 

397 self.assertEqual(len(sources), 0) 

398 

399 def testDipoleFootprintTooLarge(self): 

400 """Test that the footprint area cut flags sources.""" 

401 

402 dipoleTestImage = DipoleTestImage() 

403 # This area is smaller than the area of the test sources (~750). 

404 sources = self._runDetection(dipoleTestImage, maxFootprintArea=500) 

405 

406 self.assertTrue(np.all(sources["ip_diffim_DipoleFit_flag"])) 

407 

408 

409class TestMemory(lsst.utils.tests.MemoryTestCase): 

410 pass 

411 

412 

413def setup_module(module): 

414 lsst.utils.tests.init() 

415 

416 

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

418 lsst.utils.tests.init() 

419 unittest.main()