Coverage for tests/test_packageAlerts.py: 98%

463 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-26 12:18 -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 datetime 

23from decimal import Decimal 

24import io 

25import os 

26 

27import numpy as np 

28import pandas as pd 

29import tempfile 

30import unittest 

31from unittest.mock import patch, Mock 

32from astropy import wcs 

33from astropy.nddata import CCDData 

34import fastavro 

35try: 

36 import confluent_kafka 

37 from confluent_kafka import KafkaException 

38except ImportError: 

39 confluent_kafka = None 

40 

41import lsst.alert.packet as alertPack 

42from lsst.ap.association import PackageAlertsConfig, PackageAlertsTask 

43from lsst.ap.association.packageAlerts import _toAlertValues 

44from lsst.ap.association.utils import readMpcOrbitsSchema, readSchemaFromApdb 

45from lsst.afw.cameraGeom.testUtils import DetectorWrapper 

46import lsst.afw.image as afwImage 

47from lsst.daf.base import DateTime 

48from lsst.dax.apdb import Apdb, ApdbSql 

49import lsst.geom as geom 

50import lsst.meas.base.tests 

51from lsst.sphgeom import Box 

52import lsst.utils.tests 

53from lsst.pipe.tasks.functors import LocalWcs 

54from lsst.pipe.tasks.schemaUtils import convertDataFrameToSdmSchema 

55import utils_tests 

56 

57 

58def _roundTripThroughApdb(objects, sources, forcedSources, dateTime): 

59 """Run object and source catalogs through the Apdb to get the correct 

60 table schemas. 

61 

62 Parameters 

63 ---------- 

64 objects : `pandas.DataFrame` 

65 Set of test DiaObjects to round trip. 

66 sources : `pandas.DataFrame` 

67 Set of test DiaSources to round trip. 

68 forcedSources : `pandas.DataFrame` 

69 Set of test DiaForcedSources to round trip. 

70 dateTime : `astropy.time.Time` 

71 Time for the Apdb. 

72 

73 Returns 

74 ------- 

75 objects : `pandas.DataFrame` 

76 Round tripped objects. 

77 sources : `pandas.DataFrame` 

78 Round tripped sources. 

79 """ 

80 with tempfile.NamedTemporaryFile() as tmpFile: 

81 apdbConfig = ApdbSql.init_database(db_url="sqlite:///" + tmpFile.name) 

82 apdb = Apdb.from_config(apdbConfig) 

83 

84 wholeSky = Box.full() 

85 loadedObjects = apdb.getDiaObjects(wholeSky) 

86 if loadedObjects.empty: 86 ↛ 89line 86 didn't jump to line 89 because the condition on line 86 was always true

87 diaObjects = objects 

88 else: 

89 diaObjects = pd.concat([loadedObjects, objects]) 

90 loadedDiaSources = apdb.getDiaSources(wholeSky, [], dateTime) 

91 if loadedDiaSources.empty: 91 ↛ 94line 91 didn't jump to line 94 because the condition on line 91 was always true

92 diaSources = sources 

93 else: 

94 diaSources = pd.concat([loadedDiaSources, sources]) 

95 loadedDiaForcedSources = apdb.getDiaForcedSources(wholeSky, [], dateTime) 

96 if loadedDiaForcedSources.empty: 96 ↛ 99line 96 didn't jump to line 99 because the condition on line 96 was always true

97 diaForcedSources = forcedSources 

98 else: 

99 diaForcedSources = pd.concat([loadedDiaForcedSources, forcedSources]) 

100 

101 apdb.store(dateTime, diaObjects, diaSources, diaForcedSources) 

102 

103 diaObjects = apdb.getDiaObjects(wholeSky) 

104 diaSources = apdb.getDiaSources(wholeSky, 

105 np.unique(diaObjects["diaObjectId"]), 

106 dateTime) 

107 diaForcedSources = apdb.getDiaForcedSources( 

108 wholeSky, np.unique(diaObjects["diaObjectId"]), dateTime) 

109 

110 diaObjects.set_index("diaObjectId", drop=False, inplace=True) 

111 diaSources.set_index(["diaObjectId", "band", "diaSourceId"], 

112 drop=False, 

113 inplace=True) 

114 diaForcedSources.set_index(["diaObjectId"], drop=False, inplace=True) 

115 

116 # apply SDM type standardization to catch pandas typing issues 

117 schema = readSchemaFromApdb(apdb) 

118 diaObjects = convertDataFrameToSdmSchema(schema, diaObjects, tableName="DiaObject", skipIndex=True) 

119 diaSources = convertDataFrameToSdmSchema(schema, diaSources, tableName="DiaSource", skipIndex=True) 

120 diaForcedSources = convertDataFrameToSdmSchema(schema, diaForcedSources, tableName="DiaForcedSource", 

121 skipIndex=True) 

122 

123 return (diaObjects, diaSources, diaForcedSources) 

124 

125 

126def _makeApdbSchema(): 

127 """Return the table schemas of a new APDB, as DiaPipelineTask builds 

128 them. 

129 """ 

130 with tempfile.NamedTemporaryFile() as tmpFile: 

131 apdb = Apdb.from_config(ApdbSql.init_database(db_url="sqlite:///" + tmpFile.name)) 

132 schema = readSchemaFromApdb(apdb) 

133 schema["mpc_orbits"] = readMpcOrbitsSchema(apdb) 

134 return schema 

135 

136 

137VISIT = 2 

138DETECTOR = 42 

139 

140 

141def mock_alert(dia_source_id): 

142 """Generate a minimal mock alert. 

143 """ 

144 return { 

145 "diaSourceId": dia_source_id, 

146 "diaSource": { 

147 "midpointMjdTai": 5, 

148 "diaSourceId": 1234, 

149 "visit": VISIT, 

150 "detector": DETECTOR, 

151 "band": 'g', 

152 "ra": 12.5, 

153 "dec": -16.9, 

154 # These types are 32-bit floats in the avro schema, so we have to 

155 # make them that type here, so that they round trip appropriately. 

156 "x": np.float32(15.7), 

157 "y": np.float32(89.8), 

158 "apFlux": np.float32(54.85), 

159 "apFluxErr": np.float32(70.0), 

160 "snr": np.float32(6.7), 

161 "psfFlux": np.float32(700.0), 

162 "psfFluxErr": np.float32(90.0), 

163 "psfNdata": int(25), 

164 "dipoleNdata": int(43), 

165 "trailNdata": int(5), 

166 "bboxSize": int(50), 

167 "templateInstrument": "TESTCam", 

168 "templateVersion": 0, 

169 "mixedInstruments": False, 

170 # unlike in transformDiaSourceCatalog.py we need a timezone-aware 

171 # version because mock_alert does not go through pandas 

172 "timeProcessedMjdTai": DateTime.now().get(system=DateTime.MJD, scale=DateTime.TAI) 

173 } 

174 } 

175 

176 

177def mock_ss_alert(dia_source_id, ss_object_id): 

178 """Generate a minimal mock alert. 

179 """ 

180 alert = mock_alert(dia_source_id) 

181 alert['mpc_orbits'] = { 

182 'id': 42, 

183 'designation': '2020 AH11', # a string-typed field 

184 'q': np.float64(0.99999), # a double-typed field 

185 'unpacked_primary_provisional_designation': '2020 AH11', 

186 'packed_primary_provisional_designation': 'J201AH1', 

187 

188 } 

189 alert['ssSource'] = { 

190 'diaSourceId': dia_source_id, 

191 'ssObjectId': ss_object_id, 

192 'eclLambda': np.float64(3.141592), # a double-typed field 

193 'eclBeta': np.float64(3.141592), # a double-typed field 

194 'galLon': np.float64(3.141592), # a double-typed field 

195 'galLat': np.float64(3.141592), # a double-typed field 

196 'helioRange': np.float32(3.141592), # a float-typed field 

197 } 

198 return alert 

199 

200 

201def _deserialize_alert(alert_bytes): 

202 """Deserialize an alert message from Kafka. 

203 

204 Parameters 

205 ---------- 

206 alert_bytes : `bytes` 

207 Binary-encoding serialized Avro alert, including Confluent Wire 

208 Format prefix. 

209 

210 Returns 

211 ------- 

212 alert : `dict` 

213 An alert payload. 

214 """ 

215 schema = alertPack.Schema.from_uri(str(alertPack.get_uri_to_latest_schema())) 

216 content_bytes = io.BytesIO(alert_bytes[5:]) 

217 

218 return fastavro.schemaless_reader(content_bytes, schema.definition) 

219 

220 

221class TestPackageAlerts(lsst.utils.tests.TestCase): 

222 @classmethod 

223 def setUpClass(cls): 

224 super().setUpClass() 

225 cls.apdbSchema = _makeApdbSchema() 

226 

227 def setUp(self): 

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

229 rng = np.random.default_rng(1234) 

230 

231 patcher = patch.dict(os.environ, {"AP_KAFKA_PRODUCER_PASSWORD": "fake_password", 

232 "AP_KAFKA_PRODUCER_USERNAME": "fake_username", 

233 "AP_KAFKA_SERVER": "fake_server", 

234 "AP_KAFKA_TOPIC": "fake_topic"}) 

235 self.environ = patcher.start() 

236 self.addCleanup(patcher.stop) 

237 self.cutoutSize = 35 

238 self.center = lsst.geom.Point2D(50.1, 49.8) 

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

240 lsst.geom.Extent2I(140, 160)) 

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

242 self.dataset.addSource(100000.0, self.center) 

243 exposure, catalog = self.dataset.realize( 

244 10.0, 

245 self.dataset.makeMinimalSchema(), 

246 randomSeed=1234) 

247 self.exposure = exposure 

248 detector = DetectorWrapper(id=DETECTOR, bbox=exposure.getBBox()).detector 

249 self.exposure.setDetector(detector) 

250 

251 visit = afwImage.VisitInfo( 

252 id=VISIT, 

253 exposureTime=200., 

254 date=DateTime("2014-05-13T17:00:00.000000000", 

255 DateTime.Timescale.TAI), 

256 boresightRotAngle=geom.Angle(0.785398)) 

257 self.exposure.info.id = 1234 

258 self.exposure.info.setVisitInfo(visit) 

259 

260 self.exposure.setFilter( 

261 afwImage.FilterLabel(band='g', physical="g.MP9401")) 

262 

263 diaObjects = utils_tests.makeDiaObjects(2, self.exposure, rng) 

264 diaSourceHistory = utils_tests.makeDiaSources( 

265 10, diaObjects["diaObjectId"].to_numpy(), self.exposure, rng) 

266 diaForcedSources = utils_tests.makeDiaForcedSources( 

267 10, diaObjects["diaObjectId"].to_numpy(), self.exposure, rng) 

268 self.diaObjects, diaSourceHistory, self.diaForcedSources = _roundTripThroughApdb( 

269 diaObjects, 

270 diaSourceHistory, 

271 diaForcedSources, 

272 self.exposure.visitInfo.date.toAstropy()) 

273 diaSourceHistory["programId"] = 0 

274 

275 self.diaSources = diaSourceHistory.loc[[(1, "g", 9), (2, "g", 10)], :] 

276 self.diaSources["bboxSize"] = self.cutoutSize 

277 self.diaSourceHistory = diaSourceHistory.drop(labels=[(1, "g", 9), 

278 (2, "g", 10)]) 

279 

280 self.cutoutWcs = wcs.WCS(naxis=2) 

281 self.cutoutWcs.wcs.crpix = [self.center[0], self.center[1]] 

282 self.cutoutWcs.wcs.crval = [ 

283 self.exposure.getWcs().getSkyOrigin().getRa().asDegrees(), 

284 self.exposure.getWcs().getSkyOrigin().getDec().asDegrees()] 

285 self.cutoutWcs.wcs.cd = self.exposure.getWcs().getCdMatrix() 

286 self.cutoutWcs.wcs.ctype = ["RA---TAN", "DEC--TAN"] 

287 

288 # create a mask with planes=("BAD", "SATURATED", "EDGE") 

289 bad_bit = self.exposure.mask.getMaskPlane("BAD") 

290 self.exposure.mask.array[50:55, 100:110] |= bad_bit 

291 saturated_bit = self.exposure.mask.getMaskPlane("SAT") 

292 self.exposure.mask.array[10:25, 60:68] |= saturated_bit 

293 edge_bit = self.exposure.mask.getMaskPlane("EDGE") 

294 self.exposure.mask.array[0:5, ...] |= edge_bit 

295 

296 def testCreateExtentMinimum(self): 

297 """Test the extent creation for the cutout bbox returns a cutout with 

298 the minimum cutouut size. 

299 """ 

300 packConfig = PackageAlertsConfig() 

301 # Just create a minimum less than the default cutout size. 

302 packConfig.minCutoutSize = self.cutoutSize - 5 

303 packageAlerts = PackageAlertsTask(config=packConfig) 

304 extent = packageAlerts.createDiaSourceExtent( 

305 packConfig.minCutoutSize - 5) 

306 self.assertTrue(extent == geom.Extent2I(packConfig.minCutoutSize, 

307 packConfig.minCutoutSize)) 

308 # Test that the cutout size is correctly increased. 

309 extent = packageAlerts.createDiaSourceExtent(self.cutoutSize) 

310 self.assertTrue(extent == geom.Extent2I(self.cutoutSize, 

311 self.cutoutSize)) 

312 

313 def testCreateExtentMaximum(self): 

314 """Test the extent creation for the cutout bbox returns a cutout with 

315 the maximum cutout size. 

316 """ 

317 packConfig = PackageAlertsConfig() 

318 # Just create a maximum more than the default cutout size. 

319 packConfig.maxCutoutSize = self.cutoutSize + 5 

320 packageAlerts = PackageAlertsTask(config=packConfig) 

321 extent = packageAlerts.createDiaSourceExtent( 

322 packConfig.maxCutoutSize + 5) 

323 self.assertTrue(extent == geom.Extent2I(packConfig.maxCutoutSize, 

324 packConfig.maxCutoutSize)) 

325 # Test that the cutout size is correctly reduced. 

326 extent = packageAlerts.createDiaSourceExtent(self.cutoutSize) 

327 self.assertTrue(extent == geom.Extent2I(self.cutoutSize, 

328 self.cutoutSize)) 

329 

330 def testPsfSerializedAsFloat32Bitpix(self): 

331 """Test that PSF is downcast to float32 and serialized with BITPIX=-32.""" 

332 from astropy.io import fits 

333 

334 packageAlerts = PackageAlertsTask() 

335 

336 diaSrcId = 1234 

337 ccdData = packageAlerts.createCcdDataCutout( 

338 self.exposure, 

339 self.exposure.getWcs().getSkyOrigin(), 

340 self.exposure.getWcs().getPixelOrigin(), 

341 self.exposure.getBBox().getDimensions(), 

342 self.exposure.getPhotoCalib(), 

343 diaSrcId) 

344 

345 self.assertIsNotNone(ccdData) 

346 self.assertIsNotNone(ccdData.psf) 

347 self.assertEqual(ccdData.psf.dtype, np.float32) 

348 

349 cutoutBytes = packageAlerts.streamCcdDataToBytes(ccdData) 

350 

351 with io.BytesIO(cutoutBytes) as bytesIO: 

352 with fits.open(bytesIO) as hdul: 

353 self.assertIn("PSFIMAGE", hdul) 

354 self.assertEqual(hdul["PSFIMAGE"].header["BITPIX"], -32) 

355 

356 with io.BytesIO(cutoutBytes) as bytesIO: 

357 cutoutFromBytes = CCDData.read(bytesIO, format="fits") 

358 self.assertIsNotNone(cutoutFromBytes.psf) 

359 self.assertEqual(cutoutFromBytes.psf.dtype, '>f4') 

360 

361 def testCreateCcdDataCutout(self): 

362 """Test that the data is being extracted into the CCDData cutout 

363 correctly. 

364 """ 

365 packageAlerts = PackageAlertsTask() 

366 

367 diaSrcId = 1234 

368 ccdData = packageAlerts.createCcdDataCutout( 

369 self.exposure, 

370 self.exposure.getWcs().getSkyOrigin(), 

371 self.exposure.getWcs().getPixelOrigin(), 

372 self.exposure.getBBox().getDimensions(), 

373 self.exposure.getPhotoCalib(), 

374 diaSrcId) 

375 calibExposure = self.exposure.getPhotoCalib().calibrateImage( 

376 self.exposure.getMaskedImage()) 

377 

378 self.assertFloatsAlmostEqual(ccdData.wcs.wcs.cd, 

379 self.cutoutWcs.wcs.cd) 

380 self.assertFloatsAlmostEqual(ccdData.data, 

381 calibExposure.getImage().array) 

382 self.assertFloatsAlmostEqual( 

383 ccdData.psf, 

384 self.exposure.psf.computeKernelImage(self.center).array.astype(np.float32), 

385 rtol=1e-6, atol=1e-6 

386 ) 

387 self.assertFloatsAlmostEqual(self.exposure.mask.array, ccdData.flags) 

388 

389 cutoutBytes = packageAlerts.streamCcdDataToBytes(ccdData) 

390 readCcdData = CCDData.read(io.BytesIO(cutoutBytes), format="fits", hdu_flags='MASKPLANE') 

391 self.assertFloatsAlmostEqual(self.exposure.mask.array, readCcdData.flags) 

392 self.assertFloatsAlmostEqual(readCcdData.data, ccdData.data) 

393 self.assertFloatsAlmostEqual(readCcdData.flags, ccdData.flags) 

394 

395 ccdData = packageAlerts.createCcdDataCutout( 

396 self.exposure, 

397 geom.SpherePoint(0, 0, geom.degrees), 

398 geom.Point2D(-100, -100), 

399 self.exposure.getBBox().getDimensions(), 

400 self.exposure.getPhotoCalib(), 

401 diaSrcId) 

402 self.assertTrue(ccdData is None) 

403 

404 def testMakeLocalTransformMatrix(self): 

405 """Test that the local WCS approximation is correct. 

406 """ 

407 packageAlerts = PackageAlertsTask() 

408 

409 sphPoint = self.exposure.getWcs().pixelToSky(self.center) 

410 cutout = self.exposure.getCutout(sphPoint, 

411 geom.Extent2I(self.cutoutSize, 

412 self.cutoutSize)) 

413 cd = packageAlerts.makeLocalTransformMatrix( 

414 cutout.getWcs(), self.center, sphPoint) 

415 self.assertFloatsAlmostEqual( 

416 cd, 

417 cutout.getWcs().getCdMatrix(), 

418 rtol=5e-10, 

419 atol=5e-10) 

420 

421 def testStreamCcdDataToBytes(self): 

422 """Test round tripping an CCDData cutout to bytes and back. 

423 """ 

424 packageAlerts = PackageAlertsTask() 

425 

426 sphPoint = self.exposure.getWcs().pixelToSky(self.center) 

427 cutout = self.exposure.getCutout(sphPoint, 

428 geom.Extent2I(self.cutoutSize, 

429 self.cutoutSize)) 

430 cutoutCcdData = CCDData( 

431 data=cutout.getImage().array, 

432 wcs=self.cutoutWcs, 

433 unit="adu") 

434 

435 cutoutBytes = packageAlerts.streamCcdDataToBytes(cutoutCcdData) 

436 with io.BytesIO(cutoutBytes) as bytesIO: 

437 cutoutFromBytes = CCDData.read(bytesIO, format="fits") 

438 self.assertFloatsAlmostEqual(cutoutCcdData.data, cutoutFromBytes.data) 

439 

440 def testFindMissingDiaSourceColumns(self): 

441 """Test that only the DiaSource columns that alerts require are 

442 reported missing. 

443 """ 

444 packageAlerts = PackageAlertsTask() 

445 self.assertEqual(packageAlerts.findMissingDiaSourceColumns(self.diaSources), []) 

446 # templateMjdMean accepts null, so it may be absent. 

447 incomplete = self.diaSources.drop(columns=["mixedInstruments", "templateMjdMean", "templateVersion"]) 

448 self.assertEqual(packageAlerts.findMissingDiaSourceColumns(incomplete), 

449 ["templateVersion", "mixedInstruments"]) 

450 

451 def testMakeAlertDict(self): 

452 """Test stripping data from the various data products and into a 

453 dictionary "alert". 

454 """ 

455 packageAlerts = PackageAlertsTask() 

456 dia_source_id = 1234 

457 

458 for srcIdx, diaSource in self.diaSources.iterrows(): 

459 sphPoint = geom.SpherePoint(diaSource["ra"], 

460 diaSource["dec"], 

461 geom.degrees) 

462 pixelPoint = geom.Point2D(diaSource["x"], diaSource["y"]) 

463 cutout = self.exposure.getCutout(sphPoint, 

464 geom.Extent2I(self.cutoutSize, 

465 self.cutoutSize)) 

466 ccdCutout = packageAlerts.createCcdDataCutout( 

467 cutout, 

468 sphPoint, 

469 pixelPoint, 

470 geom.Extent2I(self.cutoutSize, self.cutoutSize), 

471 cutout.getPhotoCalib(), 

472 1234, 

473 rotPa=cutout.visitInfo.boresightRotAngle.asDegrees()) 

474 cutoutBytes = packageAlerts.streamCcdDataToBytes( 

475 ccdCutout) 

476 objSources = self.diaSourceHistory.loc[srcIdx[0]] 

477 objForcedSources = self.diaForcedSources.loc[srcIdx[0]] 

478 alert = packageAlerts.makeAlertDict( 

479 dia_source_id, 

480 self.exposure.visitInfo.getObservationReason(), 

481 self.exposure.visitInfo.getObject(), 

482 diaSource, 

483 self.diaObjects.loc[srcIdx[0]], 

484 objSources, 

485 objForcedSources, 

486 ccdCutout, 

487 ccdCutout, 

488 ccdCutout) 

489 self.assertEqual(len(alert), 13) 

490 

491 self.assertEqual(alert["diaSourceId"], dia_source_id) 

492 self.assertEqual(alert["diaSource"], diaSource.to_dict()) 

493 self.assertIsNone(alert["observation_reason"]) 

494 self.assertIsNone(alert["target_name"]) 

495 self.assertEqual(alert["cutoutDifference"], 

496 cutoutBytes) 

497 self.assertEqual(alert["cutoutScience"], 

498 cutoutBytes) 

499 self.assertEqual(alert["cutoutTemplate"], 

500 cutoutBytes) 

501 science_cutout = CCDData.read(io.BytesIO(alert["cutoutScience"]), 

502 format="fits") 

503 template_cutout = CCDData.read(io.BytesIO(alert["cutoutTemplate"]), 

504 format="fits") 

505 self.assertAlmostEqual(science_cutout.header["ROTPA"], 

506 template_cutout.header["ROTPA"]) 

507 

508 def testMakeAlertDictSchedulerFields(self): 

509 """Test non-null scheduler fields pass through as expected. 

510 

511 """ 

512 packageAlerts = PackageAlertsTask() 

513 dia_source_id = 1234 

514 

515 for srcIdx, diaSource in self.diaSources.iterrows(): 

516 objSources = self.diaSourceHistory.loc[srcIdx[0]] 

517 objForcedSources = self.diaForcedSources.loc[srcIdx[0]] 

518 obs_reason = f"obs_reason_{srcIdx}", 

519 target = f"target_name_{srcIdx}", 

520 alert = packageAlerts.makeAlertDict( 

521 dia_source_id, 

522 obs_reason, 

523 target, 

524 diaSource, 

525 self.diaObjects.loc[srcIdx[0]], 

526 objSources, 

527 objForcedSources, 

528 None, 

529 None, 

530 None) 

531 self.assertEqual(len(alert), 13) 

532 

533 self.assertEqual(alert["observation_reason"], obs_reason) 

534 self.assertEqual(alert["target_name"], target) 

535 

536 def _makeSsSrc(self, **mpcOrbitUpdates): 

537 """Make a one-row solar system source catalog with MPCORB columns 

538 shaped like the ephemeris service output. 

539 """ 

540 mockAlert = mock_ss_alert(1, 1) 

541 mpcOrbit = dict(mockAlert["mpc_orbits"], id="1234", u_param=np.nan, nopp=1.0, 

542 a=Decimal("2.5"), created_at=0, updated_at=0, fitting_datetime=0) 

543 mpcOrbit.update(mpcOrbitUpdates) 

544 row = dict(mockAlert["ssSource"]) 

545 row.update({f"MPCORB_{key}": value for key, value in mpcOrbit.items()}) 

546 return pd.DataFrame({key: [value] for key, value in row.items()}) 

547 

548 def testToAlertValues(self): 

549 """Test that nulls become None except in floating-point columns, and 

550 that timestamps become UTC. 

551 """ 

552 catalog = pd.DataFrame({ 

553 "nullableInt": pd.Series([1, pd.NA], dtype="Int64"), 

554 "nullableFloat": pd.Series([2.0, pd.NA], dtype="Float64"), 

555 "float": [3.0, np.nan], 

556 "bool": pd.Series([True, pd.NA], dtype="boolean"), 

557 "string": ["a", np.nan], 

558 "time": pd.Series([0, pd.NaT], dtype="datetime64[ms]"), 

559 }) 

560 values = _toAlertValues(catalog) 

561 

562 self.assertTrue((values.dtypes == object).all()) 

563 self.assertEqual(values["nullableInt"].tolist(), [1, None]) 

564 self.assertEqual(values["bool"].tolist(), [True, None]) 

565 self.assertEqual(values["string"].tolist(), ["a", None]) 

566 self.assertEqual(values["time"].tolist(), 

567 [pd.Timestamp(0, tz="UTC"), None]) 

568 for name in ["nullableFloat", "float"]: 

569 self.assertEqual(values[name][0], catalog[name][0]) 

570 self.assertTrue(np.isnan(values[name][1])) 

571 

572 def testStandardizeMpcOrbits(self): 

573 """Test converting MPCORB columns to the SDM mpc_orbits types. 

574 """ 

575 packageAlerts = PackageAlertsTask() 

576 ssSrc = packageAlerts.standardizeMpcOrbits(self._makeSsSrc(), self.apdbSchema) 

577 

578 self.assertEqual(ssSrc["MPCORB_u_param"].dtype, "Int32") 

579 self.assertTrue(pd.isna(ssSrc["MPCORB_u_param"][0])) 

580 self.assertEqual(ssSrc["MPCORB_nopp"].dtype, "Int32") 

581 self.assertEqual(ssSrc["MPCORB_nopp"][0], 1) 

582 self.assertEqual(ssSrc["MPCORB_a"].dtype, np.float64) 

583 self.assertEqual(ssSrc["MPCORB_a"][0], 2.5) 

584 self.assertEqual(ssSrc["MPCORB_id"][0], 0) 

585 # Columns missing from the input are added as null. 

586 self.assertTrue(np.isnan(ssSrc["MPCORB_earth_moid"][0])) 

587 # Other columns are kept. 

588 self.assertEqual(ssSrc["ssObjectId"][0], 1) 

589 

590 noOrbits = pd.DataFrame({"diaSourceId": [1]}) 

591 self.assertIs(packageAlerts.standardizeMpcOrbits(noOrbits, None), noOrbits) 

592 

593 def testStandardizeMpcOrbitsInvalid(self): 

594 """Test that values that do not fit the schema type raise. 

595 """ 

596 packageAlerts = PackageAlertsTask() 

597 for name, value in [("u_param", np.int64(-2**63)), ("nopp", 1.5)]: 

598 with self.subTest(name=name): 

599 with self.assertRaisesRegex(ValueError, name): 

600 packageAlerts.standardizeMpcOrbits(self._makeSsSrc(**{name: value}), self.apdbSchema) 

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

602 packageAlerts.standardizeMpcOrbits(self._makeSsSrc(), None) 

603 

604 def testSerializeStandardizedMpcOrbits(self): 

605 """Test that an alert built from standardized MPCORB columns 

606 serializes, with nulls as null. 

607 """ 

608 packageAlerts = PackageAlertsTask() 

609 ssSrc = packageAlerts.standardizeMpcOrbits(self._makeSsSrc(), self.apdbSchema) 

610 ssSrc = _toAlertValues(ssSrc.set_index("diaSourceId")) 

611 ssSource = ssSrc.loc[[1]].to_dict("records")[0] 

612 diaSource = pd.Series(mock_alert(1)["diaSource"], dtype=object) 

613 alert = packageAlerts.makeAlertDict(1, "", "", diaSource, None, None, None, 

614 None, None, None, ssSource=ssSource) 

615 

616 mpcOrbit = _deserialize_alert(packageAlerts._serializeAlert(alert))["mpc_orbits"] 

617 self.assertIsNone(mpcOrbit["u_param"]) 

618 self.assertTrue(np.isnan(mpcOrbit["earth_moid"])) 

619 self.assertEqual(mpcOrbit["nopp"], 1) 

620 self.assertEqual(mpcOrbit["a"], 2.5) 

621 self.assertEqual(mpcOrbit["created_at"], datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)) 

622 

623 def testCutoutRotpa(self): 

624 """Test that the ROTPA header keyword matches the boresightRotAngle from visitInfo. 

625 """ 

626 packageAlerts = PackageAlertsTask() 

627 

628 # Create a cutout using existing test exposure 

629 sphPoint = self.exposure.getWcs().pixelToSky(self.center) 

630 cutout = self.exposure.getCutout(sphPoint, 

631 geom.Extent2I(self.cutoutSize, 

632 self.cutoutSize)) 

633 

634 # Create CCDData cutout 

635 ccdCutout = packageAlerts.createCcdDataCutout( 

636 cutout, 

637 sphPoint, 

638 self.center, 

639 geom.Extent2I(self.cutoutSize, self.cutoutSize), 

640 cutout.getPhotoCalib(), 

641 1234, 

642 rotPa=cutout.visitInfo.boresightRotAngle.asDegrees()) 

643 

644 wcs = self.exposure.wcs 

645 cd_matrix = wcs.getCdMatrix() # This gets the CD matrix elements 

646 angle_rad = LocalWcs.computePositionAngle([0], 

647 [cd_matrix[0, 0]], # CD1_1 

648 [cd_matrix[0, 1]], # CD1_2 

649 [cd_matrix[1, 0]], # CD2_1 

650 [cd_matrix[1, 1]] # CD2_2 

651 ) 

652 wcs_pa = geom.Angle(angle_rad.iloc[0], geom.radians).asDegrees() 

653 

654 cutoutBytes = packageAlerts.streamCcdDataToBytes(ccdCutout) 

655 with io.BytesIO(cutoutBytes) as bytesIO: 

656 cutoutFromBytes = CCDData.read(bytesIO, format="fits") 

657 

658 self.assertIn('ROTPA', cutoutFromBytes.header) 

659 self.assertAlmostEqual( 

660 cutoutFromBytes.header['ROTPA'], 

661 self.exposure.visitInfo.boresightRotAngle.asDegrees()) 

662 self.assertAlmostEqual( 

663 cutoutFromBytes.header['ROTPA'], 

664 wcs_pa, places=4) 

665 

666 @unittest.skipIf(confluent_kafka is None, 'Kafka is not enabled') 

667 def test_produceAlerts_empty_password(self): 

668 """ Test that produceAlerts raises if the password is empty or missing. 

669 """ 

670 self.environ['AP_KAFKA_PRODUCER_PASSWORD'] = "" 

671 with self.assertRaisesRegex(ValueError, "Kafka password"): 

672 packConfig = PackageAlertsConfig(doProduceAlerts=True) 

673 PackageAlertsTask(config=packConfig) 

674 

675 del self.environ['AP_KAFKA_PRODUCER_PASSWORD'] 

676 with self.assertRaisesRegex(ValueError, "Kafka password"): 

677 packConfig = PackageAlertsConfig(doProduceAlerts=True) 

678 PackageAlertsTask(config=packConfig) 

679 

680 @unittest.skipIf(confluent_kafka is None, 'Kafka is not enabled') 

681 def test_produceAlerts_empty_username(self): 

682 """ Test that produceAlerts raises if the username is empty or missing. 

683 """ 

684 self.environ['AP_KAFKA_PRODUCER_USERNAME'] = "" 

685 with self.assertRaisesRegex(ValueError, "Kafka username"): 

686 packConfig = PackageAlertsConfig(doProduceAlerts=True) 

687 PackageAlertsTask(config=packConfig) 

688 

689 del self.environ['AP_KAFKA_PRODUCER_USERNAME'] 

690 with self.assertRaisesRegex(ValueError, "Kafka username"): 

691 packConfig = PackageAlertsConfig(doProduceAlerts=True) 

692 PackageAlertsTask(config=packConfig) 

693 

694 @unittest.skipIf(confluent_kafka is None, 'Kafka is not enabled') 

695 def test_produceAlerts_empty_server(self): 

696 """ Test that produceAlerts raises if the server is empty or missing. 

697 """ 

698 self.environ['AP_KAFKA_SERVER'] = "" 

699 with self.assertRaisesRegex(ValueError, "Kafka server"): 

700 packConfig = PackageAlertsConfig(doProduceAlerts=True) 

701 PackageAlertsTask(config=packConfig) 

702 

703 del self.environ['AP_KAFKA_SERVER'] 

704 with self.assertRaisesRegex(ValueError, "Kafka server"): 

705 packConfig = PackageAlertsConfig(doProduceAlerts=True) 

706 PackageAlertsTask(config=packConfig) 

707 

708 @unittest.skipIf(confluent_kafka is None, 'Kafka is not enabled') 

709 def test_produceAlerts_empty_topic(self): 

710 """ Test that produceAlerts raises if the topic is empty or missing. 

711 """ 

712 self.environ['AP_KAFKA_TOPIC'] = "" 

713 with self.assertRaisesRegex(ValueError, "Kafka topic"): 

714 packConfig = PackageAlertsConfig(doProduceAlerts=True) 

715 PackageAlertsTask(config=packConfig) 

716 

717 del self.environ['AP_KAFKA_TOPIC'] 

718 with self.assertRaisesRegex(ValueError, "Kafka topic"): 

719 packConfig = PackageAlertsConfig(doProduceAlerts=True) 

720 PackageAlertsTask(config=packConfig) 

721 

722 @patch('confluent_kafka.Producer') 

723 @patch.object(PackageAlertsTask, '_server_check') 

724 @unittest.skipIf(confluent_kafka is None, 'Kafka is not enabled') 

725 def test_produceAlerts_success(self, mock_server_check, mock_producer): 

726 """ Test that produceAlerts calls the producer on all provided alerts 

727 when the alerts are all under the batch size limit. 

728 """ 

729 packConfig = PackageAlertsConfig(doProduceAlerts=True) 

730 packageAlerts = PackageAlertsTask(config=packConfig) 

731 alerts = [mock_alert(1), mock_alert(2), mock_ss_alert(3, 3)] 

732 

733 # Create a variable and assign it an instance of the patched kafka producer 

734 producer_instance = mock_producer.return_value 

735 producer_instance.produce = Mock() 

736 producer_instance.flush = Mock() 

737 unix_midpoint = self.exposure.visitInfo.date.toAstropy().tai.unix 

738 exposure_time = self.exposure.visitInfo.exposureTime 

739 packageAlerts.produceAlerts(alerts, VISIT, DETECTOR, unix_midpoint, exposure_time) 

740 

741 self.assertEqual(mock_server_check.call_count, 1) 

742 self.assertEqual(producer_instance.produce.call_count, len(alerts)) 

743 self.assertEqual(producer_instance.flush.call_count, len(alerts)+1) 

744 

745 @patch('confluent_kafka.Producer') 

746 @patch.object(PackageAlertsTask, '_server_check') 

747 @unittest.skipIf(confluent_kafka is None, 'Kafka is not enabled') 

748 def test_produceAlerts_one_failure(self, mock_server_check, mock_producer): 

749 """ Test that produceAlerts correctly fails on one alert 

750 and is writing the failure to disk. 

751 """ 

752 counter = 0 

753 

754 def mock_produce(*args, **kwargs): 

755 nonlocal counter 

756 counter += 1 

757 if counter == 2: 

758 raise KafkaException 

759 else: 

760 return 

761 

762 packConfig = PackageAlertsConfig(doProduceAlerts=True, doWriteFailedAlerts=True) 

763 packageAlerts = PackageAlertsTask(config=packConfig) 

764 

765 patcher = patch("builtins.open") 

766 patch_open = patcher.start() 

767 alerts = [mock_alert(1), mock_alert(2), mock_alert(3), mock_ss_alert(4, 4)] 

768 unix_midpoint = self.exposure.visitInfo.date.toAstropy().tai.unix 

769 exposure_time = self.exposure.visitInfo.exposureTime 

770 

771 producer_instance = mock_producer.return_value 

772 producer_instance.produce = Mock(side_effect=mock_produce) 

773 producer_instance.flush = Mock() 

774 packageAlerts.produceAlerts(alerts, VISIT, DETECTOR, unix_midpoint, exposure_time) 

775 

776 self.assertEqual(mock_server_check.call_count, 1) 

777 self.assertEqual(producer_instance.produce.call_count, len(alerts)) 

778 self.assertEqual(patch_open.call_count, 1) 

779 self.assertIn(f"{VISIT}_{DETECTOR}_2.avro", patch_open.call_args.args[0]) 

780 # Because one produce raises, we call flush one fewer times than in the success 

781 # test above. 

782 self.assertEqual(producer_instance.flush.call_count, len(alerts)) 

783 patcher.stop() 

784 

785 @patch.object(PackageAlertsTask, '_server_check') 

786 def testRun_without_produce(self, mock_server_check): 

787 """Test the run method of package alerts with produce set to False and 

788 doWriteAlerts set to true. 

789 """ 

790 packConfig = PackageAlertsConfig(doWriteAlerts=True) 

791 with tempfile.TemporaryDirectory(prefix='alerts') as tempdir: 

792 packConfig.alertWriteLocation = tempdir 

793 packageAlerts = PackageAlertsTask(config=packConfig) 

794 

795 packageAlerts.run(self.diaSources, 

796 self.diaObjects, 

797 self.diaSourceHistory, 

798 self.diaForcedSources, 

799 self.exposure, 

800 self.exposure, 

801 self.exposure) 

802 

803 self.assertEqual(mock_server_check.call_count, 0) 

804 

805 with open(os.path.join(tempdir, f"{VISIT}_{DETECTOR}.avro"), 'rb') as f: 

806 writer_schema, data_stream = \ 

807 packageAlerts.alertSchema.retrieve_alerts(f) 

808 data = list(data_stream) 

809 

810 self.assertEqual(len(data), len(self.diaSources)) 

811 for idx, alert in enumerate(data): 

812 for key, value in alert["diaSource"].items(): 

813 if isinstance(value, float): 

814 if np.isnan(self.diaSources.iloc[idx][key]): 

815 self.assertTrue(np.isnan(value)) 

816 else: 

817 self.assertAlmostEqual( 

818 1 - value / self.diaSources.iloc[idx][key], 

819 0.) 

820 elif value is None: 

821 self.assertTrue(pd.isna(self.diaSources.iloc[idx][key])) 

822 else: 

823 self.assertEqual(value, self.diaSources.iloc[idx][key]) 

824 sphPoint = geom.SpherePoint(alert["diaSource"]["ra"], 

825 alert["diaSource"]["dec"], 

826 geom.degrees) 

827 pixelPoint = geom.Point2D(alert["diaSource"]["x"], alert["diaSource"]["y"]) 

828 cutout = self.exposure.getCutout(sphPoint, 

829 geom.Extent2I(self.cutoutSize, 

830 self.cutoutSize)) 

831 ccdCutout = packageAlerts.createCcdDataCutout( 

832 cutout, 

833 sphPoint, 

834 pixelPoint, 

835 geom.Extent2I(self.cutoutSize, self.cutoutSize), 

836 cutout.getPhotoCalib(), 

837 1234, 

838 rotPa=cutout.visitInfo.boresightRotAngle.asDegrees()) 

839 

840 self.assertEqual(alert["cutoutDifference"], 

841 packageAlerts.streamCcdDataToBytes(ccdCutout)) 

842 

843 self.assertEqual(alert["cutoutDifference"], 

844 packageAlerts.streamCcdDataToBytes(ccdCutout)) 

845 

846 @patch.object(PackageAlertsTask, '_server_check') 

847 def testRun_without_produce_use_averagePsf(self, mock_server_check): 

848 """Test the run method of package alerts with produce set to False and 

849 doWriteAlerts set to true. 

850 """ 

851 packConfig = PackageAlertsConfig(doWriteAlerts=True) 

852 with tempfile.TemporaryDirectory(prefix='alerts') as tempdir: 

853 packConfig.alertWriteLocation = tempdir 

854 packConfig.useAveragePsf = True 

855 packageAlerts = PackageAlertsTask(config=packConfig) 

856 

857 packageAlerts.run(self.diaSources, 

858 self.diaObjects, 

859 self.diaSourceHistory, 

860 self.diaForcedSources, 

861 self.exposure, 

862 self.exposure, 

863 self.exposure) 

864 

865 self.assertEqual(mock_server_check.call_count, 0) 

866 

867 with open(os.path.join(tempdir, f"{VISIT}_{DETECTOR}.avro"), 'rb') as f: 

868 writer_schema, data_stream = \ 

869 packageAlerts.alertSchema.retrieve_alerts(f) 

870 data = list(data_stream) 

871 

872 self.assertEqual(len(data), len(self.diaSources)) 

873 for idx, alert in enumerate(data): 

874 for key, value in alert["diaSource"].items(): 

875 if isinstance(value, float): 

876 if np.isnan(self.diaSources.iloc[idx][key]): 

877 self.assertTrue(np.isnan(value)) 

878 else: 

879 self.assertAlmostEqual( 

880 1 - value / self.diaSources.iloc[idx][key], 

881 0.) 

882 elif value is None: 

883 self.assertTrue(pd.isna(self.diaSources.iloc[idx][key])) 

884 else: 

885 self.assertEqual(value, self.diaSources.iloc[idx][key]) 

886 sphPoint = geom.SpherePoint(alert["diaSource"]["ra"], 

887 alert["diaSource"]["dec"], 

888 geom.degrees) 

889 pixelPoint = geom.Point2D(alert["diaSource"]["x"], alert["diaSource"]["y"]) 

890 cutout = self.exposure.getCutout(sphPoint, 

891 geom.Extent2I(self.cutoutSize, 

892 self.cutoutSize)) 

893 ccdCutout = packageAlerts.createCcdDataCutout( 

894 cutout, 

895 sphPoint, 

896 pixelPoint, 

897 geom.Extent2I(self.cutoutSize, self.cutoutSize), 

898 cutout.getPhotoCalib(), 

899 1234, 

900 rotPa=cutout.visitInfo.boresightRotAngle.asDegrees()) 

901 self.assertEqual(alert["cutoutDifference"], 

902 packageAlerts.streamCcdDataToBytes(ccdCutout)) 

903 

904 @patch.object(PackageAlertsTask, 'produceAlerts') 

905 @patch('confluent_kafka.Producer') 

906 @patch.object(PackageAlertsTask, '_server_check') 

907 @unittest.skipIf(confluent_kafka is None, 'Kafka is not enabled') 

908 def testRun_with_produce(self, mock_produceAlerts, mock_server_check, mock_producer): 

909 """Test that packageAlerts calls produceAlerts when doProduceAlerts 

910 is set to True. 

911 """ 

912 packConfig = PackageAlertsConfig(doProduceAlerts=True) 

913 packageAlerts = PackageAlertsTask(config=packConfig) 

914 

915 packageAlerts.run(self.diaSources, 

916 self.diaObjects, 

917 self.diaSourceHistory, 

918 self.diaForcedSources, 

919 self.exposure, 

920 self.exposure, 

921 self.exposure) 

922 self.assertEqual(mock_server_check.call_count, 1) 

923 self.assertEqual(mock_produceAlerts.call_count, 1) 

924 

925 def test_serialize_alert_round_trip(self): 

926 """Test that values in the alert packet exactly round trip. 

927 """ 

928 packClass = PackageAlertsConfig() 

929 packageAlerts = PackageAlertsTask(config=packClass) 

930 

931 alert = mock_ss_alert(1, 1) 

932 serialized = PackageAlertsTask._serializeAlert(packageAlerts, alert) 

933 deserialized = _deserialize_alert(serialized) 

934 for table in ['diaSource', 'ssSource', 'mpc_orbits']: 

935 for field in alert[table]: 

936 self.assertEqual(alert[table][field], deserialized[table][field]) 

937 

938 self.assertEqual(1, deserialized["diaSourceId"]) 

939 

940 @unittest.skipIf(confluent_kafka is None, 'Kafka is not enabled') 

941 def test_server_check(self): 

942 

943 with self.assertRaisesRegex(KafkaException, "_TRANSPORT"): 

944 packConfig = PackageAlertsConfig(doProduceAlerts=True) 

945 PackageAlertsTask(config=packConfig) 

946 

947 

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

949 pass 

950 

951 

952def setup_module(module): 

953 lsst.utils.tests.init() 

954 

955 

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

957 lsst.utils.tests.init() 

958 unittest.main()