Coverage for tests/test_diaPipe.py: 99%

531 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-14 02:09 -0800

1# This file is part of ap_association. 

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 contextlib 

23import tempfile 

24import unittest 

25from unittest.mock import patch, MagicMock, DEFAULT 

26import warnings 

27 

28import numpy as np 

29import pandas as pd 

30import astropy.table as tb 

31import astropy.units as u 

32 

33import lsst.afw.table as afwTable 

34import lsst.dax.apdb as daxApdb 

35from lsst.meas.base import DetectorVisitIdGeneratorConfig, IdGenerator 

36import lsst.pex.config as pexConfig 

37import lsst.pipe.base as pipeBase 

38import lsst.utils.tests 

39from lsst.pipe.base.testUtils import assertValidOutput 

40 

41from lsst.ap.association import DiaPipelineTask 

42from lsst.ap.association.utils import getRegion 

43from lsst.pipe.tasks.schemaUtils import convertDataFrameToSdmSchema 

44from utils_tests import makeExposure, makeDiaObjects, makeDiaSources, makeDiaForcedSources, \ 

45 makeSolarSystemSources 

46 

47 

48def _makeMockDataFrame(): 

49 """Create a new mock of a DataFrame. 

50 

51 Returns 

52 ------- 

53 mock : `unittest.mock.Mock` 

54 A mock guaranteed to accept all operations used by `pandas.DataFrame`. 

55 """ 

56 with warnings.catch_warnings(): 

57 # spec triggers deprecation warnings on DataFrame, but will 

58 # automatically adapt to any removals. 

59 warnings.simplefilter("ignore", category=DeprecationWarning) 

60 return MagicMock(spec=pd.DataFrame()) 

61 

62 

63def _makeMockTable(): 

64 """Create a new mock of a Table. 

65 

66 Returns 

67 ------- 

68 mock : `unittest.mock.Mock` 

69 A mock guaranteed to accept all operations used by `astropy.table.Table`. 

70 """ 

71 with warnings.catch_warnings(): 

72 # spec triggers deprecation warnings on DataFrame, but will 

73 # automatically adapt to any removals. 

74 warnings.simplefilter("ignore", category=DeprecationWarning) 

75 return MagicMock(spec=tb.Table()) 

76 

77 

78class TestDiaPipelineTask(unittest.TestCase): 

79 

80 @classmethod 

81 def _makeDefaultConfig(cls, config_file, **kwargs): 

82 config = DiaPipelineTask.ConfigClass() 

83 config.apdb_config_url = config_file 

84 config.update(**kwargs) 

85 return config 

86 

87 def setUp(self): 

88 # Create an instance of random generator with fixed seed. 

89 rng = np.random.default_rng(1234) 

90 self.rng = rng 

91 

92 # schemas are persisted in both Gen 2 and Gen 3 butler as prototypical catalogs 

93 srcSchema = afwTable.SourceTable.makeMinimalSchema() 

94 srcSchema.addField("base_PixelFlags_flag", type="Flag") 

95 srcSchema.addField("base_PixelFlags_flag_offimage", type="Flag") 

96 self.srcSchema = afwTable.SourceCatalog(srcSchema) 

97 self.exposure = makeExposure(False, False) 

98 self.diffim = makeExposure(False, False) 

99 self.template = makeExposure(False, False) 

100 self.diaObjects = makeDiaObjects(20, self.exposure, rng) 

101 self.diaSources = makeDiaSources( 

102 100, self.diaObjects["diaObjectId"].to_numpy(), self.exposure, rng) 

103 self.diaForcedSources = makeDiaForcedSources( 

104 200, self.diaObjects["diaObjectId"].to_numpy(), self.exposure, rng) 

105 self.ssSources = makeSolarSystemSources( 

106 20, self.diaObjects["diaObjectId"].to_numpy(), self.exposure, rng) 

107 

108 sqlite_file = tempfile.NamedTemporaryFile() 

109 self.addCleanup(sqlite_file.close) 

110 self.config_file = tempfile.NamedTemporaryFile() 

111 self.addCleanup(self.config_file.close) 

112 apdb_config = daxApdb.ApdbSql.init_database(db_url=f"sqlite:///{sqlite_file.name}") 

113 apdb_config.save(self.config_file.name) 

114 

115 def testRun(self): 

116 """Test running while creating and packaging alerts. 

117 """ 

118 self._testRun(doPackageAlerts=True, doSolarSystemAssociation=True, doReloadDiaObjects=False) 

119 

120 def testRunWithSolarSystemAssociation(self): 

121 """Test running while creating and packaging alerts. 

122 """ 

123 self._testRun(doPackageAlerts=False, doSolarSystemAssociation=True, doReloadDiaObjects=False) 

124 

125 def testRunWithAlerts(self): 

126 """Test running while creating and packaging alerts. 

127 """ 

128 self._testRun(doPackageAlerts=True, doSolarSystemAssociation=False, doReloadDiaObjects=False) 

129 

130 def testRunWithoutAlertsOrSolarSystem(self): 

131 """Test running without creating and packaging alerts. 

132 """ 

133 self._testRun(doPackageAlerts=False, doSolarSystemAssociation=False, doReloadDiaObjects=False) 

134 

135 def testRunWithReload(self): 

136 """Test running with reloading DiaObjects. 

137 """ 

138 self._testRun(doPackageAlerts=False, doSolarSystemAssociation=False, doReloadDiaObjects=True) 

139 

140 def testRunWithReloadAndSolarSystem(self): 

141 """Test running with solar system association and reloading DiaObjects. 

142 """ 

143 self._testRun(doPackageAlerts=False, doSolarSystemAssociation=True, doReloadDiaObjects=True) 

144 

145 def testRunWithReloadAndAlerts(self): 

146 """Test running with reloading DiaObjects while creating and packaging alerts. 

147 """ 

148 self._testRun(doPackageAlerts=True, doSolarSystemAssociation=False, doReloadDiaObjects=True) 

149 

150 def testRunDisableDeprecatedDoRunForcedMeasurement(self): 

151 """Test running with forced sources disabled. 

152 """ 

153 self._testRun(doPackageAlerts=True, doSolarSystemAssociation=False, doReloadDiaObjects=True, 

154 doRunForcedMeasurement=False, subtasksToMock=["diaCalculation", ] 

155 ) 

156 

157 def testRunWithReloadAllApdbCatalogs(self): 

158 """Test running with reloading the DiaSource history. 

159 """ 

160 self._testRun(doPackageAlerts=False, doSolarSystemAssociation=False, doReloadDiaObjects=True, 

161 doReloadAllApdbCatalogs=True) 

162 

163 def testRunWithReloadAllApdbCatalogsAndAlerts(self): 

164 """Test reloading the DiaSource history while packaging alerts. 

165 """ 

166 self._testRun(doPackageAlerts=True, doSolarSystemAssociation=False, doReloadDiaObjects=True, 

167 doReloadAllApdbCatalogs=True) 

168 

169 def testMissingMpcOrbitsSchema(self): 

170 """Test that packaging solar system alerts requires an mpc_orbits 

171 table schema. 

172 """ 

173 with patch("lsst.ap.association.diaPipe.readMpcOrbitsSchema", return_value=None): 

174 config = self._makeDefaultConfig(config_file=self.config_file.name, 

175 doPackageAlerts=True, doSolarSystemAssociation=True) 

176 with self.assertRaisesRegex(ValueError, "mpc_orbits"): 

177 DiaPipelineTask(config=config) 

178 for doPackageAlerts, doSolarSystemAssociation in [(True, False), (False, True)]: 

179 config = self._makeDefaultConfig(config_file=self.config_file.name, 

180 doPackageAlerts=doPackageAlerts, 

181 doSolarSystemAssociation=doSolarSystemAssociation) 

182 task = DiaPipelineTask(config=config) 

183 self.assertIsNone(task.schema["mpc_orbits"]) 

184 

185 def testRunWithReloadAllApdbCatalogsOnly(self): 

186 """Test that reloading everything implies the DiaObject reload. 

187 """ 

188 self._testRun(doPackageAlerts=False, doSolarSystemAssociation=False, doReloadDiaObjects=False, 

189 doReloadAllApdbCatalogs=True) 

190 

191 def _testRun(self, doPackageAlerts=False, doSolarSystemAssociation=False, 

192 doReloadDiaObjects=False, doReloadAllApdbCatalogs=False, subtasksToMock=None, **kwargs): 

193 """Test the normal workflow of each ap_pipe step. 

194 """ 

195 config = self._makeDefaultConfig( 

196 config_file=self.config_file.name, 

197 doPackageAlerts=doPackageAlerts, 

198 doSolarSystemAssociation=doSolarSystemAssociation, 

199 doReloadDiaObjects=doReloadDiaObjects, 

200 doReloadAllApdbCatalogs=doReloadAllApdbCatalogs, 

201 **kwargs 

202 ) 

203 task = DiaPipelineTask(config=config) 

204 # Set DataFrame index testing to always return False. Mocks return 

205 # true for this check otherwise. 

206 task.testDataFrameIndex = lambda x: False 

207 diaSrc = _makeMockDataFrame() 

208 ssObjects = _makeMockTable() 

209 

210 # Each of these subtasks should be called once during diaPipe 

211 # execution. We use mocks here to check they are being executed 

212 # appropriately. 

213 if subtasksToMock is None: 

214 subtasksToMock = ["diaCalculation", "diaForcedSource", ] 

215 if doPackageAlerts: 

216 subtasksToMock.append("alertPackager") 

217 else: 

218 self.assertFalse(hasattr(task, "alertPackager")) 

219 

220 if not doSolarSystemAssociation: 

221 self.assertFalse(hasattr(task, "solarSystemAssociator")) 

222 

223 def concatMock(_data, **_kwargs): 

224 return _makeMockDataFrame() 

225 

226 # Mock out the run() methods of these Tasks to ensure they 

227 # return data in the correct form. 

228 def solarSystemAssociator_run(unAssocDiaSources, solarSystemObjectTable, visitInfo, 

229 bbox, wcs): 

230 return lsst.pipe.base.Struct(nTotalSsObjects=42, 

231 nAssociatedSsObjects=30, 

232 ssoAssocDiaSources=_makeMockTable(), 

233 unAssocDiaSources=_makeMockTable(), 

234 associatedSsSources=_makeMockTable(), 

235 unassociatedSsObjects=_makeMockTable()) 

236 

237 def associator_run(table, diaObjects, schema=None): 

238 return lsst.pipe.base.Struct(nUpdatedDiaObjects=2, nUnassociatedDiaObjects=3, 

239 matchedDiaSources=_makeMockDataFrame(), 

240 unAssocDiaSources=_makeMockDataFrame()) 

241 

242 def loadObjects_run(region, preloadedDiaObjects): 

243 task.metadata['loadRefreshedDiaObjectsStartUtc'] = 1.234 

244 task.metadata['loadRefreshedDiaObjectsEndUtc'] = 5.678 

245 return self.diaObjects 

246 

247 def loadSources_run(region, diaObjects, visitTime): 

248 task.metadata['loadRefreshedDiaSourcesStartUtc'] = 1.234 

249 task.metadata['loadRefreshedDiaSourcesEndUtc'] = 5.678 

250 return self.diaSources 

251 

252 def loadForcedSources_run(region, diaObjects, visitTime): 

253 task.metadata['loadRefreshedDiaForcedSourcesStartUtc'] = 1.234 

254 task.metadata['loadRefreshedDiaForcedSourcesEndUtc'] = 5.678 

255 return self.diaForcedSources 

256 

257 def updateObjectTableMock(diaObjects, diaSources): 

258 pass 

259 

260 def _selectGoodDiaObjects(diaObjectCat, mergedDiaSourceHistory): 

261 return diaObjectCat.copy(deep=True) 

262 

263 # apdb isn't a subtask, but still needs to be mocked out for correct 

264 # execution in the test environment. 

265 with patch.multiple(task, **{task: DEFAULT for task in subtasksToMock + ["apdb"]}), \ 

266 patch('lsst.ap.association.diaPipe.pd.concat', side_effect=concatMock), \ 

267 patch('lsst.ap.association.diaPipe.DiaPipelineTask.updateObjectTable', 

268 side_effect=updateObjectTableMock), \ 

269 patch('lsst.ap.association.diaPipe.DiaPipelineTask._selectGoodDiaObjects', 

270 side_effect=_selectGoodDiaObjects), \ 

271 patch('lsst.ap.association.diaPipe.DiaPipelineTask.loadRefreshedDiaObjects', 

272 side_effect=loadObjects_run) as loadObjectsRun, \ 

273 patch('lsst.ap.association.diaPipe.DiaPipelineTask.loadRefreshedDiaSources', 

274 side_effect=loadSources_run) as loadSourcesRun, \ 

275 patch('lsst.ap.association.diaPipe.DiaPipelineTask.loadRefreshedDiaForcedSources', 

276 side_effect=loadForcedSources_run) as loadForcedSourcesRun, \ 

277 patch('lsst.ap.association.association.AssociationTask.run', 

278 side_effect=associator_run) as mainRun, \ 

279 patch('lsst.pipe.tasks.ssoAssociation.SolarSystemAssociationTask.run', 

280 side_effect=solarSystemAssociator_run) as ssRun: 

281 if doPackageAlerts: 

282 task.alertPackager.findMissingDiaSourceColumns.return_value = [] 

283 

284 result = task.run(diaSrc, 

285 None, 

286 self.diffim, 

287 self.exposure, 

288 self.template, 

289 # `run` sees None when the preloaded 

290 # connections have been removed. 

291 preloadedDiaObjects=None if doReloadAllApdbCatalogs else self.diaObjects, 

292 preloadedDiaSources=None if doReloadAllApdbCatalogs else self.diaSources, 

293 preloadedDiaForcedSources=( 

294 None if doReloadAllApdbCatalogs else self.diaForcedSources), 

295 band="g", 

296 idGenerator=IdGenerator(), 

297 solarSystemObjectTable=ssObjects) 

298 for subtaskName in subtasksToMock: 

299 getattr(task, subtaskName).run.assert_called_once() 

300 assertValidOutput(task, result) 

301 # Exact type and contents of apdbMarker are undefined. 

302 self.assertIsInstance(result.apdbMarker, pexConfig.Config) 

303 meta = task.getFullMetadata() 

304 # Check that the expected metadata has been set. 

305 self.assertEqual(meta["diaPipe.numUpdatedDiaObjects"], 2) 

306 self.assertEqual(meta["diaPipe.numUnassociatedDiaObjects"], 3) 

307 # and that associators ran once or not at all. 

308 mainRun.assert_called_once() 

309 if doSolarSystemAssociation: 

310 ssRun.assert_called_once() 

311 else: 

312 ssRun.assert_not_called() 

313 # doReloadAllApdbCatalogs implies the DiaObject reload. 

314 if doReloadDiaObjects or doReloadAllApdbCatalogs: 

315 loadObjectsRun.assert_called_once() 

316 else: 

317 loadObjectsRun.assert_not_called() 

318 # These key names are shared with LoadDiaCatalogsTask so that both 

319 # tasks publish to the same Sasquatch topics. 

320 if doReloadAllApdbCatalogs: 

321 loadSourcesRun.assert_called_once() 

322 loadForcedSourcesRun.assert_called_once() 

323 self.assertGreater(meta["diaPipe.loadDiaSourcesDuration"], 0) 

324 self.assertGreater(meta["diaPipe.loadDiaForcedSourcesDuration"], 0) 

325 else: 

326 loadSourcesRun.assert_not_called() 

327 loadForcedSourcesRun.assert_not_called() 

328 self.assertEqual(meta["diaPipe.loadDiaSourcesDuration"], -1) 

329 self.assertEqual(meta["diaPipe.loadDiaForcedSourcesDuration"], -1) 

330 

331 def test_runRejectsIncompleteDiaSourceHistory(self): 

332 """Test that DiaSource history lacking columns that alerts require 

333 stops processing before anything is written to the APDB. 

334 """ 

335 config = self._makeDefaultConfig(config_file=self.config_file.name, 

336 doPackageAlerts=True, 

337 doReloadDiaObjects=False) 

338 task = DiaPipelineTask(config=config) 

339 history = self.diaSources.drop(columns=["templateVersion", "mixedInstruments"]) 

340 with patch.object(task, "apdb") as apdb, \ 

341 self.assertRaisesRegex(ValueError, "before writing to the APDB.*: " 

342 "templateVersion, mixedInstruments\\."): 

343 task.run(_makeMockDataFrame(), 

344 None, 

345 self.diffim, 

346 self.exposure, 

347 self.template, 

348 preloadedDiaObjects=self.diaObjects, 

349 preloadedDiaSources=history, 

350 preloadedDiaForcedSources=self.diaForcedSources, 

351 band="g", 

352 idGenerator=IdGenerator(), 

353 solarSystemObjectTable=_makeMockTable()) 

354 apdb.store.assert_not_called() 

355 

356 def test_reloadAllApdbCatalogsRemovesPreloadedConnections(self): 

357 """Test that reloading drops the preloaded catalog connections. 

358 """ 

359 preloaded = {"preloadedDiaObjects", "preloadedDiaSources", "preloadedDiaForcedSources"} 

360 

361 config = self._makeDefaultConfig(config_file=self.config_file.name, 

362 doReloadAllApdbCatalogs=False) 

363 connections = config.connections.ConnectionsClass(config=config) 

364 self.assertTrue(preloaded <= set(connections.inputs)) 

365 

366 config = self._makeDefaultConfig(config_file=self.config_file.name, 

367 doReloadAllApdbCatalogs=True) 

368 connections = config.connections.ConnectionsClass(config=config) 

369 self.assertFalse(preloaded & set(connections.inputs)) 

370 

371 def test_runQuantumOmitsRemovedPreloadedInputs(self): 

372 """Test that runQuantum passes only the preloaded inputs it has. 

373 

374 `run` defaults the preloaded catalogs to `None`, so runQuantum passes 

375 just the connections that survived, and must leave the loaded catalogs 

376 alone when they are present. 

377 """ 

378 preloaded = ["preloadedDiaObjects", "preloadedDiaSources", "preloadedDiaForcedSources"] 

379 loaded = {"preloadedDiaObjects": self.diaObjects, 

380 "preloadedDiaSources": self.diaSources, 

381 "preloadedDiaForcedSources": self.diaForcedSources} 

382 

383 def runQuantumKwargs(doReloadAllApdbCatalogs): 

384 config = self._makeDefaultConfig(config_file=self.config_file.name, 

385 doReloadAllApdbCatalogs=doReloadAllApdbCatalogs) 

386 task = DiaPipelineTask(config=config) 

387 # The quantum only carries the connections that survived. 

388 inputs = {"diaSourceTable": _makeMockDataFrame(), 

389 "diffIm": self.diffim, 

390 "exposure": self.exposure, 

391 "template": self.template, 

392 "solarSystemObjectTable": _makeMockTable()} 

393 if not doReloadAllApdbCatalogs: 

394 inputs.update(loaded) 

395 butlerQC = MagicMock() 

396 butlerQC.get.return_value = inputs 

397 with patch.object(DetectorVisitIdGeneratorConfig, "apply", return_value=IdGenerator()), \ 

398 patch.object(DiaPipelineTask, "run") as mockRun: 

399 task.runQuantum(butlerQC, MagicMock(), MagicMock()) 

400 return mockRun.call_args.kwargs 

401 

402 kwargs = runQuantumKwargs(True) 

403 for name in preloaded: 

404 self.assertNotIn(name, kwargs, msg=f"{name} should be left to the default") 

405 

406 kwargs = runQuantumKwargs(False) 

407 for name in preloaded: 

408 self.assertIs(kwargs[name], loaded[name], msg=f"{name} should be the loaded catalog") 

409 

410 def test_connectionsImageType(self): 

411 """Test that input_image_type sets the storage class of each image. 

412 """ 

413 expected = {"legacy": {"diffIm": "ExposureF", "exposure": "ExposureF", "template": "ExposureF"}, 

414 "future": {"diffIm": "DifferenceImage", "exposure": "VisitImage", 

415 "template": "DifferenceImage"}} 

416 for image_type, storageClasses in expected.items(): 

417 with self.subTest(image_type=image_type): 

418 config = self._makeDefaultConfig(config_file=self.config_file.name, 

419 input_image_type=image_type) 

420 connections = config.connections.ConnectionsClass(config=config) 

421 for name, storageClass in storageClasses.items(): 

422 self.assertEqual(getattr(connections, name).storageClass, storageClass) 

423 

424 def test_runQuantumFutureImages(self): 

425 """Test that runQuantum passes run() the legacy form of each 

426 future-mode image. 

427 """ 

428 config = self._makeDefaultConfig(config_file=self.config_file.name, input_image_type="future") 

429 task = DiaPipelineTask(config=config) 

430 legacy = {"diffIm": self.diffim, "exposure": self.exposure, "template": self.template} 

431 inputs = {"diaSourceTable": _makeMockDataFrame(), 

432 "solarSystemObjectTable": _makeMockTable(), 

433 "preloadedDiaObjects": self.diaObjects, 

434 "preloadedDiaSources": self.diaSources, 

435 "preloadedDiaForcedSources": self.diaForcedSources} 

436 for name, image in legacy.items(): 

437 inputs[name] = MagicMock() 

438 inputs[name].to_legacy.return_value = image 

439 butlerQC = MagicMock() 

440 butlerQC.get.return_value = inputs 

441 with patch.object(DetectorVisitIdGeneratorConfig, "apply", return_value=IdGenerator()), \ 

442 patch.object(DiaPipelineTask, "run") as mockRun: 

443 task.runQuantum(butlerQC, MagicMock(), MagicMock()) 

444 for name, image in legacy.items(): 

445 self.assertIs(mockRun.call_args.kwargs[name], image) 

446 

447 def test_runRequiresBandAndIdGenerator(self): 

448 """Test that `run` rejects the `None` defaults on required arguments. 

449 """ 

450 config = self._makeDefaultConfig(config_file=self.config_file.name) 

451 task = DiaPipelineTask(config=config) 

452 kwargs = {"diaSourceTable": _makeMockDataFrame(), 

453 "legacySolarSystemTable": None, 

454 "diffIm": self.diffim, 

455 "exposure": self.exposure, 

456 "template": self.template, 

457 "band": "g", 

458 "idGenerator": IdGenerator()} 

459 

460 with self.assertRaisesRegex(ValueError, "band"): 

461 task.run(**(kwargs | {"band": None})) 

462 with self.assertRaisesRegex(ValueError, "idGenerator"): 

463 task.run(**(kwargs | {"idGenerator": None})) 

464 

465 def test_loadRefreshedDiaObjectsNoPreloaded(self): 

466 """Test reloading DiaObjects when no preloaded catalog is available. 

467 """ 

468 config = self._makeDefaultConfig(config_file=self.config_file.name, 

469 doReloadAllApdbCatalogs=True) 

470 task = DiaPipelineTask(config=config) 

471 task.apdb.store(self.exposure.visitInfo.date.toAstropy() - 30*u.day, 

472 self.diaObjects, 

473 self.diaSources, 

474 self.diaForcedSources) 

475 

476 diaObjects = task.loadRefreshedDiaObjects(getRegion(self.exposure)) 

477 

478 self.assertEqual(len(diaObjects), len(self.diaObjects)) 

479 self.assertEqual(diaObjects.index.name, "diaObjectId") 

480 

481 def test_loadRefreshedDiaSources(self): 

482 """Test that the DiaSource history is reloaded from the APDB. 

483 """ 

484 config = self._makeDefaultConfig(config_file=self.config_file.name, 

485 doReloadAllApdbCatalogs=True) 

486 task = DiaPipelineTask(config=config) 

487 visitTime = self.exposure.visitInfo.date.toAstropy() 

488 # Store the history as though it were observed a month earlier. 

489 task.apdb.store(visitTime - 30*u.day, 

490 self.diaObjects, 

491 self.diaSources, 

492 self.diaForcedSources) 

493 

494 region = getRegion(self.exposure) 

495 diaSources = task.loadRefreshedDiaSources(region, self.diaObjects, visitTime) 

496 diaForcedSources = task.loadRefreshedDiaForcedSources(region, self.diaObjects, visitTime) 

497 

498 self.assertEqual(len(diaSources), len(self.diaSources)) 

499 self.assertEqual(len(diaForcedSources), len(self.diaForcedSources)) 

500 self.assertEqual(list(diaSources.index.names), ["diaObjectId", "band", "diaSourceId"]) 

501 self.assertEqual(list(diaForcedSources.index.names), ["diaObjectId", "diaForcedSourceId"]) 

502 self.assertFalse(diaSources.index.has_duplicates) 

503 self.assertFalse(diaForcedSources.index.has_duplicates) 

504 

505 def test_loadRefreshedDiaSourcesNoDiaObjects(self): 

506 """Test reloading the history when no DiaObjects are in range. 

507 """ 

508 config = self._makeDefaultConfig(config_file=self.config_file.name, 

509 doReloadAllApdbCatalogs=True) 

510 task = DiaPipelineTask(config=config) 

511 emptyDiaObjects = self.diaObjects.iloc[:0] 

512 region = getRegion(self.exposure) 

513 visitTime = self.exposure.visitInfo.date.toAstropy() 

514 

515 diaSources = task.loadRefreshedDiaSources(region, emptyDiaObjects, visitTime) 

516 diaForcedSources = task.loadRefreshedDiaForcedSources(region, emptyDiaObjects, visitTime) 

517 

518 self.assertTrue(diaSources.empty) 

519 self.assertTrue(diaForcedSources.empty) 

520 

521 def test_tooManyDiaObjectsError(self): 

522 maxNewDiaObjects = 100 

523 

524 nDiaSources = maxNewDiaObjects + 1 

525 diaSources = makeDiaSources(nDiaSources, np.zeros(nDiaSources), self.exposure, self.rng) 

526 

527 def runAndTestWithContextManager(threshold): 

528 config = self._makeDefaultConfig(config_file=self.config_file.name, 

529 doSolarSystemAssociation=False, 

530 filterUnAssociatedSources=False, 

531 maxNewDiaObjects=threshold, 

532 ) 

533 task = DiaPipelineTask(config=config) 

534 contextManager = self.assertRaises(pipeBase.AlgorithmError) if nDiaSources > threshold > 0 \ 

535 else contextlib.nullcontext() 

536 with contextManager: 

537 task.associateDiaSources( 

538 diaSources, 

539 None, 

540 None, 

541 self.diaObjects, 

542 ) 

543 # Test cases at, above, and below the threshold as well as at 0. 

544 runAndTestWithContextManager(0) 

545 runAndTestWithContextManager(maxNewDiaObjects - 1) 

546 runAndTestWithContextManager(maxNewDiaObjects) 

547 runAndTestWithContextManager(maxNewDiaObjects + 1) 

548 

549 def test_createDiaObjects(self): 

550 """Test that creating new DiaObjects works as expected. 

551 """ 

552 nSources = 5 

553 config = self._makeDefaultConfig(config_file=self.config_file.name, doPackageAlerts=False) 

554 task = DiaPipelineTask(config=config) 

555 diaSources = pd.DataFrame(data=[ 

556 {"ra": 0.04*idx, "dec": 0.04*idx, 

557 "diaSourceId": idx + 1 + nSources, "diaObjectId": 0, 

558 "ssObjectId": 0} 

559 for idx in range(nSources)]) 

560 

561 result = task.createNewDiaObjects(convertDataFrameToSdmSchema(task.schema, diaSources, "DiaSource", 

562 skipIndex=True)) 

563 self.assertEqual(nSources, len(result.newDiaObjects)) 

564 self.assertTrue(np.all(np.equal( 

565 result.diaSources["diaObjectId"].to_numpy(), 

566 result.diaSources["diaSourceId"].to_numpy()))) 

567 self.assertTrue(np.all(np.equal( 

568 result.newDiaObjects["diaObjectId"].to_numpy(), 

569 result.diaSources["diaSourceId"].to_numpy()))) 

570 

571 def test_purgeDiaObjects(self): 

572 """Remove diaOjects that are outside an image's bounding box. 

573 """ 

574 

575 config = self._makeDefaultConfig(config_file=self.config_file.name, doPackageAlerts=False) 

576 task = DiaPipelineTask(config=config) 

577 exposure = makeExposure(False, False) 

578 nObj0 = 20 

579 

580 # Create diaObjects 

581 diaObjects = makeDiaObjects(nObj0, exposure, self.rng) 

582 # Shrink the bounding box so that some of the diaObjects will be outside 

583 bbox = exposure.getBBox() 

584 size = np.minimum(bbox.getHeight(), bbox.getWidth()) 

585 bbox.grow(-size//4) 

586 exposureCut = exposure[bbox] 

587 sizeCut = np.minimum(bbox.getHeight(), bbox.getWidth()) 

588 buffer = 10 

589 bbox.grow(buffer) 

590 

591 def check_diaObjects(bbox, wcs, diaObjects): 

592 raVals = diaObjects.ra.to_numpy() 

593 decVals = diaObjects.dec.to_numpy() 

594 xVals, yVals = wcs.skyToPixelArray(raVals, decVals, degrees=True) 

595 selector = bbox.contains(xVals, yVals) 

596 return selector 

597 

598 selector0 = check_diaObjects(bbox, exposureCut.getWcs(), diaObjects) 

599 nIn0 = np.count_nonzero(selector0) 

600 nOut0 = np.count_nonzero(~selector0) 

601 self.assertEqual(nObj0, nIn0 + nOut0) 

602 

603 # Add an ID that is not in the diaObject table. It should not get removed. 

604 diaObjectIds0 = diaObjects["diaObjectId"].copy(deep=True) 

605 diaObjectIds0[max(diaObjectIds0.index) + 1] = 999 

606 diaObjects1, objIds = task.purgeDiaObjects(exposureCut.getBBox(), exposureCut.getWcs(), diaObjects, 

607 diaObjectIds=diaObjectIds0, buffer=buffer) 

608 diaObjectIds1 = diaObjects1["diaObjectId"] 

609 # Verify that the bounding box was not changed 

610 sizeCheck = np.minimum(exposureCut.getBBox().getHeight(), exposureCut.getBBox().getWidth()) 

611 self.assertEqual(sizeCut, sizeCheck) 

612 selector1 = check_diaObjects(bbox, exposureCut.getWcs(), diaObjects1) 

613 nIn1 = np.count_nonzero(selector1) 

614 nOut1 = np.count_nonzero(~selector1) 

615 nObj1 = len(diaObjects1) 

616 self.assertEqual(nObj1, nIn0) 

617 # Verify that not all diaObjects were removed 

618 self.assertGreater(nObj1, 0) 

619 # Check that some diaObjects were removed 

620 self.assertLess(nObj1, nObj0) 

621 # Verify that no objects outside the bounding box remain 

622 self.assertEqual(nOut1, 0) 

623 # Verify that no objects inside the bounding box were removed 

624 self.assertEqual(nIn1, nIn0) 

625 # The length of the updated object IDs should equal the number of objects 

626 # plus one, since we added an extra ID. 

627 self.assertEqual(nObj1 + 1, len(objIds)) 

628 # All of the object IDs extracted from the catalog should be in the pruned object IDs 

629 self.assertTrue(set(objIds).issuperset(diaObjectIds1)) 

630 # The pruned object IDs should contain entries that are not in the catalog 

631 self.assertFalse(set(diaObjectIds1).issuperset(objIds)) 

632 # Some IDs should have been removed 

633 self.assertLess(len(objIds), len(diaObjectIds0)) 

634 

635 def test_filterDiaObjects(self): 

636 """Unassociated diaSources that are filtered should have good reliability and SNR. 

637 Glint trail sources should also be filtered out. 

638 """ 

639 

640 config = self._makeDefaultConfig(config_file=self.config_file.name, 

641 doPackageAlerts=False, 

642 filterUnAssociatedSources=True) 

643 

644 configBadFilter = self._makeDefaultConfig(config_file=self.config_file.name, 

645 doPackageAlerts=False, 

646 filterUnAssociatedSources=True, 

647 newObjectFluxField="notAFlux") 

648 configBadFlag = self._makeDefaultConfig(config_file=self.config_file.name, 

649 doPackageAlerts=False, 

650 filterUnAssociatedSources=True, 

651 newObjectBadFlags=("junkSource", "notUsed")) 

652 with self.assertRaises(pipeBase.InvalidQuantumError): 

653 DiaPipelineTask(config=configBadFilter) 

654 with self.assertRaises(pipeBase.InvalidQuantumError): 

655 DiaPipelineTask(config=configBadFlag) 

656 task = DiaPipelineTask(config=config) 

657 nUnassociatedDiaSources = 234 

658 

659 # Create diaSources 

660 diaSources = makeDiaSources(nUnassociatedDiaSources, 

661 np.zeros(nUnassociatedDiaSources), 

662 self.exposure, 

663 self.rng, 

664 flagList=task.config.newObjectBadFlags) 

665 reliability = self.rng.random(nUnassociatedDiaSources) 

666 flux = (self.rng.random(nUnassociatedDiaSources)**2)*100 

667 fluxErr = np.sqrt(flux) 

668 glint_trail = np.zeros(nUnassociatedDiaSources, dtype=bool) 

669 glint_trail[12:16] = True # add 4 glint trail sources 

670 diaSources["reliability"] = reliability 

671 diaSources["reliabilityVersion"] = '99.42' 

672 diaSources[config.newObjectFluxField] = flux 

673 diaSources[config.newObjectFluxField + "Err"] = fluxErr 

674 diaSources["glint_trail"] = glint_trail 

675 badFlagName = task.config.newObjectBadFlags[0] 

676 badFlags = np.zeros(nUnassociatedDiaSources, dtype=bool) 

677 nBadFlags = 20 

678 badFlags[0:nBadFlags] = True 

679 diaSources[badFlagName] = badFlags 

680 

681 def runAndCheckFilter(diaSources, snrThreshold=None, lowReliabilitySnrThreshold=None, 

682 reliabilityThreshold=None, lowSnrReliabilityThreshold=None, 

683 badFlags=None, 

684 ): 

685 

686 filterResults = task.filterSources( 

687 diaSources.copy(deep=True), 

688 snrThreshold=snrThreshold, 

689 lowReliabilitySnrThreshold=lowReliabilitySnrThreshold, 

690 reliabilityThreshold=reliabilityThreshold, 

691 lowSnrReliabilityThreshold=lowSnrReliabilityThreshold, 

692 badFlags=badFlags, 

693 ) 

694 self.assertEqual(len(filterResults.goodSources) + len(filterResults.badSources), 

695 nUnassociatedDiaSources) 

696 goodFlux = filterResults.goodSources[config.newObjectFluxField] 

697 goodFluxErr = filterResults.goodSources[config.newObjectFluxField + "Err"] 

698 goodSnr = np.array(goodFlux/goodFluxErr) 

699 self.assertTrue(np.all(goodSnr > snrThreshold)) 

700 goodReliability = np.array(filterResults.goodSources["reliability"]) 

701 self.assertTrue(np.all(goodReliability > reliabilityThreshold)) 

702 goodLowSnrFlag = goodSnr < lowReliabilitySnrThreshold 

703 lowSnrReliability = goodReliability[goodLowSnrFlag] 

704 self.assertTrue(np.all(lowSnrReliability > lowSnrReliabilityThreshold)) 

705 glintTrailSources = np.array(filterResults.goodSources["glint_trail"]) 

706 self.assertTrue(not any(glintTrailSources)) 

707 

708 # No sources should be removed if the thresholds are turned off 

709 runAndCheckFilter(diaSources, 

710 snrThreshold=0, lowReliabilitySnrThreshold=0, 

711 reliabilityThreshold=0, lowSnrReliabilityThreshold=0) 

712 runAndCheckFilter(diaSources, 

713 snrThreshold=0, lowReliabilitySnrThreshold=0, 

714 reliabilityThreshold=0, lowSnrReliabilityThreshold=0, 

715 badFlags=[badFlagName]) 

716 runAndCheckFilter(diaSources, 

717 snrThreshold=2, lowReliabilitySnrThreshold=8, 

718 reliabilityThreshold=0, lowSnrReliabilityThreshold=0) 

719 runAndCheckFilter(diaSources, 

720 snrThreshold=2, lowReliabilitySnrThreshold=8, 

721 reliabilityThreshold=0, lowSnrReliabilityThreshold=0.5) 

722 runAndCheckFilter(diaSources, 

723 snrThreshold=0, lowReliabilitySnrThreshold=0, 

724 reliabilityThreshold=0.1, lowSnrReliabilityThreshold=0.5) 

725 runAndCheckFilter(diaSources, 

726 snrThreshold=2, lowReliabilitySnrThreshold=8, 

727 reliabilityThreshold=0.1, lowSnrReliabilityThreshold=0.5) 

728 runAndCheckFilter(diaSources, 

729 snrThreshold=2, lowReliabilitySnrThreshold=8, 

730 reliabilityThreshold=0.1, lowSnrReliabilityThreshold=0.5, 

731 badFlags=[badFlagName]) 

732 

733 def testRunWithForcedMeasurement(self): 

734 """Test running association with forced photometry.""" 

735 

736 reliabilityThreshold = 0.5 

737 trailLengthThreshold = 1.0 

738 config = self._makeDefaultConfig(config_file=self.config_file.name, 

739 doPackageAlerts=False, 

740 forcedReliabilityThreshold=reliabilityThreshold, 

741 forcedTrailLengthThreshold=trailLengthThreshold) 

742 task = DiaPipelineTask(config=config) 

743 nDeepObjects = 20 

744 nShallowObjects = 20 

745 nGoodDiaSourcesDeep = 100 

746 nGoodDiaSourcesShallow = nShallowObjects 

747 nGoodDiaSources = nGoodDiaSourcesDeep + nGoodDiaSourcesShallow 

748 nBadDiaSources = 200 

749 

750 # Create diaObjects 

751 diaObjectsDeep = makeDiaObjects(nDeepObjects, self.exposure, self.rng, startId=1) 

752 diaObjectsShallow = makeDiaObjects(nShallowObjects, self.exposure, self.rng, startId=1 + nDeepObjects) 

753 diaObjects = task.mergeCatalogs(diaObjectsDeep, diaObjectsShallow, tableName="DiaObject") 

754 

755 diaSourcesGoodDeep = makeDiaSources(nGoodDiaSourcesDeep, diaObjectsDeep["diaObjectId"].to_numpy(), 

756 self.exposure, self.rng, startId=1, 

757 flagList=config.forcedBadFlags) 

758 diaSourcesGoodShallow = makeDiaSources(nGoodDiaSourcesShallow, 

759 diaObjectsShallow["diaObjectId"].to_numpy(), 

760 self.exposure, self.rng, startId=1 + nGoodDiaSourcesDeep, 

761 flagList=config.forcedBadFlags) 

762 

763 diaSourcesGoodDeep = convertDataFrameToSdmSchema(task.schema, diaSourcesGoodDeep, 

764 tableName="DiaSource", skipIndex=True) 

765 diaSourcesGood = task.mergeCatalogs(diaSourcesGoodDeep, diaSourcesGoodShallow, tableName="DiaSource") 

766 

767 diaSourcesBad = makeDiaSources(nBadDiaSources, diaObjects["diaObjectId"].to_numpy(), self.exposure, 

768 self.rng, randomizeObjects=True, startId=1 + nGoodDiaSources, 

769 flagList=config.forcedBadFlags) 

770 diaSourcesGood['reliability'] = (self.rng.random(nGoodDiaSources)*(1 - reliabilityThreshold) 

771 + reliabilityThreshold) 

772 diaSourcesGood['reliabilityVersion'] = '99.42' 

773 diaSourcesGood['trailLength'] = self.rng.random(nGoodDiaSources)*trailLengthThreshold 

774 diaSourcesBad = convertDataFrameToSdmSchema(task.schema, diaSourcesBad, 

775 tableName="DiaSource", skipIndex=True) 

776 

777 # Set some "bad" diaSources to have bad reliability, some good 

778 diaSourcesBad['reliability'] = self.rng.random(nBadDiaSources) 

779 diaSourcesBad['reliabilityVersion'] = '99.42' 

780 # Set some "bad" diaSources to have too long trail lengths, some acceptible 

781 diaSourcesBad['trailLength'] = self.rng.random(nBadDiaSources)*trailLengthThreshold + 0.5 

782 missingBadFlags = ((diaSourcesBad['reliability'] > reliabilityThreshold) 

783 & (diaSourcesBad['trailLength'] < trailLengthThreshold) 

784 ) 

785 for badFlag in config.forcedBadFlags: 

786 # Set a fraction of the bad diaSources to have each flag, assigned randomly 

787 diaSourcesBad[badFlag] = self.rng.random(nBadDiaSources) > 0.8 

788 missingBadFlags &= ~diaSourcesBad[badFlag] 

789 # Catch any "bad" diaSources that have not yet been flagged 

790 if np.any(missingBadFlags): 790 ↛ 792line 790 didn't jump to line 792 because the condition on line 790 was always true

791 diaSourcesBad[badFlag] |= missingBadFlags 

792 diaObjectsForcedGoodOnly = task._selectGoodDiaObjects(diaObjects, diaSourcesGood) 

793 diaObjectsForcedBadOnly = task._selectGoodDiaObjects(diaObjects, diaSourcesBad) 

794 # None of the diaObjects should be selected if only given the bad diaSources 

795 self.assertTrue(diaObjectsForcedBadOnly.empty) 

796 

797 diaSources = task.mergeCatalogs(diaSourcesGood, diaSourcesBad, tableName="DiaSource") 

798 diaObjectsForced = task._selectGoodDiaObjects(diaObjects, diaSources) 

799 # The number of diaObjects selected should be the same regardless of 

800 # whether the bad diaSources are included 

801 self.assertEqual(len(diaObjectsForced), len(diaObjectsForcedGoodOnly)) 

802 # All of the deep diaObjects should be selected, and none of the shallow 

803 self.assertEqual(len(diaObjectsForced), nDeepObjects) 

804 fSrc = task.runForcedMeasurement(diaObjectsForced, diaObjectsForced, self.exposure, self.exposure, 

805 IdGenerator()) 

806 self.assertEqual(set(fSrc['diaObjectId']), set(diaObjectsDeep['diaObjectId'])) 

807 

808 def test_selectGoodObjects(self): 

809 """Test the diaObject selection funtion used for forced photometry. 

810 """ 

811 reliabilityThreshold = 0.5 

812 trailLengthThreshold = 1.0 

813 config = self._makeDefaultConfig(config_file=self.config_file.name, 

814 doPackageAlerts=False, 

815 forcedReliabilityThreshold=reliabilityThreshold, 

816 forcedTrailLengthThreshold=trailLengthThreshold) 

817 task = DiaPipelineTask(config=config) 

818 nObjects = 20 

819 nDiaSources = 100 

820 

821 # Create diaObjects 

822 diaObjects = makeDiaObjects(nObjects, self.exposure, self.rng, startId=1) 

823 

824 diaSources = makeDiaSources(nDiaSources, diaObjects["diaObjectId"].to_numpy(), 

825 self.exposure, self.rng, startId=1, 

826 flagList=config.forcedBadFlags) 

827 # Since flagList is not specified, the columns will be missing, and added and filled with NaNs 

828 # when put through convertDataFrameToSdmSchema. 

829 diaSourcesMissingColumns = makeDiaSources(nDiaSources, diaObjects["diaObjectId"].to_numpy(), 

830 self.exposure, self.rng, startId=1 + nDiaSources) 

831 # Should raise an error if run before adding the required columns 

832 with self.assertRaises(RuntimeError): 

833 task._selectGoodDiaObjects(diaObjects, diaSources) 

834 

835 diaSources['reliability'] = (self.rng.random(nDiaSources)*(1 - reliabilityThreshold) 

836 + reliabilityThreshold) 

837 diaSources['reliabilityVersion'] = '99.42' 

838 diaSources['trailLength'] = self.rng.random(nDiaSources)*trailLengthThreshold 

839 

840 diaSourcesMissingColumns['reliability'] = (self.rng.random(nDiaSources)*(1 - reliabilityThreshold) 

841 + reliabilityThreshold) 

842 diaSourcesMissingColumns['trailLength'] = self.rng.random(nDiaSources)*trailLengthThreshold 

843 

844 diaSourcesNotMatched = makeDiaSources(nDiaSources, diaObjects["diaObjectId"].to_numpy() + 999, 

845 self.exposure, self.rng, startId=1) 

846 

847 diaSourcesNotMatched['reliability'] = (self.rng.random(nDiaSources)*(1 - reliabilityThreshold) 

848 + reliabilityThreshold) 

849 diaSourcesNotMatched['reliabilityVersion'] = '99.42' 

850 diaSourcesNotMatched['trailLength'] = self.rng.random(nDiaSources)*trailLengthThreshold 

851 

852 diaSources = convertDataFrameToSdmSchema(task.schema, diaSources, 

853 tableName="DiaSource", skipIndex=True) 

854 diaSourcesMissingColumns = convertDataFrameToSdmSchema(task.schema, diaSourcesMissingColumns, 

855 tableName="DiaSource", skipIndex=True) 

856 diaSourcesNotMatched = convertDataFrameToSdmSchema(task.schema, diaSourcesNotMatched, 

857 tableName="DiaSource", skipIndex=True) 

858 

859 # Run the method with missing flags 

860 diaObjectsSelected = task._selectGoodDiaObjects(diaObjects, diaSources) 

861 diaObjectsBadSelection = task._selectGoodDiaObjects(diaObjects, diaSourcesNotMatched) 

862 diaObjectsNaNSelection = task._selectGoodDiaObjects(diaObjects, diaSourcesMissingColumns) 

863 # The matched catalog of good diaSources should not drop any diaObjects 

864 self.assertTrue(diaObjects.equals(diaObjectsSelected)) 

865 # The mis-matched catalog of good diaSources should drop every diaObject 

866 self.assertTrue(diaObjectsBadSelection.empty) 

867 # All diaObjects should be dropped for the diaSource catalog that has all NaN values for the flags 

868 self.assertTrue(diaObjectsNaNSelection.empty) 

869 

870 def test_selectGoodObjectsWithWrongFlags(self): 

871 """Test the diaObject selection funtion used for forced photometry. 

872 """ 

873 reliabilityThreshold = 0.5 

874 trailLengthThreshold = 1.0 

875 config = self._makeDefaultConfig(config_file=self.config_file.name, 

876 doPackageAlerts=False, 

877 forcedReliabilityThreshold=reliabilityThreshold, 

878 forcedTrailLengthThreshold=trailLengthThreshold, 

879 forcedBadFlags=['foo', 'bar']) 

880 task = DiaPipelineTask(config=config) 

881 nObjects = 20 

882 nDiaSources = 100 

883 

884 # Create diaObjects 

885 diaObjects = makeDiaObjects(nObjects, self.exposure, self.rng, startId=1) 

886 

887 diaSources = makeDiaSources(nDiaSources, diaObjects["diaObjectId"].to_numpy(), 

888 self.exposure, self.rng, startId=1) 

889 

890 diaSources['reliability'] = (self.rng.random(nDiaSources)*(1 - reliabilityThreshold) 

891 + reliabilityThreshold) 

892 diaSources['reliabilityVersion'] = '99.42' 

893 diaSources['trailLength'] = self.rng.random(nDiaSources)*trailLengthThreshold 

894 

895 diaSourcesNotMatched = makeDiaSources(nDiaSources, diaObjects["diaObjectId"].to_numpy() + 999, 

896 self.exposure, self.rng, startId=1) 

897 

898 diaSourcesNotMatched['reliability'] = (self.rng.random(nDiaSources)*(1 - reliabilityThreshold) 

899 + reliabilityThreshold) 

900 diaSourcesNotMatched['reliabilityVersion'] = '99.42' 

901 diaSourcesNotMatched['trailLength'] = self.rng.random(nDiaSources)*trailLengthThreshold 

902 

903 diaSources = convertDataFrameToSdmSchema(task.schema, diaSources, 

904 tableName="DiaSource", skipIndex=True) 

905 diaSourcesNotMatched = convertDataFrameToSdmSchema(task.schema, diaSourcesNotMatched, 

906 tableName="DiaSource", skipIndex=True) 

907 

908 # Verify that the flags are in fact missing 

909 for flag in config.forcedBadFlags: 

910 self.assertNotIn(flag, diaSources.columns) 

911 # Run the method with missing flags 

912 diaObjectsSelected = task._selectGoodDiaObjects(diaObjects, diaSources) 

913 diaObjectsBadSelection = task._selectGoodDiaObjects(diaObjects, diaSourcesNotMatched) 

914 # The matched catalog of good diaSources should not drop any diaObjects 

915 self.assertTrue(diaObjects.equals(diaObjectsSelected)) 

916 # The mis-matched catalog of good diaSources should drop every diaObject 

917 self.assertTrue(diaObjectsBadSelection.empty) 

918 

919 def test_mergeEmptyCatalog(self): 

920 """Test that a catalog is unchanged if it is merged with an empty 

921 catalog. 

922 """ 

923 diaSourcesBase = self.diaSources 

924 

925 config = self._makeDefaultConfig(config_file=self.config_file.name, doPackageAlerts=False) 

926 task = DiaPipelineTask(config=config) 

927 # Include some but not all columns that should be in diaSourcesBase, and some that are mis-matched 

928 diaSourcesEmpty = pd.DataFrame(columns=["ra", "dec", "foo"]) 

929 diaSourcesTest = task.mergeCatalogs(diaSourcesBase, diaSourcesEmpty, tableName="DiaSource") 

930 self.assertTrue(diaSourcesBase.equals(diaSourcesTest)) 

931 

932 def test_mergeCatalogs(self): 

933 """Test that a merged catalog is concatenated correctly. 

934 """ 

935 config = self._makeDefaultConfig(config_file=self.config_file.name, doPackageAlerts=False) 

936 task = DiaPipelineTask(config=config) 

937 

938 diaSourcesBase = convertDataFrameToSdmSchema(task.schema, self.diaSources, "DiaSource", 

939 skipIndex=True) 

940 nBase = len(diaSourcesBase) 

941 nNew = int(nBase/2) 

942 

943 diaSourcesNew = makeDiaSources(nNew, self.diaObjects["diaObjectId"].to_numpy(), self.exposure, 

944 self.rng) 

945 diaSourcesNew = convertDataFrameToSdmSchema(task.schema, diaSourcesNew, "DiaSource", skipIndex=True) 

946 diaSourcesTest = task.mergeCatalogs(diaSourcesBase, diaSourcesNew, tableName="DiaSource") 

947 self.assertEqual(len(diaSourcesTest), nBase + nNew) 

948 diaSourcesExtract1 = diaSourcesTest.iloc[:nBase] 

949 diaSourcesExtract2 = diaSourcesTest.iloc[nBase:] 

950 

951 pd.testing.assert_frame_equal(diaSourcesBase, diaSourcesExtract1) 

952 pd.testing.assert_frame_equal(diaSourcesNew, diaSourcesExtract2) 

953 

954 def test_updateObjectTable(self): 

955 """Test that the diaObject record is updated with the number of 

956 diaSources. 

957 """ 

958 config = self._makeDefaultConfig(config_file=self.config_file.name, doPackageAlerts=False) 

959 task = DiaPipelineTask(config=config) 

960 nObjects = 20 

961 nSrcPerObject = 10 

962 nExtraSources = 5 

963 nSources = nSrcPerObject*nObjects + nExtraSources 

964 expectedSourcesPerObject = nSrcPerObject*np.ones(nObjects) 

965 expectedSourcesPerObject[:nExtraSources] += 1 

966 diaObjects = makeDiaObjects(nObjects, self.exposure, self.rng) 

967 diaSources = makeDiaSources(nSources, diaObjects["diaObjectId"].to_numpy(), self.exposure, self.rng) 

968 updatedDiaObjects = task.updateObjectTable(diaObjects, diaSources) 

969 self.assertTrue(np.all(updatedDiaObjects.nDiaSources.values == expectedSourcesPerObject)) 

970 

971 def test_diaCalculationAllBands(self): 

972 """Test that the full DiaPipelineTask.run computes per-band 

973 psfFluxMean for all bands with source data and NaN where absent. 

974 """ 

975 config = self._makeDefaultConfig( 

976 config_file=self.config_file.name, 

977 doPackageAlerts=False, 

978 doSolarSystemAssociation=False, 

979 ) 

980 task = DiaPipelineTask(config=config) 

981 task.testDataFrameIndex = lambda x: False 

982 

983 nObjects = 3 

984 diaObjects = makeDiaObjects(nObjects, self.exposure, self.rng) 

985 diaObjectIds = diaObjects["diaObjectId"].to_numpy() 

986 

987 # Synthesize preloadedDiaSources in g, r, and i bands with known 

988 # psfFlux values. These represent the historical source catalog. 

989 bands_with_data = ["g", "r", "i"] 

990 rows = [] 

991 srcId = 1 

992 for band in bands_with_data: 

993 for i, objId in enumerate(diaObjectIds): 

994 nSrc = 3 

995 for j in range(nSrc): 

996 rows.append({ 

997 "diaSourceId": srcId, 

998 "diaObjectId": objId, 

999 "band": band, 

1000 "ra": diaObjects.iloc[i]["ra"], 

1001 "dec": diaObjects.iloc[i]["dec"], 

1002 "midpointMjdTai": 58000.0 + srcId, 

1003 "psfFlux": 1000.0 + srcId * 10, 

1004 "psfFluxErr": 10.0, 

1005 }) 

1006 srcId += 1 

1007 preloadedDiaSources = pd.DataFrame(rows) 

1008 preloadedDiaSources = convertDataFrameToSdmSchema( 

1009 task.schema, preloadedDiaSources, "DiaSource", skipIndex=True 

1010 ) 

1011 preloadedDiaSources.set_index( 

1012 ["diaObjectId", "band", "diaSourceId"], inplace=True, drop=False 

1013 ) 

1014 

1015 # The new diaSourceTable for this visit (band=g) needs to associate 

1016 # with existing objects. Use the same positions as the diaObjects. 

1017 newSrcRows = [] 

1018 for i, objId in enumerate(diaObjectIds): 

1019 newSrcRows.append({ 

1020 "diaSourceId": srcId, 

1021 "diaObjectId": 0, 

1022 "ssObjectId": 0, 

1023 "band": "g", 

1024 "ra": diaObjects.iloc[i]["ra"], 

1025 "dec": diaObjects.iloc[i]["dec"], 

1026 "midpointMjdTai": 58100.0, 

1027 "psfFlux": 1500.0, 

1028 "psfFluxErr": 15.0, 

1029 }) 

1030 srcId += 1 

1031 diaSourceTable = pd.DataFrame(newSrcRows) 

1032 

1033 preloadedDiaForcedSources = pd.DataFrame( 

1034 columns=["diaObjectId", "diaForcedSourceId"] 

1035 ).set_index(["diaObjectId", "diaForcedSourceId"], drop=False) 

1036 

1037 with patch.multiple(task, apdb=DEFAULT, diaForcedSource=DEFAULT): 

1038 result = task.run( 

1039 diaSourceTable, 

1040 None, 

1041 self.diffim, 

1042 self.exposure, 

1043 self.template, 

1044 preloadedDiaObjects=diaObjects, 

1045 preloadedDiaSources=preloadedDiaSources, 

1046 preloadedDiaForcedSources=preloadedDiaForcedSources, 

1047 band="g", 

1048 idGenerator=IdGenerator(), 

1049 ) 

1050 

1051 outputDiaObjects = result.diaObjects 

1052 

1053 # Bands with data should have finite psfFluxMean. 

1054 for band in bands_with_data: 

1055 col = f"{band}_psfFluxMean" 

1056 self.assertIn(col, outputDiaObjects.columns) 

1057 vals = outputDiaObjects[col].to_numpy() 

1058 self.assertTrue( 

1059 np.all(np.isfinite(vals)), 

1060 f"{col} should be finite for all objects but got {vals}" 

1061 ) 

1062 

1063 # Bands without data should have NaN psfFluxMean. 

1064 bands_without_data = [b for b in config.validBands 

1065 if b not in bands_with_data] 

1066 for band in bands_without_data: 

1067 col = f"{band}_psfFluxMean" 

1068 if col in outputDiaObjects.columns: 1068 ↛ 1066line 1068 didn't jump to line 1066 because the condition on line 1068 was always true

1069 vals = outputDiaObjects[col].to_numpy() 

1070 self.assertTrue( 

1071 np.all(np.isnan(vals)), 

1072 f"{col} should be NaN (no data in {band}) but got {vals}" 

1073 ) 

1074 

1075 

1076class MemoryTester(lsst.utils.tests.MemoryTestCase): 

1077 pass 

1078 

1079 

1080def setup_module(module): 

1081 lsst.utils.tests.init() 

1082 

1083 

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

1085 lsst.utils.tests.init() 

1086 unittest.main()