Coverage for python/lsst/ap/association/packageAlerts.py: 85%

329 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-26 07:23 +0000

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 

22__all__ = ("PackageAlertsConfig", "PackageAlertsTask") 

23 

24import io 

25import os 

26import sys 

27import time 

28 

29from astropy import wcs 

30import astropy.units as u 

31from astropy.nddata import CCDData, VarianceUncertainty 

32import numpy as np 

33import pandas as pd 

34import struct 

35import fastavro 

36from confluent_kafka.cimpl import KafkaError 

37 

38# confluent_kafka is not in the standard Rubin environment as it is a third 

39# party package and is only needed when producing alerts. 

40try: 

41 import confluent_kafka 

42 from confluent_kafka import KafkaException 

43 from confluent_kafka.admin import AdminClient 

44except ImportError: 

45 confluent_kafka = None 

46 

47import lsst.alert.packet as alertPack 

48from lsst.afw.detection import InvalidPsfError 

49import lsst.afw.geom as afwGeom 

50import lsst.geom as geom 

51import lsst.pex.config as pexConfig 

52from lsst.pex.exceptions import InvalidParameterError 

53import lsst.pipe.base as pipeBase 

54from lsst.pipe.tasks.associationUtils import ss_object_id_to_obj_id 

55from lsst.pipe.tasks.schemaUtils import checkDataFrameAgainstSdmSchema, convertDataFrameToSdmSchema 

56import lsst.utils.logging 

57from lsst.utils.timer import timeMethod 

58 

59 

60def _toAlertValues(catalog): 

61 """Convert a catalog to object dtype holding values that Avro accepts. 

62 

63 Parameters 

64 ---------- 

65 catalog : `pandas.DataFrame` 

66 Catalog to convert. 

67 

68 Returns 

69 ------- 

70 values : `pandas.DataFrame` 

71 Copy of ``catalog`` with object dtype. Nulls in columns that are not 

72 floating point are `None`, and timestamps are timezone-aware UTC. 

73 

74 Notes 

75 ----- 

76 Object dtype stops pandas from coercing a row to a common dtype (e.g. 

77 nullable ``Float64``) when single rows are selected. Avro rejects 

78 `pandas.NA` and `pandas.NaT` in nullable fields but accepts NaN in 

79 ``float`` and ``double`` fields, so NaN in floating-point columns is 

80 kept. Naive timestamps are UTC in the SDM schemas, while Avro treats 

81 naive datetimes as local time. 

82 """ 

83 catalog = catalog.copy() 

84 for name, column in catalog.items(): 

85 if column.dtype.kind == "M" and column.dt.tz is None: 

86 catalog[name] = column.dt.tz_localize("UTC") 

87 elif column.dtype.kind == "f" and isinstance(column.dtype, pd.api.extensions.ExtensionDtype): 

88 catalog[name] = column.to_numpy(dtype=column.dtype.numpy_dtype, na_value=np.nan) 

89 values = catalog.astype("object") 

90 for name, column in catalog.items(): 

91 if column.dtype.kind != "f": 

92 nulls = column.isna().to_numpy() 

93 if nulls.any(): 

94 values.loc[nulls, name] = None 

95 return values 

96 

97 

98class PackageAlertsConfig(pexConfig.Config): 

99 """Config class for AssociationTask. 

100 """ 

101 schemaFile = pexConfig.Field( 

102 dtype=str, 

103 doc="Schema definition file URI for the avro alerts.", 

104 default=str(alertPack.get_uri_to_latest_schema()) 

105 ) 

106 minCutoutSize = pexConfig.RangeField( 

107 dtype=int, 

108 min=0, 

109 max=1000, 

110 default=30, 

111 doc="Dimension of the square image cutouts to package in the alert." 

112 ) 

113 maxCutoutSize = pexConfig.RangeField( 

114 dtype=int, 

115 min=0, 

116 max=1000, 

117 default=102, 

118 doc="Dimension of the square image cutouts to package in the alert. The" 

119 "default size comes from the max trail length in arcseconds " 

120 "(10 deg/day) for a 30 second observation divided by the" 

121 "arcseconds per pixel (0.2), which is 62.5 pixels. The effective" 

122 "size of the psf (40 pixels) is then added for a total of 102 pixels. " 

123 ) 

124 alertWriteLocation = pexConfig.Field( 

125 dtype=str, 

126 doc="Location to write alerts to.", 

127 default=os.path.join(os.getcwd(), "alerts"), 

128 ) 

129 

130 doProduceAlerts = pexConfig.Field( 

131 dtype=bool, 

132 doc="Turn on alert production to kafka if true and if confluent_kafka is in the environment.", 

133 default=False, 

134 ) 

135 

136 doWriteAlerts = pexConfig.Field( 

137 dtype=bool, 

138 doc="Write alerts to disk if true.", 

139 default=False, 

140 ) 

141 

142 doWriteFailedAlerts = pexConfig.Field( 

143 dtype=bool, 

144 doc="If an alert cannot be sent when doProduceAlerts is set, " 

145 "write it to disk for debugging purposes.", 

146 default=False, 

147 ) 

148 

149 maxTimeout = pexConfig.Field( 

150 dtype=float, 

151 doc="Sets the maximum time in seconds to wait for the alert stream " 

152 "broker to respond to a query before timing out.", 

153 default=15.0, 

154 ) 

155 

156 deliveryTimeout = pexConfig.Field( 

157 dtype=float, 

158 doc="Sets the time to wait for the producer to wait to deliver an " 

159 "alert in milliseconds.", 

160 default=1200.0, 

161 ) 

162 

163 useAveragePsf = pexConfig.Field( 

164 dtype=bool, 

165 doc="Use the average PSF for the image, instead of the PSF for each cutout. " 

166 "This option is much less accurate, but much faster.", 

167 default=False, 

168 ) 

169 

170 

171class PackageAlertsTask(pipeBase.Task): 

172 """Tasks for packaging Dia and Pipelines data into Avro alert packages. 

173 """ 

174 ConfigClass = PackageAlertsConfig 

175 _DefaultName = "packageAlerts" 

176 

177 _scale = (1.0 * geom.arcseconds).asDegrees() 

178 

179 def __init__(self, **kwargs): 

180 super().__init__(**kwargs) 

181 self.alertSchema = alertPack.Schema.from_uri(self.config.schemaFile) 

182 os.makedirs(self.config.alertWriteLocation, exist_ok=True) 

183 

184 if self.config.doProduceAlerts: 

185 if confluent_kafka is not None: 185 ↛ 243line 185 didn't jump to line 243 because the condition on line 185 was always true

186 self.password = os.getenv("AP_KAFKA_PRODUCER_PASSWORD") 

187 if not self.password: 

188 raise ValueError("Kafka password environment variable was not set.") 

189 self.username = os.getenv("AP_KAFKA_PRODUCER_USERNAME") 

190 if not self.username: 

191 raise ValueError("Kafka username environment variable was not set.") 

192 self.server = os.getenv("AP_KAFKA_SERVER") 

193 if not self.server: 

194 raise ValueError("Kafka server environment variable was not set.") 

195 self.kafkaTopic = os.getenv("AP_KAFKA_TOPIC") 

196 if not self.kafkaTopic: 

197 raise ValueError("Kafka topic environment variable was not set.") 

198 

199 # confluent_kafka configures all of its classes with dictionaries. This one 

200 # sets up the bare minimum that is needed. 

201 self.kafkaConfig = { 

202 # This is the URL to use to connect to the Kafka cluster. 

203 "bootstrap.servers": self.server, 

204 # These next two properties tell the Kafka client about the specific 

205 # authentication and authorization protocols that should be used when 

206 # connecting. 

207 "security.protocol": "SASL_PLAINTEXT", 

208 "sasl.mechanisms": "SCRAM-SHA-512", 

209 # The sasl.username and sasl.password are passed through over 

210 # SCRAM-SHA-512 auth to connect to the cluster. The username is not 

211 # sensitive, but the password is (of course) a secret value which 

212 # should never be committed to source code. 

213 "sasl.username": self.username, 

214 "sasl.password": self.password, 

215 # Batch size limits the largest size of a kafka alert that can be sent. 

216 # We set the batch size to 2 Mb. 

217 "batch.size": 2097152, 

218 "linger.ms": 5, 

219 "delivery.timeout.ms": self.config.deliveryTimeout, 

220 # Compression options are snappy, lz4, zstd, and gzip. 

221 "compression.type": 'snappy' 

222 } 

223 self.kafkaAdminConfig = { 

224 # This is the URL to use to connect to the Kafka cluster. 

225 "bootstrap.servers": self.server, 

226 # These next two properties tell the Kafka client about the specific 

227 # authentication and authorization protocols that should be used when 

228 # connecting. 

229 "security.protocol": "SASL_PLAINTEXT", 

230 "sasl.mechanisms": "SCRAM-SHA-512", 

231 # The sasl.username and sasl.password are passed through over 

232 # SCRAM-SHA-512 auth to connect to the cluster. The username is not 

233 # sensitive, but the password is (of course) a secret value which 

234 # should never be committed to source code. 

235 "sasl.username": self.username, 

236 "sasl.password": self.password, 

237 } 

238 

239 self._server_check() 

240 self.producer = confluent_kafka.Producer(**self.kafkaConfig) 

241 

242 else: 

243 raise RuntimeError("Produce alerts is set but confluent_kafka is not present in " 

244 "the environment. Alerts will not be sent to the alert stream.") 

245 

246 @timeMethod 

247 def run(self, 

248 diaSourceCat, 

249 diaObjectCat, 

250 diaSrcHistory, 

251 diaForcedSources, 

252 diffIm, 

253 calexp, 

254 template, 

255 ssSrc=None, 

256 doRunForcedMeasurement=True, 

257 forcedSourceHistoryThreshold=0, 

258 schema=None, 

259 ): 

260 """Package DiaSources/Object and exposure data into Avro alerts. 

261 

262 Alerts can be sent to the alert stream if ``doProduceAlerts`` is set 

263 and written to disk if ``doWriteAlerts`` is set. Both can be set at the 

264 same time, and are independent of one another. 

265 

266 Writes Avro alerts to a location determined by the 

267 ``alertWriteLocation`` configurable. 

268 

269 Parameters 

270 ---------- 

271 diaSourceCat : `pandas.DataFrame` 

272 New DiaSources to package. DataFrame should be indexed on 

273 ``["diaObjectId", "band", "diaSourceId"]`` 

274 diaObjectCat : `pandas.DataFrame` 

275 New and updated DiaObjects matched to the new DiaSources. DataFrame 

276 is indexed on ``["diaObjectId"]`` 

277 diaSrcHistory : `pandas.DataFrame` 

278 12 month history of DiaSources matched to the DiaObjects. Excludes 

279 the newest DiaSource and is indexed on 

280 ``["diaObjectId", "band", "diaSourceId"]`` 

281 diaForcedSources : `pandas.DataFrame` 

282 12 month history of DiaForcedSources matched to the DiaObjects. 

283 ``["diaObjectId"]`` 

284 diffIm : `lsst.afw.image.ExposureF` 

285 Difference image the sources in ``diaSourceCat`` were detected in. 

286 calexp : `lsst.afw.image.ExposureF` 

287 Calexp used to create the ``diffIm``. 

288 template : `lsst.afw.image.ExposureF` or `None` 

289 Template image used to create the ``diffIm``. 

290 ssSrc : `pandas.DataFrame`, optional 

291 Solar system specific information for diaSources associated to ssObjects. 

292 doRunForcedMeasurement : `bool`, optional 

293 Flag to indicate whether forced measurement was run. 

294 This should only be turned off for debugging purposes. 

295 Added to allow disabling forced sources for performance 

296 reasons during the ops rehearsal. 

297 forcedSourceHistoryThreshold : `int`, optional 

298 Minimum number of detections of a diaObject required 

299 to run forced photometry. Set to 1 to include all diaObjects. 

300 schema : `dict` [`str`, `lsst.dax.apdb.schema_model.Table` \ 

301 or `felis.datamodel.Table`], optional 

302 Table schemas keyed by table name, as used by 

303 `lsst.ap.association.DiaPipelineTask`. Required if ``ssSrc`` has 

304 MPCORB columns, which are converted to the ``mpc_orbits`` table 

305 types. 

306 

307 Raises 

308 ------ 

309 ValueError 

310 Raised if ``ssSrc`` has MPCORB columns and ``schema`` has no 

311 ``mpc_orbits`` table, or if a column cannot be converted to its 

312 schema type. 

313 """ 

314 

315 alerts = [] 

316 self._patchDiaSources(diaSourceCat) 

317 self._patchDiaSources(diaSrcHistory) 

318 detector = diffIm.detector.getId() 

319 visit = diffIm.visitInfo.id 

320 observation_reason = diffIm.visitInfo.getObservationReason() 

321 target_name = diffIm.visitInfo.getObject() 

322 midpoint_unix = diffIm.visitInfo.date.toAstropy().tai.unix 

323 exposure_time = diffIm.visitInfo.exposureTime 

324 diffImPhotoCalib = diffIm.getPhotoCalib() 

325 calexpPhotoCalib = calexp.getPhotoCalib() 

326 templatePhotoCalib = template.getPhotoCalib() 

327 diffImPsf = self._computePsf(diffIm, diffIm.psf.getAveragePosition()) 

328 sciencePsf = self._computePsf(calexp, calexp.psf.getAveragePosition()) 

329 templatePsf = self._computePsf(template, template.psf.getAveragePosition()) 

330 

331 diaSourceCat = _toAlertValues(diaSourceCat) 

332 diaObjectCat = _toAlertValues(diaObjectCat) 

333 diaSrcHistory = _toAlertValues(diaSrcHistory) 

334 diaForcedSources = _toAlertValues(diaForcedSources) 

335 

336 if ssSrc is not None: 336 ↛ 337line 336 didn't jump to line 337 because the condition on line 336 was never true

337 ssSrc = self.standardizeMpcOrbits(ssSrc, schema) 

338 ssSrc = ssSrc.set_index('diaSourceId') 

339 ssSrc = _toAlertValues(ssSrc) 

340 

341 n_sources = len(diaSourceCat) 

342 self.log.info("Packaging alerts for %d DiaSources.", n_sources) 

343 # Log every 10 seconds as proof of liveness. 

344 loop_logger = lsst.utils.logging.PeriodicLogger(self.log, interval=10.0) 

345 

346 for srcIndex, diaSource in diaSourceCat.iterrows(): 

347 loop_logger.log("%s/%s sources have been packaged.", len(alerts), n_sources) 

348 

349 alertId = diaSource["diaSourceId"] 

350 if srcIndex[0] == 0: 350 ↛ 351line 350 didn't jump to line 351 because the condition on line 350 was never true

351 diaObject = None 

352 objSourceHistory = None 

353 objDiaForcedSources = None 

354 ssSource = ssSrc.loc[[alertId]].to_dict("records")[0] 

355 else: 

356 ssSource = None 

357 diaObject = diaObjectCat.loc[srcIndex[0]] 

358 if diaObject["nDiaSources"] > 1: 358 ↛ 361line 358 didn't jump to line 361 because the condition on line 358 was always true

359 objSourceHistory = diaSrcHistory.loc[srcIndex[0]] 

360 else: 

361 objSourceHistory = None 

362 if doRunForcedMeasurement and diaObject["nDiaSources"] >= forcedSourceHistoryThreshold: 362 ↛ 370line 362 didn't jump to line 370 because the condition on line 362 was always true

363 if srcIndex[0] in diaForcedSources.diaObjectId: 363 ↛ 367line 363 didn't jump to line 367 because the condition on line 363 was always true

364 objDiaForcedSources = diaForcedSources.loc[srcIndex[0]] 

365 else: 

366 # Send empty table with correct columns 

367 objDiaForcedSources = diaForcedSources.loc[[]] 

368 else: 

369 # Send empty table with correct columns 

370 objDiaForcedSources = diaForcedSources.loc[[]] 

371 

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

373 diaSource["dec"], 

374 geom.degrees) 

375 pixelPoint = geom.Point2D(diaSource["x"], 

376 diaSource["y"]) 

377 

378 cutoutExtent = self.createDiaSourceExtent(diaSource["bboxSize"]) 

379 diffImCutout = self.createCcdDataCutout( 

380 diffIm, 

381 sphPoint, 

382 pixelPoint, 

383 cutoutExtent, 

384 diffImPhotoCalib, 

385 diaSource["diaSourceId"], 

386 averagePsf=diffImPsf, 

387 rotPa=diffIm.visitInfo.boresightRotAngle.asDegrees()) 

388 calexpCutout = self.createCcdDataCutout( 

389 calexp, 

390 sphPoint, 

391 pixelPoint, 

392 cutoutExtent, 

393 calexpPhotoCalib, 

394 diaSource["diaSourceId"], 

395 averagePsf=sciencePsf, 

396 rotPa=calexp.visitInfo.boresightRotAngle.asDegrees()) 

397 templateCutout = self.createCcdDataCutout( 

398 template, 

399 sphPoint, 

400 pixelPoint, 

401 cutoutExtent, 

402 templatePhotoCalib, 

403 diaSource["diaSourceId"], 

404 averagePsf=templatePsf, 

405 rotPa=calexp.visitInfo.boresightRotAngle.asDegrees()) 

406 

407 alerts.append( 

408 self.makeAlertDict(diaSource["diaSourceId"], 

409 observation_reason, 

410 target_name, 

411 diaSource, 

412 diaObject, 

413 objSourceHistory, 

414 objDiaForcedSources, 

415 diffImCutout, 

416 calexpCutout, 

417 templateCutout, 

418 ssSource)) 

419 

420 if self.config.doProduceAlerts: 

421 self.log.info("Producing alerts to %s.", self.kafkaTopic) 

422 self.produceAlerts(alerts, visit, detector, midpoint_unix, exposure_time) 

423 else: 

424 # Fill values for the metadata so that downstream metrics don't crash 

425 self.metadata['visit_midpoint'] = midpoint_unix 

426 self.metadata['produce_end_timestamp'] = -1 

427 self.metadata['produce_start_timestamp'] = -1 

428 self.metadata['alert_timing_since_shutter_close'] = -1 

429 self.metadata['total_alerts'] = -1 

430 

431 if self.config.doWriteAlerts: 

432 avro_path = os.path.join(self.config.alertWriteLocation, f"{visit}_{detector}.avro") 

433 self.log.info("Writing alerts to %s.", avro_path) 

434 with open(avro_path, "wb") as f: 

435 self.alertSchema.store_alerts(f, alerts) 

436 

437 def _patchDiaSources(self, diaSources): 

438 """Add the ``programId`` column to the data. 

439 

440 Parameters 

441 ---------- 

442 diaSources : `pandas.DataFrame` 

443 DataFrame of DiaSources to patch. 

444 """ 

445 diaSources["programId"] = 0 

446 

447 def standardizeMpcOrbits(self, ssSources, schema): 

448 """Convert the MPCORB columns of solar system sources to the 

449 ``mpc_orbits`` column types. 

450 

451 Parameters 

452 ---------- 

453 ssSources : `pandas.DataFrame` 

454 Solar system sources, with ``mpc_orbits`` columns prefixed by 

455 ``MPCORB_``. 

456 schema : `dict` [`str`, `lsst.dax.apdb.schema_model.Table` \ 

457 or `felis.datamodel.Table`] or `None` 

458 Table schemas keyed by table name. 

459 

460 Returns 

461 ------- 

462 ssSources : `pandas.DataFrame` 

463 Copy of ``ssSources`` with the MPCORB columns converted, and any 

464 ``mpc_orbits`` columns that were missing added as null (or zero, 

465 if not nullable). Returned unchanged if there are no MPCORB 

466 columns. 

467 

468 Raises 

469 ------ 

470 ValueError 

471 Raised if there are MPCORB columns and ``schema`` has no 

472 ``mpc_orbits`` table, or if a column cannot be converted to its 

473 schema type. 

474 """ 

475 prefix = "MPCORB_" 

476 mpcorbColumns = [col for col in ssSources.columns if col.startswith(prefix)] 

477 if not mpcorbColumns: 

478 return ssSources 

479 if schema is None or schema.get("mpc_orbits") is None: 

480 raise ValueError("An APDB schema with an mpc_orbits table is required to package MPCORB columns.") 

481 mpcOrbits = ssSources[mpcorbColumns].rename(columns=lambda col: col[len(prefix):]) 

482 # The alert record always carries id 0; the ephemeris service id 

483 # is a string and does not convert to the schema's int. 

484 mpcOrbits["id"] = 0 

485 mpcOrbits = convertDataFrameToSdmSchema(schema, mpcOrbits, "mpc_orbits", skipIndex=True) 

486 # convertDataFrameToSdmSchema leaves a column's dtype unchanged when 

487 # the cast to a nullable type is unsafe, so check the result. 

488 checkDataFrameAgainstSdmSchema(schema, mpcOrbits, "mpc_orbits") 

489 return ssSources.drop(columns=mpcorbColumns).join(mpcOrbits.add_prefix(prefix)) 

490 

491 def findMissingDiaSourceColumns(self, diaSources): 

492 """Check that a DiaSource catalog has the correct schema for alerts. 

493 

494 Parameters 

495 ---------- 

496 diaSources : `pandas.DataFrame` 

497 DiaSources to include in alerts. 

498 

499 Returns 

500 ------- 

501 missing : `list` [`str`] 

502 Names of the DiaSource fields in the alert schema that have no 

503 default, do not accept null, and are not columns of 

504 ``diaSources``, in schema order. 

505 """ 

506 diaSourceSchema = next(field["type"] for field in self.alertSchema.definition["fields"] 

507 if field["name"] == "diaSource") 

508 return [field["name"] for field in diaSourceSchema["fields"] 

509 if "default" not in field 

510 and not (isinstance(field["type"], list) and "null" in field["type"]) 

511 and field["name"] not in diaSources.columns] 

512 

513 def createDiaSourceExtent(self, bboxSize): 

514 """Create an extent for a box for the cutouts given the size of the 

515 square BBox that covers the source footprint. 

516 

517 Parameters 

518 ---------- 

519 bboxSize : `int` 

520 Size of a side of the square bounding box in pixels. 

521 

522 Returns 

523 ------- 

524 extent : `lsst.geom.Extent2I` 

525 Geom object representing the size of the bounding box. 

526 """ 

527 if bboxSize < self.config.minCutoutSize: 

528 extent = geom.Extent2I(self.config.minCutoutSize, 

529 self.config.minCutoutSize) 

530 elif bboxSize > self.config.maxCutoutSize: 

531 extent = geom.Extent2I(self.config.maxCutoutSize, 

532 self.config.maxCutoutSize) 

533 else: 

534 extent = geom.Extent2I(bboxSize, bboxSize) 

535 return extent 

536 

537 @timeMethod 

538 def produceAlerts(self, alerts, visit, detector, midpoint_unix, exposure_time): 

539 """Serialize alerts and send them to the alert stream using 

540 confluent_kafka's producer. 

541 

542 Parameters 

543 ---------- 

544 alerts : `dict` 

545 Dictionary of alerts to be sent to the alert stream. 

546 visit, detector : `int` 

547 Visit and detector ids of these alerts. Used to write out alerts 

548 which fail to be sent to the alert stream. 

549 """ 

550 schema_id = self.alertSchema.get_schema_id() 

551 # Serialize and send alerts with the producer timestamp. 

552 total_alerts = 0 

553 produce_start_timestamp = time.time() 

554 try: 

555 for alert in alerts: 

556 alertBytes = self._serializeAlert(alert, 

557 schema=self.alertSchema.definition, schema_id=schema_id) 

558 try: 

559 timestamp = time.time()*1000 # Current time in milliseconds 

560 headers = [("producer_timestamp", str(timestamp).encode('utf-8'))] 

561 self.producer.produce(self.kafkaTopic, alertBytes, callback=self._delivery_callback, 

562 headers=headers) 

563 self.producer.flush() 

564 total_alerts += 1 

565 

566 except KafkaException as e: 

567 self.log.warning('Kafka error: %s, message was %s bytes', 

568 e, sys.getsizeof(alertBytes)) 

569 

570 if self.config.doWriteFailedAlerts: 570 ↛ 555line 570 didn't jump to line 555 because the condition on line 570 was always true

571 with open(os.path.join(self.config.alertWriteLocation, 

572 f"{visit}_{detector}_{alert['diaSourceId']}.avro"), "wb") as f: 

573 f.write(alertBytes) 

574 

575 self.producer.flush() 

576 finally: 

577 produce_end_timestamp = time.time() # Current time in seconds 

578 total_time = produce_end_timestamp - (midpoint_unix + exposure_time/2.0) 

579 self.metadata['visit_midpoint'] = midpoint_unix 

580 self.metadata['produce_end_timestamp'] = produce_end_timestamp 

581 self.metadata['produce_start_timestamp'] = produce_start_timestamp 

582 self.metadata['alert_timing_since_shutter_close'] = total_time 

583 self.metadata['total_alerts'] = total_alerts 

584 # A single log message is easier for Loki to parse than timeMethod's start+end pairs. 

585 self.log.verbose("Producing alerts: Took %.4f seconds", 

586 produce_end_timestamp - produce_start_timestamp) 

587 

588 self.log.info(f"Total time since shutter close to produce alerts for" 

589 f" visit {visit} detector {detector}: {total_time} seconds") 

590 

591 def createCcdDataCutout(self, image, skyCenter, pixelCenter, extent, photoCalib, srcId, averagePsf=None, 

592 rotPa=None): 

593 """Grab an image as a cutout and return a calibrated CCDData image. 

594 

595 Parameters 

596 ---------- 

597 image : `lsst.afw.image.ExposureF` 

598 Image to pull cutout from. 

599 skyCenter : `lsst.geom.SpherePoint` 

600 Center point of DiaSource on the sky. 

601 pixelCenter : `lsst.geom.Point2D` 

602 Pixel center of DiaSource on the sky. 

603 extent : `lsst.geom.Extent2I` 

604 Bounding box to cutout from the image. 

605 photoCalib : `lsst.afw.image.PhotoCalib` 

606 Calibrate object of the image the cutout is cut from. 

607 srcId : `int` 

608 Unique id of DiaSource. Used for when an error occurs extracting 

609 a cutout. 

610 averagePsf : `numpy.array`, optional 

611 Average PSF to attach to the cutout. 

612 Used if ``self.config.useAveragePsf`` is set. 

613 cutoutType : str, optional 

614 Type of cutout being created ('difference', 'template', or 'science') 

615 

616 Returns 

617 ------- 

618 ccdData : `astropy.nddata.CCDData` or `None` 

619 CCDData object storing the calibrate information from the input 

620 difference or template image. 

621 """ 

622 imBBox = image.getBBox() 

623 if not geom.Box2D(image.getBBox()).contains(pixelCenter): 

624 self.log.warning( 

625 "DiaSource id=%i centroid lies at pixel (%.2f, %.2f) " 

626 "which is outside the Exposure with bounding box " 

627 "((%i, %i), (%i, %i)). Returning None for cutout...", 

628 srcId, pixelCenter.x, pixelCenter.y, 

629 imBBox.minX, imBBox.maxX, imBBox.minY, imBBox.maxY) 

630 return None 

631 # Catch errors in retrieving the cutout. 

632 try: 

633 cutout = image.getCutout(pixelCenter, extent) 

634 except InvalidParameterError: 

635 self.log.warning( 

636 "Failed to retrieve cutout from image for DiaSource with " 

637 "id=%i. InvalidParameterError thrown during cutout " 

638 "creation. Returning None for cutout..." 

639 % srcId) 

640 if self.config.useAveragePsf: 

641 if averagePsf is None: 

642 self.log.info("Using source id=%i to compute the average PSF.", srcId) 

643 averagePsf = self._computePsf(image, pixelCenter, srcId=srcId) 

644 cutoutPsf = averagePsf 

645 else: 

646 cutoutPsf = self._computePsf(image, pixelCenter, srcId=srcId) 

647 

648 # Find the value of the bottom corner of our cutout's BBox and 

649 # subtract 1 so that the CCDData cutout position value will be 

650 # [1, 1]. 

651 cutOutMinX = cutout.getBBox().minX - 1 

652 cutOutMinY = cutout.getBBox().minY - 1 

653 center = cutout.getWcs().skyToPixel(skyCenter) 

654 calibCutout = photoCalib.calibrateImage(cutout.getMaskedImage()) 

655 

656 cutoutWcs = wcs.WCS(naxis=2) 

657 cutoutWcs.array_shape = (cutout.getBBox().getWidth(), 

658 cutout.getBBox().getWidth()) 

659 cutoutWcs.wcs.crpix = [center.x - cutOutMinX, center.y - cutOutMinY] 

660 cutoutWcs.wcs.crval = [skyCenter.getRa().asDegrees(), 

661 skyCenter.getDec().asDegrees()] 

662 cutoutWcs.wcs.cd = self.makeLocalTransformMatrix(cutout.getWcs(), 

663 center, 

664 skyCenter) 

665 ccdData = CCDData( 

666 data=calibCutout.getImage().array, 

667 uncertainty=VarianceUncertainty(calibCutout.getVariance().array), 

668 flags=calibCutout.getMask().array, 

669 wcs=cutoutWcs, 

670 psf=cutoutPsf, 

671 meta={"cutMinX": cutOutMinX, 

672 "cutMinY": cutOutMinY}, 

673 unit=u.nJy) 

674 

675 ccdData.header['ROTPA'] = (rotPa, 'Pos angle in deg of focal plane +Y wrt North') 

676 

677 return ccdData 

678 

679 def makeLocalTransformMatrix(self, wcs, center, skyCenter): 

680 """Create a local, linear approximation of the wcs transformation 

681 matrix. 

682 

683 The approximation is created as if the center is at RA=0, DEC=0. All 

684 comparing x,y coordinate are relative to the position of center. Matrix 

685 is initially calculated with units arcseconds and then converted to 

686 degrees. This yields higher precision results due to quirks in AST. 

687 

688 Parameters 

689 ---------- 

690 wcs : `lsst.afw.geom.SkyWcs` 

691 Wcs to approximate 

692 center : `lsst.geom.Point2D` 

693 Point at which to evaluate the LocalWcs. 

694 skyCenter : `lsst.geom.SpherePoint` 

695 Point on sky to approximate the Wcs. 

696 

697 Returns 

698 ------- 

699 localMatrix : `numpy.ndarray` 

700 Matrix representation the local wcs approximation with units 

701 degrees. 

702 """ 

703 blankCDMatrix = [[self._scale, 0], [0, self._scale]] 

704 localGnomonicWcs = afwGeom.makeSkyWcs( 

705 center, skyCenter, blankCDMatrix) 

706 measurementToLocalGnomonic = wcs.getTransform().then( 

707 localGnomonicWcs.getTransform().inverted() 

708 ) 

709 localMatrix = measurementToLocalGnomonic.getJacobian(center) 

710 return localMatrix / 3600 

711 

712 def makeAlertDict(self, 

713 diaSourceId, 

714 observationReason, 

715 targetName, 

716 diaSource, 

717 diaObject, 

718 objDiaSrcHistory, 

719 objDiaForcedSources, 

720 diffImCutout, 

721 calexpCutout, 

722 templateCutout, 

723 ssSource=None): 

724 """Convert data and package into a dictionary alert. 

725 

726 Parameters 

727 ---------- 

728 diaSourceId : `int` 

729 Unique identifier of the triggering diaSource 

730 diaSource : `pandas.DataFrame` 

731 New single DiaSource to package. 

732 observationReason : `str` 

733 Scheduler reason for the image containing this diaSource. 

734 targetName : `str` 

735 Scheduler target for the image containing this diaSource. 

736 diaObject : `pandas.DataFrame` 

737 DiaObject that ``diaSource`` is matched to. 

738 objDiaSrcHistory : `pandas.DataFrame` 

739 12 month history of ``diaObject`` excluding the latest DiaSource. 

740 objDiaForcedSources : `pandas.DataFrame` 

741 12 month history of ``diaObject`` forced measurements. 

742 diffImCutout : `astropy.nddata.CCDData` or `None` 

743 Cutout of the difference image around the location of ``diaSource`` 

744 with a min size set by the ``cutoutSize`` configurable. 

745 calexpCutout : `astropy.nddata.CCDData` or `None` 

746 Cutout of the calexp around the location of ``diaSource`` 

747 with a min size set by the ``cutoutSize`` configurable. 

748 templateCutout : `astropy.nddata.CCDData` or `None` 

749 Cutout of the template image around the location of ``diaSource`` 

750 with a min size set by the ``cutoutSize`` configurable. 

751 """ 

752 alert = dict() 

753 alert['diaSourceId'] = diaSourceId 

754 # alerts should have NULL if scheduler fields are not populated 

755 if not len(observationReason): 

756 observationReason = None 

757 if not len(targetName): 

758 targetName = None 

759 alert['observation_reason'] = observationReason 

760 alert['target_name'] = targetName 

761 alert['diaSource'] = diaSource.to_dict() 

762 

763 if objDiaSrcHistory is None: 

764 alert['prvDiaSources'] = None 

765 else: 

766 alert['prvDiaSources'] = objDiaSrcHistory.to_dict("records") 

767 

768 if isinstance(objDiaForcedSources, pd.Series): 768 ↛ 769line 768 didn't jump to line 769 because the condition on line 768 was never true

769 alert['prvDiaForcedSources'] = [objDiaForcedSources.to_dict()] 

770 elif objDiaForcedSources is None: 

771 alert['prvDiaForcedSources'] = None 

772 else: 

773 alert['prvDiaForcedSources'] = objDiaForcedSources.to_dict("records") 

774 

775 alert['prvDiaNondetectionLimits'] = None 

776 

777 if diaObject is None: 

778 alert['diaObject'] = None 

779 else: 

780 alert['diaObject'] = diaObject.to_dict() 

781 

782 if ssSource is None: 

783 alert['ssSource'] = None 

784 alert['mpc_orbits'] = None 

785 else: 

786 mpcorbColumns = [col for col in ssSource if col[:7] == 'MPCORB_'] 

787 mpcOrbit = {key[7:]: ssSource[key] for key in mpcorbColumns} 

788 

789 if 'packed_primary_provisional_designation' not in mpcOrbit: 789 ↛ 790line 789 didn't jump to line 790 because the condition on line 789 was never true

790 unpacked_desig = ssSource['designation'] 

791 packed_desig = ss_object_id_to_obj_id(ssSource['ssObjectId'], packed=True) 

792 mpcOrbit['designation'] = unpacked_desig 

793 mpcOrbit['packed_primary_provisional_designation'] = packed_desig 

794 mpcOrbit['unpacked_primary_provisional_designation'] = unpacked_desig 

795 

796 mpcOrbit['id'] = 0 

797 ssSource = {key: ssSource[key] for key in ssSource if key not in mpcorbColumns} 

798 ssSource['diaSourceId'] = diaSourceId 

799 alert['ssSource'] = ssSource 

800 alert['mpc_orbits'] = mpcOrbit 

801 

802 if diffImCutout is None: 

803 alert['cutoutDifference'] = None 

804 else: 

805 alert['cutoutDifference'] = self.streamCcdDataToBytes(diffImCutout) 

806 

807 if calexpCutout is None: 

808 alert['cutoutScience'] = None 

809 else: 

810 alert['cutoutScience'] = self.streamCcdDataToBytes(calexpCutout) 

811 

812 if templateCutout is None: 

813 alert["cutoutTemplate"] = None 

814 else: 

815 alert["cutoutTemplate"] = self.streamCcdDataToBytes(templateCutout) 

816 

817 return alert 

818 

819 def streamCcdDataToBytes(self, cutout): 

820 """Serialize a cutout into bytes. 

821 

822 Parameters 

823 ---------- 

824 cutout : `astropy.nddata.CCDData` 

825 Cutout to serialize. 

826 

827 Returns 

828 ------- 

829 coutputBytes : `bytes` 

830 Input cutout serialized into byte data. 

831 """ 

832 with io.BytesIO() as streamer: 

833 cutout.write(streamer, format="fits", hdu_flags='MASKPLANE') 

834 cutoutBytes = streamer.getvalue() 

835 return cutoutBytes 

836 

837 def _serializeAlert(self, alert, schema=None, schema_id=0): 

838 """Serialize an alert to a byte sequence for sending to Kafka. 

839 

840 Parameters 

841 ---------- 

842 alert : `dict` 

843 An alert payload to be serialized. 

844 schema : `dict`, optional 

845 An Avro schema definition describing how to encode `alert`. By default, 

846 the schema is None, which sets it to the latest schema available. 

847 schema_id : `int`, optional 

848 The Confluent Schema Registry ID of the schema. By default, 0 (an 

849 invalid ID) is used, indicating that the schema is not registered. 

850 

851 Returns 

852 ------- 

853 serialized : `bytes` 

854 The byte sequence describing the alert, including the Confluent Wire 

855 Format prefix. 

856 """ 

857 if schema is None: 

858 schema = self.alertSchema.definition 

859 

860 buf = io.BytesIO() 

861 buf.write(self._serializeConfluentWireHeader(schema_id)) 

862 fastavro.schemaless_writer(buf, schema, alert) 

863 return buf.getvalue() 

864 

865 @staticmethod 

866 def _serializeConfluentWireHeader(schema_version): 

867 """Returns the byte prefix for Confluent Wire Format-style Kafka messages. 

868 

869 Parameters 

870 ---------- 

871 schema_version : `int` 

872 A version number which indicates the Confluent Schema Registry ID 

873 number of the Avro schema used to encode the message that follows this 

874 header. 

875 

876 Returns 

877 ------- 

878 header : `bytes` 

879 The 5-byte encoded message prefix. 

880 

881 Notes 

882 ----- 

883 The Confluent Wire Format is described more fully here: 

884 https://docs.confluent.io/current/schema-registry/serdes-develop/index.html#wire-format 

885 """ 

886 ConfluentWireFormatHeader = struct.Struct(">bi") 

887 return ConfluentWireFormatHeader.pack(0, schema_version) 

888 

889 def _delivery_callback(self, err, msg): 

890 if err: 

891 if err.code() == KafkaError.UNKNOWN_TOPIC_OR_PART: 

892 topic = msg.topic() if msg and hasattr(msg, 

893 'topic') else 'unknown' 

894 self.log.warning( 

895 'Message failed delivery. Topic %s unknown: %s', 

896 topic, err) 

897 else: 

898 self.log.debug('Message delivered to %s [%d] @ %d', msg.topic(), msg.partition(), msg.offset()) 

899 

900 def _server_check(self): 

901 """Checks if the alert stream credentials are still valid and the 

902 server is contactable. 

903 

904 Raises 

905 ------- 

906 KafkaException 

907 Raised if the server us not contactable. 

908 RuntimeError 

909 Raised if the server is contactable but there are no topics 

910 present. 

911 """ 

912 admin_client = AdminClient(self.kafkaAdminConfig) 

913 topics = admin_client.list_topics(timeout=self.config.maxTimeout).topics 

914 

915 if not topics: 

916 raise RuntimeError() 

917 if self.kafkaTopic not in topics: 

918 raise RuntimeError( 

919 f"Topic '{self.kafkaTopic}' not found on the Kafka server. " 

920 f"Check that the correct topic has been provided and exists " 

921 f"on the Kafka server.") 

922 

923 def _computePsf(self, exposure, pixelCenter, srcId=None): 

924 """Compute the PSF at a location and catch errors. 

925 

926 Parameters 

927 ---------- 

928 exposure : `lsst.afw.image.Exposure` 

929 The image to compute the PSF for. 

930 pixelCenter : `lsst.geom.Point2D` 

931 The location on the image to compute the PSF. 

932 srcId : `int`, optional 

933 Unique id of DiaSource. Used for when an error occurs extracting 

934 a cutout. 

935 

936 Returns 

937 ------- 

938 cutoutPsf : `numpy.array` 

939 Array of the PSF values. 

940 """ 

941 try: 

942 # use exposure.psf.computeKernelImage to provide PSF centered in the array 

943 cutoutPsf = exposure.psf.computeKernelImage(pixelCenter).array 

944 except InvalidParameterError: 

945 if srcId is not None: 

946 msg = "Could not calculate PSF for DiaSource with "\ 

947 "id=%i. InvalidParameterError encountered. Exiting."\ 

948 % srcId 

949 else: 

950 msg = "Could not calculate average PSF for the image" 

951 self.log.warning(msg) 

952 cutoutPsf = None 

953 except InvalidPsfError: 

954 if srcId is not None: 

955 msg = "Could not calculate PSF for DiaSource with "\ 

956 "id=%i. InvalidPsfError encountered. Exiting."\ 

957 % srcId 

958 else: 

959 msg = "Could not calculate average PSF for the image" 

960 self.log.warning(msg) 

961 cutoutPsf = None 

962 # Cast the PSF to float32 to reduce the size of the alert. 

963 if cutoutPsf is not None: 963 ↛ 966line 963 didn't jump to line 966 because the condition on line 963 was always true

964 cutoutPsf = cutoutPsf.astype(np.float32) 

965 

966 return cutoutPsf