Coverage for tests/test_gaap.py: 13%

356 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2022-09-21 02:06 -0700

1# This file is part of meas_extensions_gaap 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (http://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 LSST License Statement and 

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

21# see <http://www.lsstcorp.org/LegalNotices/>. 

22 

23import math 

24import unittest 

25import galsim 

26import itertools 

27import lsst.afw.detection as afwDetection 

28import lsst.afw.display as afwDisplay 

29import lsst.afw.geom as afwGeom 

30import lsst.afw.image as afwImage 

31import lsst.afw.table as afwTable 

32import lsst.daf.base as dafBase 

33import lsst.geom as geom 

34from lsst.pex.exceptions import InvalidParameterError 

35import lsst.meas.base as measBase 

36import lsst.meas.base.tests 

37import lsst.meas.extensions.gaap 

38import lsst.utils.tests 

39import numpy as np 

40import scipy 

41 

42 

43try: 

44 type(display) 

45except NameError: 

46 display = False 

47 frame = 1 

48 

49 

50def makeGalaxyExposure(scale, psfSigma=0.9, flux=1000., galSigma=3.7, variance=1.0): 

51 """Make an ideal exposure of circular Gaussian 

52 

53 For the purpose of testing Gaussian Aperture and PSF algorithm (GAaP), this 

54 generates a noiseless image of circular Gaussian galaxy of a desired total 

55 flux convolved by a circular Gaussian PSF. The Gaussianity of the galaxy 

56 and the PSF allows comparison with analytical results, modulo pixelization. 

57 

58 Parameters 

59 ---------- 

60 scale : `float` 

61 Pixel scale in the exposure. 

62 psfSigma : `float` 

63 Sigma of the circular Gaussian PSF. 

64 flux : `float` 

65 The total flux of the galaxy. 

66 galSigma : `float` 

67 Sigma of the pre-seeing circular Gaussian galaxy. 

68 

69 Returns 

70 ------- 

71 exposure, center 

72 A tuple containing an lsst.afw.image.Exposure and lsst.geom.Point2D 

73 objects, corresponding to the galaxy image and its centroid. 

74 """ 

75 psfWidth = 2*int(4.0*psfSigma) + 1 

76 galWidth = 2*int(40.*math.hypot(galSigma, psfSigma)) + 1 

77 gal = galsim.Gaussian(sigma=galSigma, flux=flux) 

78 

79 galIm = galsim.Image(galWidth, galWidth) 

80 galIm = galsim.Convolve([gal, galsim.Gaussian(sigma=psfSigma, flux=1.)]).drawImage(image=galIm, 

81 scale=1.0, 

82 method='no_pixel') 

83 exposure = afwImage.makeExposure(afwImage.makeMaskedImageFromArrays(galIm.array)) 

84 exposure.setPsf(afwDetection.GaussianPsf(psfWidth, psfWidth, psfSigma)) 

85 

86 exposure.variance.set(variance) 

87 exposure.mask.set(0) 

88 center = exposure.getBBox().getCenter() 

89 

90 cdMatrix = afwGeom.makeCdMatrix(scale=scale) 

91 exposure.setWcs(afwGeom.makeSkyWcs(crpix=center, 

92 crval=geom.SpherePoint(0.0, 0.0, geom.degrees), 

93 cdMatrix=cdMatrix)) 

94 return exposure, center 

95 

96 

97class GaapFluxTestCase(lsst.meas.base.tests.AlgorithmTestCase, lsst.utils.tests.TestCase): 

98 """Main test case for the GAaP plugin. 

99 """ 

100 def setUp(self): 

101 self.center = lsst.geom.Point2D(100.0, 770.0) 

102 self.bbox = lsst.geom.Box2I(lsst.geom.Point2I(-20, -30), 

103 lsst.geom.Extent2I(240, 1600)) 

104 self.dataset = lsst.meas.base.tests.TestDataset(self.bbox) 

105 

106 # We will consider three sources in our test case 

107 # recordId = 0: A bright point source 

108 # recordId = 1: An elliptical (Gaussian) galaxy 

109 # recordId = 2: A source near a corner 

110 self.dataset.addSource(1000., self.center - lsst.geom.Extent2I(0, 100)) 

111 self.dataset.addSource(1000., self.center + lsst.geom.Extent2I(0, 100), 

112 afwGeom.Quadrupole(9., 9., 4.)) 

113 self.dataset.addSource(600., lsst.geom.Point2D(self.bbox.getMin()) + lsst.geom.Extent2I(10, 10)) 

114 

115 def tearDown(self): 

116 del self.center 

117 del self.bbox 

118 del self.dataset 

119 

120 def makeAlgorithm(self, gaapConfig=None): 

121 schema = lsst.meas.base.tests.TestDataset.makeMinimalSchema() 

122 if gaapConfig is None: 

123 gaapConfig = lsst.meas.extensions.gaap.SingleFrameGaapFluxConfig() 

124 gaapPlugin = lsst.meas.extensions.gaap.SingleFrameGaapFluxPlugin(gaapConfig, 

125 "ext_gaap_GaapFlux", 

126 schema, None) 

127 if gaapConfig.doOptimalPhotometry: 

128 afwTable.QuadrupoleKey.addFields(schema, "psfShape", "PSF shape") 

129 schema.getAliasMap().set("slot_PsfShape", "psfShape") 

130 return gaapPlugin, schema 

131 

132 def check(self, psfSigma=0.5, flux=1000., scalingFactors=[1.15], forced=False): 

133 """Check for non-negative values for GAaP instFlux and instFluxErr. 

134 """ 

135 scale = 0.1*geom.arcseconds 

136 

137 TaskClass = measBase.ForcedMeasurementTask if forced else measBase.SingleFrameMeasurementTask 

138 

139 # Create an image of a tiny source 

140 exposure, center = makeGalaxyExposure(scale, psfSigma, flux, galSigma=0.001, variance=0.) 

141 

142 measConfig = TaskClass.ConfigClass() 

143 algName = "ext_gaap_GaapFlux" 

144 

145 measConfig.plugins.names.add(algName) 

146 

147 if forced: 

148 measConfig.copyColumns = {"id": "objectId", "parent": "parentObjectId"} 

149 

150 algConfig = measConfig.plugins[algName] 

151 algConfig.scalingFactors = scalingFactors 

152 algConfig.scaleByFwhm = True 

153 algConfig.doPsfPhotometry = True 

154 # Do not turn on optimal photometry; not robust for a point-source. 

155 algConfig.doOptimalPhotometry = False 

156 

157 if forced: 

158 offset = geom.Extent2D(-12.3, 45.6) 

159 refWcs = exposure.getWcs().copyAtShiftedPixelOrigin(offset) 

160 refSchema = afwTable.SourceTable.makeMinimalSchema() 

161 centroidKey = afwTable.Point2DKey.addFields(refSchema, "my_centroid", doc="centroid", 

162 unit="pixel") 

163 shapeKey = afwTable.QuadrupoleKey.addFields(refSchema, "my_shape", "shape") 

164 refSchema.getAliasMap().set("slot_Centroid", "my_centroid") 

165 refSchema.getAliasMap().set("slot_Shape", "my_shape") 

166 refSchema.addField("my_centroid_flag", type="Flag", doc="centroid flag") 

167 refSchema.addField("my_shape_flag", type="Flag", doc="shape flag") 

168 refCat = afwTable.SourceCatalog(refSchema) 

169 refSource = refCat.addNew() 

170 refSource.set(centroidKey, center + offset) 

171 refSource.set(shapeKey, afwGeom.Quadrupole(1.0, 1.0, 0.0)) 

172 

173 refSource.setCoord(refWcs.pixelToSky(refSource.get(centroidKey))) 

174 taskInitArgs = (refSchema,) 

175 taskRunArgs = (refCat, refWcs) 

176 else: 

177 taskInitArgs = (afwTable.SourceTable.makeMinimalSchema(),) 

178 taskRunArgs = () 

179 

180 # Activate undeblended measurement with the same configuration 

181 measConfig.undeblended.names.add(algName) 

182 measConfig.undeblended[algName] = measConfig.plugins[algName] 

183 

184 # We are no longer going to change the configs. 

185 # So validate and freeze as they would happen when run from a CLI 

186 measConfig.validate() 

187 measConfig.freeze() 

188 

189 algMetadata = dafBase.PropertyList() 

190 task = TaskClass(*taskInitArgs, config=measConfig, algMetadata=algMetadata) 

191 

192 schema = task.schema 

193 measCat = afwTable.SourceCatalog(schema) 

194 source = measCat.addNew() 

195 source.getTable().setMetadata(algMetadata) 

196 ss = afwDetection.FootprintSet(exposure.getMaskedImage(), afwDetection.Threshold(10.0)) 

197 fp = ss.getFootprints()[0] 

198 source.setFootprint(fp) 

199 

200 task.run(measCat, exposure, *taskRunArgs) 

201 

202 if display: 

203 disp = afwDisplay.Display(frame) 

204 disp.mtv(exposure) 

205 disp.dot("x", *center, origin=afwImage.PARENT, title="psfSigma=%f" % (psfSigma,)) 

206 

207 self.assertFalse(source.get(algName + "_flag")) # algorithm succeeded 

208 

209 # We first check if it produces a positive number (non-nan) 

210 for baseName in algConfig.getAllGaapResultNames(algName): 

211 self.assertTrue((source.get(baseName + "_instFlux") >= 0)) 

212 self.assertTrue((source.get(baseName + "_instFluxErr") >= 0)) 

213 

214 # For scalingFactor > 1, check if the measured value is close to truth. 

215 for baseName in algConfig.getAllGaapResultNames(algName): 

216 if "_1_0x_" not in baseName: 

217 rtol = 0.1 if "PsfFlux" not in baseName else 0.2 

218 self.assertFloatsAlmostEqual(source.get(baseName + "_instFlux"), flux, rtol=rtol) 

219 

220 def runGaap(self, forced, psfSigma, scalingFactors=(1.0, 1.05, 1.1, 1.15, 1.2, 1.5, 2.0)): 

221 self.check(psfSigma=psfSigma, forced=forced, scalingFactors=scalingFactors) 

222 

223 @lsst.utils.tests.methodParameters(psfSigma=(1.7, 0.95, 1.3,)) 

224 def testGaapPluginUnforced(self, psfSigma): 

225 """Run GAaP as Single-frame measurement plugin. 

226 """ 

227 self.runGaap(False, psfSigma) 

228 

229 @lsst.utils.tests.methodParameters(psfSigma=(1.7, 0.95, 1.3,)) 

230 def testGaapPluginForced(self, psfSigma): 

231 """Run GAaP as forced measurement plugin. 

232 """ 

233 self.runGaap(True, psfSigma) 

234 

235 def testFail(self, scalingFactors=[100.], sigmas=[500.]): 

236 """Test that the fail method sets the flags correctly. 

237 

238 Set config parameters that are guaranteed to raise exceptions, 

239 and check that they are handled properly by the `fail` method and that 

240 expected log messages are generated. 

241 For failure modes not handled by the `fail` method, we test them 

242 in the ``testFlags`` method. 

243 """ 

244 algName = "ext_gaap_GaapFlux" 

245 dependencies = ("base_SdssShape",) 

246 config = self.makeSingleFrameMeasurementConfig(algName, dependencies=dependencies) 

247 gaapConfig = config.plugins[algName] 

248 gaapConfig.scalingFactors = scalingFactors 

249 gaapConfig.sigmas = sigmas 

250 gaapConfig.doPsfPhotometry = True 

251 gaapConfig.doOptimalPhotometry = True 

252 

253 gaapConfig.scaleByFwhm = True 

254 self.assertTrue(gaapConfig.scaleByFwhm) # Test the getter method. 

255 

256 algMetadata = lsst.daf.base.PropertyList() 

257 sfmTask = self.makeSingleFrameMeasurementTask(algName, dependencies=dependencies, config=config, 

258 algMetadata=algMetadata) 

259 exposure, catalog = self.dataset.realize(0.0, sfmTask.schema) 

260 self.recordPsfShape(catalog) 

261 

262 # Expected error messages in the logs when running `sfmTask`. 

263 errorMessage = [("Failed to solve for PSF matching kernel in GAaP for (100.000000, 670.000000): " 

264 "Problematic scaling factors = 100.0 " 

265 "Errors: Exception('Unable to determine kernel sum; 0 candidates')"), 

266 ("Failed to solve for PSF matching kernel in GAaP for (100.000000, 870.000000): " 

267 "Problematic scaling factors = 100.0 " 

268 "Errors: Exception('Unable to determine kernel sum; 0 candidates')"), 

269 ("Failed to solve for PSF matching kernel in GAaP for (-10.000000, -20.000000): " 

270 "Problematic scaling factors = 100.0 " 

271 "Errors: Exception('Unable to determine kernel sum; 0 candidates')")] 

272 

273 plugin_logger_name = sfmTask.log.getChild(algName).name 

274 self.assertEqual(plugin_logger_name, "lsst.measurement.ext_gaap_GaapFlux") 

275 with self.assertLogs(plugin_logger_name, "ERROR") as cm: 

276 sfmTask.run(catalog, exposure) 

277 self.assertEqual([record.message for record in cm.records], errorMessage) 

278 

279 for record in catalog: 

280 self.assertFalse(record[algName + "_flag"]) 

281 for scalingFactor in scalingFactors: 

282 flagName = gaapConfig._getGaapResultName(scalingFactor, "flag_gaussianization", algName) 

283 self.assertTrue(record[flagName]) 

284 for sigma in sigmas + ["Optimal"]: 

285 baseName = gaapConfig._getGaapResultName(scalingFactor, sigma, algName) 

286 self.assertTrue(record[baseName + "_flag"]) 

287 self.assertFalse(record[baseName + "_flag_bigPsf"]) 

288 

289 baseName = gaapConfig._getGaapResultName(scalingFactor, "PsfFlux", algName) 

290 self.assertTrue(record[baseName + "_flag"]) 

291 

292 # Try and "fail" with no PSF. 

293 # Since fatal exceptions are not caught by the measurement framework, 

294 # use a context manager and catch it here. 

295 exposure.setPsf(None) 

296 with self.assertRaises(lsst.meas.base.FatalAlgorithmError): 

297 sfmTask.run(catalog, exposure) 

298 

299 def testFlags(self, sigmas=[0.4, 0.5, 0.7], scalingFactors=[1.15, 1.25, 1.4, 100.]): 

300 """Test that GAaP flags are set properly. 

301 

302 Specifically, we test that 

303 

304 1. for invalid combinations of config parameters, only the 

305 appropriate flags are set and not that the entire measurement itself is 

306 flagged. 

307 2. for sources close to the edge, the edge flags are set. 

308 

309 Parameters 

310 ---------- 

311 sigmas : `list` [`float`], optional 

312 The list of sigmas (in arcseconds) to construct the 

313 `SingleFrameGaapFluxConfig`. 

314 scalingFactors : `list` [`float`], optional 

315 The list of scaling factors to construct the 

316 `SingleFrameGaapFluxConfig`. 

317 

318 Raises 

319 ----- 

320 InvalidParameterError 

321 Raised if none of the config parameters will fail a measurement. 

322 

323 Notes 

324 ----- 

325 Since the seeing in the test dataset is 2 pixels, at least one of the 

326 ``sigmas`` should be smaller than at least twice of one of the 

327 ``scalingFactors`` to avoid the InvalidParameterError exception being 

328 raised. 

329 """ 

330 gaapConfig = lsst.meas.extensions.gaap.SingleFrameGaapFluxConfig(sigmas=sigmas, 

331 scalingFactors=scalingFactors) 

332 gaapConfig.scaleByFwhm = True 

333 gaapConfig.doOptimalPhotometry = True 

334 

335 # Make an instance of GAaP algorithm from a config 

336 algName = "ext_gaap_GaapFlux" 

337 algorithm, schema = self.makeAlgorithm(gaapConfig) 

338 # Make a noiseless exposure and measurements for reference 

339 exposure, catalog = self.dataset.realize(0.0, schema) 

340 # Record the PSF shapes if optimal photometry is performed. 

341 if gaapConfig.doOptimalPhotometry: 

342 self.recordPsfShape(catalog) 

343 

344 record = catalog[0] 

345 algorithm.measure(record, exposure) 

346 seeing = exposure.getPsf().getSigma() 

347 pixelScale = exposure.getWcs().getPixelScale().asArcseconds() 

348 # Measurement must fail (i.e., flag_bigPsf and flag must be set) if 

349 # sigma < scalingFactor * seeing 

350 # Ensure that there is at least one combination of parameters that fail 

351 if not(min(gaapConfig.sigmas)/pixelScale < seeing*max(gaapConfig.scalingFactors)): 

352 raise InvalidParameterError("The config parameters do not trigger a measurement failure. " 

353 "Consider including lower values in ``sigmas`` and/or larger values " 

354 "for ``scalingFactors``") 

355 # Ensure that the measurement is not a complete failure 

356 self.assertFalse(record[algName + "_flag"]) 

357 self.assertFalse(record[algName + "_flag_edge"]) 

358 # Ensure that flag_bigPsf is set if sigma < scalingFactor * seeing 

359 for scalingFactor, sigma in itertools.product(gaapConfig.scalingFactors, gaapConfig.sigmas): 

360 targetSigma = scalingFactor*seeing 

361 baseName = gaapConfig._getGaapResultName(scalingFactor, sigma, algName) 

362 # Give some leeway for the edge case. 

363 if targetSigma - sigma/pixelScale >= -1e-10: 

364 self.assertTrue(record[baseName+"_flag_bigPsf"]) 

365 self.assertTrue(record[baseName+"_flag"]) 

366 else: 

367 self.assertFalse(record[baseName+"_flag_bigPsf"]) 

368 self.assertFalse(record[baseName+"_flag"]) 

369 

370 # Ensure that flag_bigPsf is set if OptimalShape is not large enough. 

371 if gaapConfig.doOptimalPhotometry: 

372 aperShape = afwTable.QuadrupoleKey(schema[schema.join(algName, "OptimalShape")]).get(record) 

373 for scalingFactor in gaapConfig.scalingFactors: 

374 targetSigma = scalingFactor*seeing 

375 baseName = gaapConfig._getGaapResultName(scalingFactor, "Optimal", algName) 

376 try: 

377 afwGeom.Quadrupole(aperShape.getParameterVector()-[targetSigma**2, targetSigma**2, 0.0], 

378 normalize=True) 

379 self.assertFalse(record[baseName + "_flag_bigPsf"]) 

380 except InvalidParameterError: 

381 self.assertTrue(record[baseName + "_flag_bigPsf"]) 

382 

383 # Ensure that the edge flag is set for the source at the corner. 

384 record = catalog[2] 

385 algorithm.measure(record, exposure) 

386 self.assertTrue(record[algName + "_flag_edge"]) 

387 self.assertFalse(record[algName + "_flag"]) 

388 

389 def recordPsfShape(self, catalog) -> None: 

390 """Record PSF shapes under the appropriate fields in ``catalog``. 

391 

392 This method must be called after the dataset is realized and a catalog 

393 is returned by the `realize` method. It assumes that the schema is 

394 non-minimal and has "psfShape_xx", "psfShape_yy" and "psfShape_xy" 

395 fields setup 

396 

397 Parameters 

398 ---------- 

399 catalog : `~lsst.afw.table.SourceCatalog` 

400 A source catalog containing records of the simulated sources. 

401 """ 

402 psfShapeKey = afwTable.QuadrupoleKey(catalog.schema["slot_PsfShape"]) 

403 for record in catalog: 

404 record.set(psfShapeKey, self.dataset.psfShape) 

405 

406 @staticmethod 

407 def invertQuadrupole(shape: afwGeom.Quadrupole) -> afwGeom.Quadrupole: 

408 """Compute the Quadrupole object corresponding to the inverse matrix. 

409 

410 If M = [[Q.getIxx(), Q.getIxy()], 

411 [Q.getIxy(), Q.getIyy()]] 

412 

413 for the input quadrupole Q, the returned quadrupole R corresponds to 

414 

415 M^{-1} = [[R.getIxx(), R.getIxy()], 

416 [R.getIxy(), R.getIyy()]]. 

417 """ 

418 invShape = afwGeom.Quadrupole(shape.getIyy(), shape.getIxx(), -shape.getIxy()) 

419 invShape.scale(1./shape.getDeterminantRadius()**2) 

420 return invShape 

421 

422 @lsst.utils.tests.methodParameters(gaussianizationMethod=("auto", "overlap-add", "direct", "fft")) 

423 def testGalaxyPhotometry(self, gaussianizationMethod): 

424 """Test GAaP fluxes for extended sources. 

425 

426 Create and run a SingleFrameMeasurementTask with GAaP plugin and reuse 

427 its outputs as reference for ForcedGaapFluxPlugin. In both cases, 

428 the measured flux is compared with the analytical expectation. 

429 

430 For a Gaussian source with intrinsic shape S and intrinsic aperture W, 

431 the GAaP flux is defined as (Eq. A16 of Kuijken et al. 2015) 

432 :math:`\\frac{F}{2\\pi\\det(S)}\\int\\mathrm{d}x\\exp(-x^T(S^{-1}+W^{-1})x/2)` 

433 :math:`F\\frac{\\det(S^{-1})}{\\det(S^{-1}+W^{-1})}` 

434 """ 

435 algName = "ext_gaap_GaapFlux" 

436 dependencies = ("base_SdssShape",) 

437 sfmConfig = self.makeSingleFrameMeasurementConfig(algName, dependencies=dependencies) 

438 forcedConfig = self.makeForcedMeasurementConfig(algName, dependencies=dependencies) 

439 # Turn on optimal photometry explicitly 

440 sfmConfig.plugins[algName].doOptimalPhotometry = True 

441 forcedConfig.plugins[algName].doOptimalPhotometry = True 

442 sfmConfig.plugins[algName].gaussianizationMethod = gaussianizationMethod 

443 forcedConfig.plugins[algName].gaussianizationMethod = gaussianizationMethod 

444 

445 algMetadata = lsst.daf.base.PropertyList() 

446 sfmTask = self.makeSingleFrameMeasurementTask(config=sfmConfig, algMetadata=algMetadata) 

447 forcedTask = self.makeForcedMeasurementTask(config=forcedConfig, algMetadata=algMetadata, 

448 refSchema=sfmTask.schema) 

449 

450 refExposure, refCatalog = self.dataset.realize(0.0, sfmTask.schema) 

451 self.recordPsfShape(refCatalog) 

452 sfmTask.run(refCatalog, refExposure) 

453 

454 # Check if the measured values match the expectations from 

455 # analytical Gaussian integrals 

456 recordId = 1 # Elliptical Gaussian galaxy 

457 refRecord = refCatalog[recordId] 

458 refWcs = self.dataset.exposure.getWcs() 

459 schema = refRecord.schema 

460 trueFlux = refRecord["truth_instFlux"] 

461 intrinsicShapeVector = afwTable.QuadrupoleKey(schema["truth"]).get(refRecord).getParameterVector() \ 

462 - afwTable.QuadrupoleKey(schema["slot_PsfShape"]).get(refRecord).getParameterVector() 

463 intrinsicShape = afwGeom.Quadrupole(intrinsicShapeVector) 

464 invIntrinsicShape = self.invertQuadrupole(intrinsicShape) 

465 # Assert that the measured fluxes agree with analytical expectations. 

466 for sigma in sfmTask.config.plugins[algName]._sigmas: 

467 if sigma == "Optimal": 

468 aperShape = afwTable.QuadrupoleKey(schema[f"{algName}_OptimalShape"]).get(refRecord) 

469 else: 

470 aperShape = afwGeom.Quadrupole(sigma**2, sigma**2, 0.0) 

471 aperShape.transformInPlace(refWcs.linearizeSkyToPixel(refRecord.getCentroid(), 

472 geom.arcseconds).getLinear()) 

473 

474 invAperShape = self.invertQuadrupole(aperShape) 

475 analyticalFlux = trueFlux*(invIntrinsicShape.getDeterminantRadius() 

476 / invIntrinsicShape.convolve(invAperShape).getDeterminantRadius())**2 

477 for scalingFactor in sfmTask.config.plugins[algName].scalingFactors: 

478 baseName = sfmTask.plugins[algName].ConfigClass._getGaapResultName(scalingFactor, 

479 sigma, algName) 

480 instFlux = refRecord.get(f"{baseName}_instFlux") 

481 self.assertFloatsAlmostEqual(instFlux, analyticalFlux, rtol=5e-3) 

482 

483 measWcs = self.dataset.makePerturbedWcs(refWcs, randomSeed=15) 

484 measDataset = self.dataset.transform(measWcs) 

485 measExposure, truthCatalog = measDataset.realize(0.0, schema) 

486 measCatalog = forcedTask.generateMeasCat(measExposure, refCatalog, refWcs) 

487 forcedTask.attachTransformedFootprints(measCatalog, refCatalog, measExposure, refWcs) 

488 forcedTask.run(measCatalog, measExposure, refCatalog, refWcs) 

489 

490 fullTransform = afwGeom.makeWcsPairTransform(refWcs, measWcs) 

491 localTransform = afwGeom.linearizeTransform(fullTransform, refRecord.getCentroid()).getLinear() 

492 intrinsicShape.transformInPlace(localTransform) 

493 invIntrinsicShape = self.invertQuadrupole(intrinsicShape) 

494 measRecord = measCatalog[recordId] 

495 

496 # Since measCatalog and refCatalog differ only by WCS, the GAaP flux 

497 # measured through consistent apertures must agree with each other. 

498 for sigma in forcedTask.config.plugins[algName]._sigmas: 

499 if sigma == "Optimal": 

500 aperShape = afwTable.QuadrupoleKey(measRecord.schema[f"{algName}_" 

501 "OptimalShape"]).get(measRecord) 

502 else: 

503 aperShape = afwGeom.Quadrupole(sigma**2, sigma**2, 0.0) 

504 aperShape.transformInPlace(measWcs.linearizeSkyToPixel(measRecord.getCentroid(), 

505 geom.arcseconds).getLinear()) 

506 

507 invAperShape = self.invertQuadrupole(aperShape) 

508 analyticalFlux = trueFlux*(invIntrinsicShape.getDeterminantRadius() 

509 / invIntrinsicShape.convolve(invAperShape).getDeterminantRadius())**2 

510 for scalingFactor in forcedTask.config.plugins[algName].scalingFactors: 

511 baseName = forcedTask.plugins[algName].ConfigClass._getGaapResultName(scalingFactor, 

512 sigma, algName) 

513 instFlux = measRecord.get(f"{baseName}_instFlux") 

514 # The measurement in the measRecord must be consistent with 

515 # the same in the refRecord in addition to analyticalFlux. 

516 self.assertFloatsAlmostEqual(instFlux, refRecord.get(f"{baseName}_instFlux"), rtol=5e-3) 

517 self.assertFloatsAlmostEqual(instFlux, analyticalFlux, rtol=5e-3) 

518 

519 def getFluxErrScaling(self, kernel, aperShape): 

520 """Returns the value by which the standard error has to be scaled due 

521 to noise correlations. 

522 

523 This is an alternative implementation to the `_getFluxErrScaling` 

524 method of `BaseGaapFluxPlugin`, but is less efficient. 

525 

526 Parameters 

527 ---------- 

528 `kernel` : `~lsst.afw.math.Kernel` 

529 The PSF-Gaussianization kernel. 

530 

531 Returns 

532 ------- 

533 fluxErrScaling : `float` 

534 The factor by which the standard error on GAaP flux must be scaled. 

535 """ 

536 kim = afwImage.ImageD(kernel.getDimensions()) 

537 kernel.computeImage(kim, False) 

538 weight = galsim.Image(np.zeros_like(kim.array)) 

539 aperSigma = aperShape.getDeterminantRadius() 

540 trace = aperShape.getIxx() + aperShape.getIyy() 

541 distortion = galsim.Shear(e1=(aperShape.getIxx()-aperShape.getIyy())/trace, 

542 e2=2*aperShape.getIxy()/trace) 

543 gauss = galsim.Gaussian(sigma=aperSigma, flux=2*np.pi*aperSigma**2).shear(distortion) 

544 weight = gauss.drawImage(image=weight, scale=1.0, method='no_pixel') 

545 kwarr = scipy.signal.convolve2d(weight.array, kim.array, boundary='fill') 

546 fluxErrScaling = np.sqrt(np.sum(kwarr*kwarr)) 

547 fluxErrScaling /= np.sqrt(np.pi*aperSigma**2) 

548 return fluxErrScaling 

549 

550 def testCorrelatedNoiseError(self, sigmas=[0.6, 0.8], scalingFactors=[1.15, 1.2, 1.25, 1.3, 1.4]): 

551 """Test the scaling to standard error due to correlated noise. 

552 

553 The uncertainty estimate on GAaP fluxes is scaled by an amount 

554 determined by the auto-correlation function of the PSF-matching kernel; 

555 see Eqs. A11 & A17 of Kuijken et al. (2015). This test ensures that the 

556 calculation of the scaling factors matches the analytical expression 

557 when the PSF-matching kernel is a Gaussian. 

558 

559 Parameters 

560 ---------- 

561 sigmas : `list` [`float`], optional 

562 A list of effective Gaussian aperture sizes. 

563 scalingFactors : `list` [`float`], optional 

564 A list of factors by which the PSF size must be scaled. 

565 

566 Notes 

567 ----- 

568 This unit test tests internal states of the plugin for accuracy and is 

569 specific to the implementation. It uses private variables as a result 

570 and intentionally breaks encapsulation. 

571 """ 

572 gaapConfig = lsst.meas.extensions.gaap.SingleFrameGaapFluxConfig(sigmas=sigmas, 

573 scalingFactors=scalingFactors) 

574 gaapConfig.scaleByFwhm = True 

575 

576 algorithm, schema = self.makeAlgorithm(gaapConfig) 

577 exposure, catalog = self.dataset.realize(0.0, schema) 

578 wcs = exposure.getWcs() 

579 record = catalog[0] 

580 center = self.center 

581 seeing = exposure.getPsf().computeShape(center).getDeterminantRadius() 

582 for scalingFactor in gaapConfig.scalingFactors: 

583 targetSigma = scalingFactor*seeing 

584 modelPsf = afwDetection.GaussianPsf(algorithm.config._modelPsfDimension, 

585 algorithm.config._modelPsfDimension, 

586 targetSigma) 

587 result = algorithm._gaussianize(exposure, modelPsf, record) 

588 kernel = result.psfMatchingKernel 

589 kernelAcf = algorithm._computeKernelAcf(kernel) 

590 for sigma in gaapConfig.sigmas: 

591 intrinsicShape = afwGeom.Quadrupole(sigma**2, sigma**2, 0.0) 

592 intrinsicShape.transformInPlace(wcs.linearizeSkyToPixel(center, geom.arcseconds).getLinear()) 

593 aperShape = afwGeom.Quadrupole(intrinsicShape.getParameterVector() 

594 - [targetSigma**2, targetSigma**2, 0.0]) 

595 fluxErrScaling1 = algorithm._getFluxErrScaling(kernelAcf, aperShape) 

596 fluxErrScaling2 = self.getFluxErrScaling(kernel, aperShape) 

597 

598 # The PSF matching kernel is a Gaussian of sigma^2 = (f^2-1)s^2 

599 # where f is the scalingFactor and s is the original seeing. 

600 # The integral of ACF of the kernel times the elliptical 

601 # Gaussian described by aperShape is given below. 

602 sigma /= wcs.getPixelScale().asArcseconds() 

603 analyticalValue = ((sigma**2 - (targetSigma)**2)/(sigma**2-seeing**2))**0.5 

604 self.assertFloatsAlmostEqual(fluxErrScaling1, analyticalValue, rtol=1e-4) 

605 self.assertFloatsAlmostEqual(fluxErrScaling1, fluxErrScaling2, rtol=1e-4) 

606 

607 # Try with an elliptical aperture. This is a proxy for 

608 # optimal aperture, since we do not actually measure anything. 

609 aperShape = afwGeom.Quadrupole(8, 6, 3) 

610 fluxErrScaling1 = algorithm._getFluxErrScaling(kernelAcf, aperShape) 

611 fluxErrScaling2 = self.getFluxErrScaling(kernel, aperShape) 

612 self.assertFloatsAlmostEqual(fluxErrScaling1, fluxErrScaling2, rtol=1e-4) 

613 

614 @lsst.utils.tests.methodParameters(noise=(0.001, 0.01, 0.1)) 

615 def testMonteCarlo(self, noise, recordId=1, sigmas=[0.7, 1.0, 1.25], 

616 scalingFactors=[1.1, 1.15, 1.2, 1.3, 1.4]): 

617 """Test GAaP flux uncertainties. 

618 

619 This test should demonstate that the estimated flux uncertainties agree 

620 with those from Monte Carlo simulations. 

621 

622 Parameters 

623 ---------- 

624 noise : `float` 

625 The RMS value of the Gaussian noise field divided by the total flux 

626 of the source. 

627 recordId : `int`, optional 

628 The source Id in the test dataset to measure. 

629 sigmas : `list` [`float`], optional 

630 The list of sigmas (in pixels) to construct the `GaapFluxConfig`. 

631 scalingFactors : `list` [`float`], optional 

632 The list of scaling factors to construct the `GaapFluxConfig`. 

633 """ 

634 gaapConfig = lsst.meas.extensions.gaap.SingleFrameGaapFluxConfig(sigmas=sigmas, 

635 scalingFactors=scalingFactors) 

636 gaapConfig.scaleByFwhm = True 

637 gaapConfig.doPsfPhotometry = True 

638 gaapConfig.doOptimalPhotometry = True 

639 

640 algorithm, schema = self.makeAlgorithm(gaapConfig) 

641 # Make a noiseless exposure and keep measurement record for reference 

642 exposure, catalog = self.dataset.realize(0.0, schema) 

643 if gaapConfig.doOptimalPhotometry: 

644 self.recordPsfShape(catalog) 

645 recordNoiseless = catalog[recordId] 

646 totalFlux = recordNoiseless["truth_instFlux"] 

647 algorithm.measure(recordNoiseless, exposure) 

648 

649 nSamples = 1024 

650 catalog = afwTable.SourceCatalog(schema) 

651 for repeat in range(nSamples): 

652 exposure, cat = self.dataset.realize(noise*totalFlux, schema, randomSeed=repeat) 

653 if gaapConfig.doOptimalPhotometry: 

654 self.recordPsfShape(cat) 

655 record = cat[recordId] 

656 algorithm.measure(record, exposure) 

657 catalog.append(record) 

658 

659 catalog = catalog.copy(deep=True) 

660 for baseName in gaapConfig.getAllGaapResultNames(): 

661 instFluxKey = schema.join(baseName, "instFlux") 

662 instFluxErrKey = schema.join(baseName, "instFluxErr") 

663 instFluxMean = catalog[instFluxKey].mean() 

664 instFluxErrMean = catalog[instFluxErrKey].mean() 

665 instFluxStdDev = catalog[instFluxKey].std() 

666 

667 # GAaP fluxes are not meant to be total fluxes. 

668 # We compare the mean of the noisy measurements to its 

669 # corresponding noiseless measurement instead of the true value 

670 instFlux = recordNoiseless[instFluxKey] 

671 self.assertFloatsAlmostEqual(instFluxErrMean, instFluxStdDev, rtol=0.02) 

672 self.assertLess(abs(instFluxMean - instFlux), 2.0*instFluxErrMean/nSamples**0.5) 

673 

674 

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

676 pass 

677 

678 

679def setup_module(module, backend="virtualDevice"): 

680 lsst.utils.tests.init() 

681 try: 

682 afwDisplay.setDefaultBackend(backend) 

683 except Exception: 

684 print("Unable to configure display backend: %s" % backend) 

685 

686 

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

688 import sys 

689 

690 from argparse import ArgumentParser 

691 parser = ArgumentParser() 

692 parser.add_argument('--backend', type=str, default="virtualDevice", 

693 help="The backend to use, e.g. 'ds9'. Be sure to 'setup display_<backend>'") 

694 args = parser.parse_args() 

695 

696 setup_module(sys.modules[__name__], backend=args.backend) 

697 unittest.main()