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

498 statements  

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

1# 

2# LSST Data Management System 

3# Copyright 2008-2016 AURA/LSST. 

4# 

5# This product includes software developed by the 

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

7# 

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

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

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

11# (at your option) any later version. 

12# 

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

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

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

16# GNU General Public License for more details. 

17# 

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

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

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

21# 

22 

23"""PipelineTask for associating DiaSources with previous DiaObjects. 

24 

25Additionally performs forced photometry on the calibrated and difference 

26images at the updated locations of DiaObjects. 

27""" 

28 

29__all__ = ("DiaPipelineConfig", 

30 "DiaPipelineTask", 

31 "DiaPipelineConnections") 

32 

33 

34import dataclasses 

35 

36import lsst.dax.apdb as daxApdb 

37import lsst.pex.config as pexConfig 

38import lsst.pipe.base as pipeBase 

39import lsst.pipe.base.connectionTypes as connTypes 

40import lsst.sphgeom 

41 

42from astropy.table import Table 

43import numpy as np 

44import pandas as pd 

45from lsst.ap.association import ( 

46 AssociationTask, 

47 DiaForcedSourceTask, 

48 PackageAlertsTask) 

49 

50from lsst.ap.association.loadDiaCatalogs import loadDiaObjectsFromApdb, loadDiaSourcesFromApdb, \ 

51 loadDiaForcedSourcesFromApdb 

52from lsst.ap.association.utils import makeEmptyForcedSourceTable, getRegion, paddedRegion, \ 

53 readMpcOrbitsSchema, readSchemaFromApdb 

54from lsst.daf.base import DateTime 

55from lsst.meas.base import DetectorVisitIdGeneratorConfig, \ 

56 DiaObjectCalculationTask 

57from lsst.pipe.tasks.schemaUtils import convertDataFrameToSdmSchema, checkSdmSchemaColumns, \ 

58 dropEmptyColumns, make_empty_catalog 

59from lsst.pipe.tasks.ssoAssociation import SolarSystemAssociationTask 

60from lsst.utils.timer import timeMethod, duration_from_timeMethod 

61 

62 

63class TooManyDiaObjectsError(pipeBase.AlgorithmError): 

64 """Raised if there are an unusually large number of unassociated DiaSources. 

65 This is usually indicative of an image subtraction error, and needs to be 

66 caught before updating the APDB with a large number of spurious entries. 

67 """ 

68 def __init__(self, *, nNewDiaObjects, threshold): 

69 msg = ("Aborting processing before writing to the APDB." 

70 f" {nNewDiaObjects} new DiaObjects would be created, which exceeds the" 

71 f" configured maximum of {threshold}") 

72 super().__init__(msg) 

73 self.nNewDiaObjects = nNewDiaObjects 

74 self.threshold = threshold 

75 

76 @property 

77 def metadata(self): 

78 return {"nNewDiaObjects": self.nNewDiaObjects, 

79 "threshold": self.threshold 

80 } 

81 

82 

83class PostApdbUpdateError(pipeBase.AlgorithmError): 

84 """Raised for any error that occurs after the APDB has been updated. 

85 This allows partial outputs to be written, and signals that processing 

86 can't be retried. 

87 """ 

88 def __init__(self, *, errorMsg): 

89 msg = ("Aborting processing after writing to the APDB. " 

90 "This image cannot be retried! " 

91 "The original error was:\n" 

92 f"{errorMsg}") 

93 super().__init__(msg) 

94 

95 @property 

96 def metadata(self): 

97 return {} 

98 

99 

100class DiaPipelineConnections( 

101 pipeBase.PipelineTaskConnections, 

102 dimensions=("instrument", "visit", "detector"), 

103 defaultTemplates={"coaddName": "deep", "fakesType": ""}): 

104 """Butler connections for DiaPipelineTask. 

105 """ 

106 diaSourceTable = connTypes.Input( 

107 doc="Catalog of calibrated DiaSources.", 

108 name="{fakesType}{coaddName}Diff_diaSrcTable", 

109 storageClass="DataFrame", 

110 dimensions=("instrument", "visit", "detector"), 

111 ) 

112 solarSystemObjectTable = connTypes.Input( 

113 doc="Catalog of SolarSolarSystem objects expected to be observable in " 

114 "this detectorVisit.", 

115 name="preloaded_SsObjects", 

116 storageClass="ArrowAstropy", 

117 dimensions=("instrument", "group", "detector"), 

118 minimum=0, 

119 ) 

120 diffIm = connTypes.Input( 

121 doc="Difference image on which the DiaSources were detected.", 

122 name="{fakesType}{coaddName}Diff_differenceExp", 

123 storageClass="ExposureF", 

124 dimensions=("instrument", "visit", "detector"), 

125 ) 

126 exposure = connTypes.Input( 

127 doc="Calibrated exposure differenced with a template image during " 

128 "image differencing.", 

129 name="{fakesType}calexp", 

130 storageClass="ExposureF", 

131 dimensions=("instrument", "visit", "detector"), 

132 ) 

133 template = connTypes.Input( 

134 doc="Warped template used to create `subtractedExposure`. Not PSF " 

135 "matched.", 

136 dimensions=("instrument", "visit", "detector"), 

137 storageClass="ExposureF", 

138 name="{fakesType}{coaddName}Diff_templateExp", 

139 ) 

140 preloadedDiaObjects = connTypes.Input( 

141 doc="DiaObjects preloaded from the APDB.", 

142 name="preloaded_diaObjects", 

143 storageClass="DataFrame", 

144 dimensions=("instrument", "group", "detector"), 

145 ) 

146 preloadedDiaSources = connTypes.Input( 

147 doc="DiaSources preloaded from the APDB.", 

148 name="preloaded_diaSources", 

149 storageClass="DataFrame", 

150 dimensions=("instrument", "group", "detector"), 

151 ) 

152 preloadedDiaForcedSources = connTypes.Input( 

153 doc="DiaForcedSources preloaded from the APDB.", 

154 name="preloaded_diaForcedSources", 

155 storageClass="DataFrame", 

156 dimensions=("instrument", "group", "detector"), 

157 ) 

158 apdbMarker = connTypes.Output( 

159 doc="Marker dataset storing the configuration of the Apdb for each " 

160 "visit/detector. Used to signal the completion of the pipeline.", 

161 name="apdb_marker", 

162 storageClass="Config", 

163 dimensions=("instrument", "visit", "detector"), 

164 ) 

165 associatedDiaSources = connTypes.Output( 

166 doc="Optional output storing the DiaSource catalog after matching, " 

167 "calibration, and standardization for insertion into the Apdb.", 

168 name="{fakesType}{coaddName}Diff_assocDiaSrc", 

169 storageClass="ArrowAstropy", 

170 dimensions=("instrument", "visit", "detector"), 

171 ) 

172 associatedSsSources = connTypes.Output( 

173 doc="Optional output storing ssSource data computed during association.", 

174 name="{fakesType}{coaddName}Diff_associatedSsSources", 

175 storageClass="ArrowAstropy", 

176 dimensions=("instrument", "visit", "detector"), 

177 ) 

178 unassociatedSsObjects = connTypes.Output( 

179 doc="Expected locations of an ssObject with no source", 

180 name="ssUnassociatedObjects", 

181 storageClass="ArrowAstropy", 

182 dimensions=("instrument", "visit", "detector"), 

183 ) 

184 

185 diaForcedSources = connTypes.Output( 

186 doc="Optional output storing the forced sources computed at the diaObject positions.", 

187 name="{fakesType}{coaddName}Diff_diaForcedSrc", 

188 storageClass="ArrowAstropy", 

189 dimensions=("instrument", "visit", "detector"), 

190 ) 

191 diaObjects = connTypes.Output( 

192 doc="Optional output storing the updated diaObjects associated to these sources.", 

193 name="{fakesType}{coaddName}Diff_diaObject", 

194 storageClass="ArrowAstropy", 

195 dimensions=("instrument", "visit", "detector"), 

196 ) 

197 newDiaSources = connTypes.Output( 

198 doc="New diaSources not associated with an existing diaObject that" 

199 " were used to create a new diaObject", 

200 name="{fakesType}new_dia_source", 

201 storageClass="ArrowAstropy", 

202 dimensions=("instrument", "visit", "detector"), 

203 ) 

204 marginalDiaSources = connTypes.Output( 

205 doc="Low SNR diaSources not associated with an existing diaObject that" 

206 " were rejected instead of creating a new diaObject", 

207 name="{fakesType}marginal_new_dia_source", 

208 storageClass="ArrowAstropy", 

209 dimensions=("instrument", "visit", "detector"), 

210 ) 

211 

212 def __init__(self, *, config=None): 

213 super().__init__(config=config) 

214 

215 if config.input_image_type == "future": 

216 self.diffIm = dataclasses.replace(self.diffIm, storageClass="DifferenceImage") 

217 self.exposure = dataclasses.replace(self.exposure, storageClass="VisitImage") 

218 self.template = dataclasses.replace(self.template, storageClass="DifferenceImage") 

219 

220 if not config.doWriteAssociatedSources: 220 ↛ 221line 220 didn't jump to line 221 because the condition on line 220 was never true

221 self.outputs.remove("associatedDiaSources") 

222 self.outputs.remove("diaForcedSources") 

223 self.outputs.remove("diaObjects") 

224 self.outputs.remove("newDiaSources") 

225 self.outputs.remove("marginalDiaSources") 

226 else: 

227 if not config.doRunForcedMeasurement: 

228 self.outputs.remove("diaForcedSources") 

229 if not config.filterUnAssociatedSources: 229 ↛ 230line 229 didn't jump to line 230 because the condition on line 229 was never true

230 self.outputs.remove("newDiaSources") 

231 self.outputs.remove("marginalDiaSources") 

232 if not config.doSolarSystemAssociation: 

233 self.inputs.remove("solarSystemObjectTable") 

234 if (not config.doWriteAssociatedSources) or (not config.doSolarSystemAssociation): 

235 self.outputs.remove("associatedSsSources") 

236 self.outputs.remove("unassociatedSsObjects") 

237 if config.doReloadAllApdbCatalogs: 

238 # If this is set, the complete history will be read from the APDB 

239 # during association and the preloaded catalogs will not be used. 

240 self.inputs.remove("preloadedDiaObjects") 

241 self.inputs.remove("preloadedDiaSources") 

242 self.inputs.remove("preloadedDiaForcedSources") 

243 

244 def adjustQuantum(self, inputs, outputs, label, dataId): 

245 """Override to make adjustments to `lsst.daf.butler.DatasetRef` objects 

246 in the `lsst.daf.butler.core.Quantum` during the graph generation stage 

247 of the activator. 

248 

249 This implementation checks to make sure that the filters in the dataset 

250 are compatible with AP processing as set by the Apdb/DPDD schema. 

251 

252 Parameters 

253 ---------- 

254 inputs : `dict` 

255 Dictionary whose keys are an input (regular or prerequisite) 

256 connection name and whose values are a tuple of the connection 

257 instance and a collection of associated `DatasetRef` objects. 

258 The exact type of the nested collections is unspecified; it can be 

259 assumed to be multi-pass iterable and support `len` and ``in``, but 

260 it should not be mutated in place. In contrast, the outer 

261 dictionaries are guaranteed to be temporary copies that are true 

262 `dict` instances, and hence may be modified and even returned; this 

263 is especially useful for delegating to `super` (see notes below). 

264 outputs : `dict` 

265 Dict of output datasets, with the same structure as ``inputs``. 

266 label : `str` 

267 Label for this task in the pipeline (should be used in all 

268 diagnostic messages). 

269 data_id : `lsst.daf.butler.DataCoordinate` 

270 Data ID for this quantum in the pipeline (should be used in all 

271 diagnostic messages). 

272 

273 Returns 

274 ------- 

275 adjusted_inputs : `dict` 

276 Dict of the same form as ``inputs`` with updated containers of 

277 input `DatasetRef` objects. Connections that are not changed 

278 should not be returned at all. Datasets may only be removed, not 

279 added. Nested collections may be of any multi-pass iterable type, 

280 and the order of iteration will set the order of iteration within 

281 `PipelineTask.runQuantum`. 

282 adjusted_outputs : `dict` 

283 Dict of updated output datasets, with the same structure and 

284 interpretation as ``adjusted_inputs``. 

285 

286 Raises 

287 ------ 

288 ScalarError 

289 Raised if any `Input` or `PrerequisiteInput` connection has 

290 ``multiple`` set to `False`, but multiple datasets. 

291 NoWorkFound 

292 Raised to indicate that this quantum should not be run; not enough 

293 datasets were found for a regular `Input` connection, and the 

294 quantum should be pruned or skipped. 

295 FileNotFoundError 

296 Raised to cause QuantumGraph generation to fail (with the message 

297 included in this exception); not enough datasets were found for a 

298 `PrerequisiteInput` connection. 

299 """ 

300 _, refs = inputs["diffIm"] 

301 for ref in refs: 

302 if ref.dataId["band"] not in self.config.validBands: 

303 raise ValueError( 

304 f"Requested '{ref.dataId['band']}' not in " 

305 "DiaPipelineConfig.validBands. To process bands not in " 

306 "the standard Rubin set (ugrizy) you must add the band to " 

307 "the validBands list in DiaPipelineConfig and add the " 

308 "appropriate columns to the Apdb schema.") 

309 return super().adjustQuantum(inputs, outputs, label, dataId) 

310 

311 

312class DiaPipelineConfig(pipeBase.PipelineTaskConfig, 

313 pipelineConnections=DiaPipelineConnections): 

314 """Config for DiaPipelineTask. 

315 """ 

316 input_image_type = pexConfig.ChoiceField[str]( 

317 doc="Type of the input images. run() takes lsst.afw.image.ExposureF" 

318 " either way.", 

319 allowed={ 

320 "legacy": "Read `lsst.afw.image.ExposureF`.", 

321 "future": "Read `lsst.images.VisitImage` for the science image and" 

322 " `lsst.images.DifferenceImage` for the difference image and" 

323 " template.", 

324 }, 

325 optional=False, 

326 default="legacy", 

327 ) 

328 coaddName = pexConfig.Field( 

329 doc="coadd name: typically one of deep, goodSeeing, or dcr", 

330 dtype=str, 

331 default="deep", 

332 ) 

333 apdb_config_url = pexConfig.Field( 

334 dtype=str, 

335 default=None, 

336 optional=False, 

337 doc="A config file specifying the APDB and its connection parameters, " 

338 "typically written by the apdb-cli command-line utility. " 

339 "The database must already be initialized.", 

340 ) 

341 validBands = pexConfig.ListField( 

342 dtype=str, 

343 default=["u", "g", "r", "i", "z", "y"], 

344 doc="List of bands that are valid for AP processing. To process a " 

345 "band not on this list, the appropriate band specific columns " 

346 "must be added to the Apdb schema in dax_apdb.", 

347 ) 

348 associator = pexConfig.ConfigurableField( 

349 target=AssociationTask, 

350 doc="Task used to associate DiaSources with DiaObjects.", 

351 ) 

352 doSolarSystemAssociation = pexConfig.Field( 

353 dtype=bool, 

354 default=True, 

355 doc="Process SolarSystem objects through the pipeline.", 

356 ) 

357 solarSystemAssociator = pexConfig.ConfigurableField( 

358 target=SolarSystemAssociationTask, 

359 doc="Task used to associate DiaSources with SolarSystemObjects.", 

360 ) 

361 diaCalculation = pexConfig.ConfigurableField( 

362 target=DiaObjectCalculationTask, 

363 doc="Task to compute summary statistics for DiaObjects.", 

364 ) 

365 doReloadDiaObjects = pexConfig.Field( 

366 dtype=bool, 

367 default=True, 

368 doc="Drop preloaded DiaObjects and reload them from the APDB?" 

369 "Used in production when the very latest objects from the APDB " 

370 "are needed. Ignored and superceded if `doReloadAllApdbCatalogs` " 

371 "is set.", 

372 ) 

373 doReloadAllApdbCatalogs = pexConfig.Field( 

374 dtype=bool, 

375 default=False, 

376 doc="Read the complete DiaObject, DiaSource, and DiaForcedSource " 

377 "history from the APDB during association? Use only during " 

378 "reprocessing, and never in Prompt Processing.", 

379 ) 

380 angleMargin = pexConfig.RangeField( 

381 doc="Padding to add when reloading catalogs from the APDB. " 

382 "Smaller than the padding used for ``LoadDiaCatalogsTask`` because " 

383 "this task is after astrometric calibration.", 

384 dtype=float, 

385 default=2, 

386 min=0, 

387 ) 

388 doRunForcedMeasurement = pexConfig.Field( 

389 dtype=bool, 

390 default=True, 

391 deprecated="Added to allow disabling forced sources for performance " 

392 "reasons during the ops rehearsal. " 

393 "It is expected to be removed.", 

394 doc="Run forced measurement on all of the diaObjects? " 

395 "This should only be turned off for debugging purposes.", 

396 ) 

397 diaForcedSource = pexConfig.ConfigurableField( 

398 target=DiaForcedSourceTask, 

399 doc="Task used for force photometer DiaObject locations in direct and " 

400 "difference images.", 

401 ) 

402 forcedReliabilityThreshold = pexConfig.Field( 

403 dtype=float, 

404 default=0.5, 

405 doc="Minimum reliability score of constituent diaSources to use when " 

406 "determining whether to calculate forced photometry for a " 

407 "diaObject.", 

408 ) 

409 forcedTrailLengthThreshold = pexConfig.Field( 

410 dtype=float, 

411 default=1.4, 

412 doc="Maximum trail length (arseconds) of constituent diaSources to use " 

413 "when determining whether to calculate forced photometry for a " 

414 "diaObject.", 

415 ) 

416 forcedBadFlags = pexConfig.ListField( 

417 dtype=str, 

418 default=["glint_trail", "isDipole"], 

419 doc="Flags of constituent diaSources to exclude when determining " 

420 "whether to calculate forced photometry for a diaObject.", 

421 ) 

422 alertPackager = pexConfig.ConfigurableField( 

423 target=PackageAlertsTask, 

424 doc="Subtask for packaging Ap data into alerts.", 

425 ) 

426 doPackageAlerts = pexConfig.Field( 

427 dtype=bool, 

428 default=False, 

429 doc="Package Dia-data into serialized alerts for distribution and " 

430 "write them to disk.", 

431 ) 

432 doWriteAssociatedSources = pexConfig.Field( 

433 dtype=bool, 

434 default=True, 

435 doc="Write out associated DiaSources, DiaForcedSources, and DiaObjects, " 

436 "formatted following the Science Data Model.", 

437 ) 

438 imagePixelMargin = pexConfig.RangeField( 

439 dtype=int, 

440 default=10, 

441 min=0, 

442 doc="Pad the image by this many pixels before removing off-image " 

443 "diaObjects for association.", 

444 ) 

445 filterUnAssociatedSources = pexConfig.Field( 

446 dtype=bool, 

447 default=True, 

448 doc="Check unassociated diaSources for quality before creating new ." 

449 "diaObjects. DiaSources that are associated with existing diaObjects " 

450 "will not be affected." 

451 ) 

452 newObjectBadFlags = pexConfig.ListField( 

453 dtype=str, 

454 default=("centroid_flag", 

455 "pixelFlags_crCenter", 

456 "pixelFlags_nodataCenter", 

457 "pixelFlags_interpolatedCenter", 

458 "pixelFlags_saturatedCenter", 

459 "pixelFlags_suspectCenter", 

460 "pixelFlags_streakCenter", 

461 "glint_trail"), 

462 doc="If `filterUnAssociatedSources` is set, exclude diaSources with " 

463 "these flags set before creating new diaObjects.", 

464 ) 

465 maxNewDiaObjects = pexConfig.RangeField( 

466 dtype=float, 

467 default=0, 

468 min=0, 

469 doc="Maximum number of new DiaObjects to create before raising an error." 

470 "Set to zero to disable.", 

471 ) 

472 newObjectSnrThreshold = pexConfig.RangeField( 

473 dtype=float, 

474 default=0, 

475 min=0, 

476 doc="If `filterUnAssociatedSources` is set, exclude diaSources with " 

477 "Abs(flux/fluxErr) less than this threshold before creating new " 

478 "diaObjects." 

479 "Set to zero to disable.", 

480 ) 

481 newObjectLowReliabilitySnrThreshold = pexConfig.RangeField( 

482 dtype=float, 

483 default=0, 

484 min=0, 

485 doc="If `filterUnAssociatedSources` is set, exclude diaSources with " 

486 "signal-to-noise ratios less than this threshold if they have" 

487 " low reliability scores before creating new diaObjects." 

488 "Set to zero to disable.", 

489 ) 

490 newObjectReliabilityThreshold = pexConfig.RangeField( 

491 dtype=float, 

492 default=0.1, 

493 min=0, 

494 max=1, 

495 doc="If `filterUnAssociatedSources` is set, exclude diaSources with " 

496 "reliability scores less than this threshold before creating new " 

497 "diaObjects." 

498 "Set to zero to disable.", 

499 ) 

500 newObjectLowSnrReliabilityThreshold = pexConfig.RangeField( 

501 dtype=float, 

502 default=0.1, 

503 min=0, 

504 max=1, 

505 doc="If `filterUnAssociatedSources` is set, exclude diaSources with " 

506 "low signal-to-noise and reliability scores below this threshold " 

507 "before creating new diaObjects." 

508 "Set to zero to disable.", 

509 ) 

510 newObjectFluxField = pexConfig.Field( 

511 dtype=str, 

512 default="apFlux", 

513 doc="Name of the flux field in the standardized diaSource catalog to " 

514 "use for checking the signal-to-noise before creating new diaObjects.", 

515 ) 

516 idGenerator = DetectorVisitIdGeneratorConfig.make_field() 

517 

518 def setDefaults(self): 

519 self.diaCalculation.plugins = ["ap_meanPosition", 

520 "ap_firstLastDiaSourceTime", 

521 "ap_nDiaSources", 

522 "ap_meanFlux", 

523 "ap_sigmaFlux", 

524 "ap_minMaxFlux", 

525 "ap_maxSlopeFlux", 

526 "ap_meanErrFlux", 

527 "ap_meanTotFlux"] 

528 

529 

530class DiaPipelineTask(pipeBase.PipelineTask): 

531 """Task for loading, associating and storing Difference Image Analysis 

532 (DIA) Objects and Sources. 

533 """ 

534 ConfigClass = DiaPipelineConfig 

535 _DefaultName = "diaPipe" 

536 

537 def __init__(self, initInputs=None, **kwargs): 

538 super().__init__(**kwargs) 

539 self.apdb = daxApdb.Apdb.from_uri(self.config.apdb_config_url) 

540 self.schema = readSchemaFromApdb(self.apdb) 

541 # Alerts include mpc_orbits records, which the APDB does not store. 

542 self.schema["mpc_orbits"] = readMpcOrbitsSchema(self.apdb) 

543 # Fail at startup rather than after the first APDB write. 

544 if (self.config.doPackageAlerts and self.config.doSolarSystemAssociation 

545 and self.schema["mpc_orbits"] is None): 

546 raise ValueError(f"APDB schema file {self.apdb.getConfig().schema_file} has no mpc_orbits " 

547 "table, which alerts for solar system sources require.") 

548 self.makeSubtask("associator") 

549 self.makeSubtask("diaCalculation") 

550 if self.config.doRunForcedMeasurement: 

551 self.makeSubtask("diaForcedSource") 

552 if self.config.doPackageAlerts: 

553 self.makeSubtask("alertPackager") 

554 if self.config.doSolarSystemAssociation: 

555 self.makeSubtask("solarSystemAssociator") 

556 if self.config.filterUnAssociatedSources: 

557 columns = [self.config.newObjectFluxField, 

558 self.config.newObjectFluxField + "Err", 

559 "reliability"] 

560 columns += self.config.newObjectBadFlags 

561 

562 missing = checkSdmSchemaColumns(self.schema, columns, "DiaSource") 

563 if missing: 

564 raise pipeBase.InvalidQuantumError("Field %s not in the DiaSource schema" % missing) 

565 

566 def runQuantum(self, butlerQC, inputRefs, outputRefs): 

567 inputs = butlerQC.get(inputRefs) 

568 if self.config.input_image_type == "future": 

569 for name in ("diffIm", "exposure", "template"): 

570 inputs[name] = inputs[name].to_legacy() 

571 inputs["idGenerator"] = self.config.idGenerator.apply(butlerQC.quantum.dataId) 

572 inputs["band"] = butlerQC.quantum.dataId["band"] 

573 inputs["legacySolarSystemTable"] = None 

574 if not self.config.doSolarSystemAssociation: 574 ↛ 575line 574 didn't jump to line 575 because the condition on line 574 was never true

575 inputs["solarSystemObjectTable"] = None 

576 

577 associationResults = pipeBase.Struct( 

578 apdbMarker=None, 

579 associatedDiaSources=None, 

580 diaForcedSources=None, 

581 diaObjects=None, 

582 associatedSsSources=None, 

583 unassociatedSsObjects=None, 

584 newDiaSources=None, 

585 marginalDiaSources=None, 

586 ) 

587 try: 

588 self.run(**inputs, associationResults=associationResults) 

589 except pipeBase.AlgorithmError as e: 

590 error = pipeBase.AnnotatedPartialOutputsError.annotate( 

591 e, 

592 self, 

593 log=self.log 

594 ) 

595 butlerQC.put(associationResults, outputRefs) 

596 raise error from e 

597 butlerQC.put(associationResults, outputRefs) 

598 

599 @timeMethod 

600 def run(self, 

601 diaSourceTable, 

602 legacySolarSystemTable, 

603 diffIm, 

604 exposure, 

605 template, 

606 preloadedDiaObjects=None, 

607 preloadedDiaSources=None, 

608 preloadedDiaForcedSources=None, 

609 band=None, 

610 idGenerator=None, 

611 solarSystemObjectTable=None, 

612 associationResults=None): 

613 """Process DiaSources and DiaObjects. 

614 

615 Load previous DiaObjects and their DiaSource history. Calibrate the 

616 values in the diaSourceCat. Associate new DiaSources with previous 

617 DiaObjects. Run forced photometry at the updated DiaObject locations. 

618 Store the results in the Alert Production Database (Apdb). 

619 

620 Parameters 

621 ---------- 

622 diaSourceTable : `pandas.DataFrame` 

623 Newly detected DiaSources. 

624 legacySolarSystemTable : `pandas.DataFrame` 

625 Not used 

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

627 Difference image exposure in which the sources in ``diaSourceCat`` 

628 were detected. 

629 exposure : `lsst.afw.image.ExposureF` 

630 Calibrated exposure differenced with a template to create 

631 ``diffIm``. 

632 template : `lsst.afw.image.ExposureF` 

633 Template exposure used to create diffIm. 

634 preloadedDiaObjects : `pandas.DataFrame`, optional 

635 Previously detected DiaObjects, loaded from the APDB. 

636 `None` if ``doReloadAllApdbCatalogs`` is set. 

637 preloadedDiaSources : `pandas.DataFrame`, optional 

638 Previously detected DiaSources, loaded from the APDB. 

639 `None` if ``doReloadAllApdbCatalogs`` is set. 

640 preloadedDiaForcedSources : `pandas.DataFrame`, optional 

641 Catalog of previously detected forced DiaSources, from the APDB. 

642 `None` if ``doReloadAllApdbCatalogs`` is set. 

643 band : `str` 

644 The band in which the new DiaSources were detected. Required, 

645 despite the `None` default. 

646 idGenerator : `lsst.meas.base.IdGenerator` 

647 Object that generates source IDs and random number generator seeds. 

648 Required, despite the `None` default. 

649 solarSystemObjectTable : `astropy.table.Table`, optional 

650 Preloaded Solar System objects expected to be visible in the image. 

651 associationResults : `lsst.pipe.base.Struct`, optional 

652 Result struct that is modified to allow saving of partial outputs 

653 for some failure conditions. If the task completes successfully, 

654 this is also returned. 

655 

656 Returns 

657 ------- 

658 associationResults : `lsst.pipe.base.Struct` 

659 Results struct with components. 

660 

661 - ``apdbMarker`` : Marker dataset to store in the Butler indicating 

662 that this ccdVisit has completed successfully. 

663 (`lsst.dax.apdb.ApdbConfig`) 

664 - ``associatedDiaSources`` : Catalog of newly associated 

665 DiaSources. (`pandas.DataFrame`) 

666 - ``diaForcedSources`` : Catalog of new and previously detected 

667 forced DiaSources. (`pandas.DataFrame`) 

668 - ``diaObjects`` : Updated table of DiaObjects. (`pandas.DataFrame`) 

669 - ``associatedSsSources`` : Catalog of ssSource records. 

670 (`pandas.DataFrame`) 

671 

672 Raises 

673 ------ 

674 RuntimeError 

675 Raised if duplicate DiaObjects or duplicate DiaSources are found. 

676 ValueError 

677 Raised if ``band`` or ``idGenerator`` is `None`. 

678 """ 

679 # These default to `None` only so that the preloaded catalogs, which 

680 # precede them, can be omitted. 

681 if band is None: 

682 raise ValueError("band is required.") 

683 if idGenerator is None: 

684 raise ValueError("idGenerator is required.") 

685 

686 if associationResults is None: 686 ↛ 688line 686 didn't jump to line 688 because the condition on line 686 was always true

687 associationResults = pipeBase.Struct() 

688 self._validateExposure(exposure, "Science") 

689 self._validateExposure(diffIm, "Difference") 

690 self._validateExposure(template, "Template") 

691 

692 # Accept either legacySolarSystemTable or optional solarSystemObjectTable. 

693 if legacySolarSystemTable is not None and solarSystemObjectTable is None: 693 ↛ 694line 693 didn't jump to line 694 because the condition on line 693 was never true

694 solarSystemObjectTable = Table.from_pandas(legacySolarSystemTable) 

695 region = getRegion(exposure) 

696 if self.config.doReloadDiaObjects or self.config.doReloadAllApdbCatalogs: 

697 try: 

698 preloadedDiaObjects = self.loadRefreshedDiaObjects(region, preloadedDiaObjects) 

699 except Exception as e: 

700 if self.config.doReloadAllApdbCatalogs: 

701 # We can't continue if the diaObjects were not loaded and 

702 # ``doReloadAllApdbCatalogs`` is set, because there will be 

703 # no preloaded diaObjects to fall back on. 

704 raise 

705 self.log.warning("Error encountered while attempting to load " 

706 "the latest diaObjects from the APDB. Processing " 

707 "will continue with only the diaObjects from " 

708 "preload.", exc_info=e) 

709 finally: 

710 self.metadata["loadDiaObjectsDuration"] = duration_from_timeMethod( 

711 self.metadata, "loadRefreshedDiaObjects", clock="Utc" 

712 ) 

713 self.log.verbose("Re-loading DiaObjects: Took %.4f seconds", 

714 self.metadata["loadDiaObjectsDuration"]) 

715 

716 else: 

717 self.metadata["loadDiaObjectsDuration"] = -1 

718 

719 if self.config.doReloadAllApdbCatalogs: 

720 # The metadata time records must use the same names as 

721 # LoadDiaCatalogsTask to keep the metrics upload consistent. 

722 visitTime = exposure.visitInfo.date.toAstropy() 

723 try: 

724 preloadedDiaSources = self.loadRefreshedDiaSources(region, preloadedDiaObjects, visitTime) 

725 finally: 

726 self.metadata["loadDiaSourcesDuration"] = duration_from_timeMethod( 

727 self.metadata, "loadRefreshedDiaSources", clock="Utc" 

728 ) 

729 self.log.verbose("Re-loading DiaSources: Took %.4f seconds", 

730 self.metadata["loadDiaSourcesDuration"]) 

731 try: 

732 preloadedDiaForcedSources = self.loadRefreshedDiaForcedSources( 

733 region, preloadedDiaObjects, visitTime) 

734 finally: 

735 self.metadata["loadDiaForcedSourcesDuration"] = duration_from_timeMethod( 

736 self.metadata, "loadRefreshedDiaForcedSources", clock="Utc" 

737 ) 

738 self.log.verbose("Re-loading DiaForcedSources: Took %.4f seconds", 

739 self.metadata["loadDiaForcedSourcesDuration"]) 

740 else: 

741 self.metadata["loadDiaSourcesDuration"] = -1 

742 self.metadata["loadDiaForcedSourcesDuration"] = -1 

743 

744 self.checkTableIndex(preloadedDiaSources, index=["diaObjectId", "band", "diaSourceId"]) 

745 self.checkTableIndex(preloadedDiaObjects, index="diaObjectId") 

746 self.checkTableIndex(preloadedDiaForcedSources, index=["diaObjectId", "diaForcedSourceId"]) 

747 

748 # Alerts include the DiaSource history, so check that it has every 

749 # column they require while the image can still be retried. 

750 if self.config.doPackageAlerts and not preloadedDiaSources.empty: 

751 missing = self.alertPackager.findMissingDiaSourceColumns(preloadedDiaSources) 

752 if missing: 

753 raise ValueError( 

754 "Aborting before writing to the APDB: the DiaSource history lacks columns that " 

755 f"alerts require: {', '.join(missing)}. It may predate these columns in the APDB schema." 

756 ) 

757 

758 if not preloadedDiaObjects.empty: 758 ↛ 763line 758 didn't jump to line 763 because the condition on line 758 was always true

759 # Include a small buffer outside the image so that we can associate sources near the edge 

760 diaObjects, _ = self.purgeDiaObjects(diffIm.getBBox(), diffIm.getWcs(), preloadedDiaObjects, 

761 buffer=self.config.imagePixelMargin) 

762 else: 

763 self.log.info("Preloaded DiaObject table is empty.") 

764 diaObjects = preloadedDiaObjects 

765 

766 # Associate DiaSources with DiaObjects 

767 assocResults = self.associateDiaSources(diaSourceTable, solarSystemObjectTable, diffIm, diaObjects) 

768 

769 # Set unassociated diaObjectIds and ssObjectIds to NULL, and convert to SDM schema format 

770 standardizedAssociatedDiaSources = self.standardizeDataFrame( 

771 assocResults.associatedDiaSources, 

772 "DiaSource", 

773 nullColumns=["diaObjectId", "ssObjectId"] 

774 ) 

775 

776 # Merge associated diaSources 

777 mergedDiaSourceHistory, mergedDiaObjects, updatedDiaObjectIds = self.mergeAssociatedCatalogs( 

778 preloadedDiaSources, 

779 assocResults.associatedDiaSources, 

780 diaObjects, 

781 assocResults.newDiaObjects, 

782 diffIm 

783 ) 

784 

785 # Compute DiaObject Summary statistics from their full DiaSource 

786 # history. 

787 diaCalResult = self.diaCalculation.run( 

788 mergedDiaObjects, 

789 mergedDiaSourceHistory, 

790 updatedDiaObjectIds, 

791 self.config.validBands) 

792 updatedDiaObjects = convertDataFrameToSdmSchema(self.schema, diaCalResult.updatedDiaObjects, 

793 tableName="DiaObject", skipIndex=True) 

794 

795 # Test for duplication in the updated DiaObjects. 

796 if self.testDataFrameIndex(diaCalResult.diaObjectCat): 796 ↛ 797line 796 didn't jump to line 797 because the condition on line 796 was never true

797 raise RuntimeError( 

798 "Duplicate DiaObjects (loaded + updated) created after " 

799 "DiaCalculation. This is unexpected behavior and should be " 

800 "reported. Exiting.") 

801 if self.testDataFrameIndex(updatedDiaObjects): 801 ↛ 802line 801 didn't jump to line 802 because the condition on line 801 was never true

802 raise RuntimeError( 

803 "Duplicate DiaObjects (updated) created after " 

804 "DiaCalculation. This is unexpected behavior and should be " 

805 "reported. Exiting.") 

806 

807 # Forced source measurement 

808 if self.config.doRunForcedMeasurement: 

809 diaObjectsForced = self._selectGoodDiaObjects(diaCalResult.diaObjectCat, mergedDiaSourceHistory) 

810 diaForcedSources = self.runForcedMeasurement( 

811 diaObjectsForced, updatedDiaObjects, exposure, diffIm, idGenerator 

812 ) 

813 forcedSourceHistoryThreshold = self.diaForcedSource.config.historyThreshold 

814 else: 

815 # alertPackager needs correct columns 

816 diaForcedSources = makeEmptyForcedSourceTable(self.schema) 

817 forcedSourceHistoryThreshold = 0 

818 

819 # Write results to Alert Production Database (APDB) 

820 try: 

821 validityStart = self.writeToApdb(updatedDiaObjects, standardizedAssociatedDiaSources, 

822 diaForcedSources) 

823 finally: 

824 self.metadata["writeToApdbDuration"] = duration_from_timeMethod(self.metadata, "writeToApdb", 

825 clock="Utc") 

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

827 self.log.verbose("writeToApdb: Took %.4f seconds", self.metadata["writeToApdbDuration"]) 

828 

829 # For historical reasons, apdbMarker is a Config even if it's not meant to be read. 

830 # A default Config is the cheapest way to satisfy the storage class. 

831 associationResults.apdbMarker = pexConfig.Config() 

832 associationResults.associatedDiaSources = assocResults.associatedDiaSources 

833 associationResults.diaForcedSources = diaForcedSources 

834 associationResults.diaObjects = diaCalResult.diaObjectCat 

835 associationResults.unassociatedSsObjects = assocResults.unassociatedSsObjects 

836 associationResults.newDiaSources = assocResults.newDiaSources 

837 associationResults.marginalDiaSources = assocResults.marginalDiaSources 

838 

839 # Catch *any* error after we have updated the APDB 

840 try: 

841 associatedSsSources = assocResults.associatedSsSources 

842 associatedSsSourcesPlusMpcorb = None 

843 if associatedSsSources is not None: 

844 mpcorbColumns = [col for col in associatedSsSources.columns if col[:7] == 'MPCORB_'] 

845 associatedSsSourceMpcorb = associatedSsSources[mpcorbColumns].copy() 

846 associatedSsSources = self.standardizeTable(associatedSsSources, "SSSource", nullColumns=[]) 

847 associatedSsSourcesPlusMpcorb = associatedSsSources.copy() 

848 for mpcorbColumn in mpcorbColumns: 848 ↛ 849line 848 didn't jump to line 849 because the loop on line 848 never started

849 associatedSsSourcesPlusMpcorb[mpcorbColumn] = associatedSsSourceMpcorb[mpcorbColumn] 

850 associationResults.associatedSsSources = associatedSsSources 

851 

852 # patch the otherwise-empty validityStart field for the alerts 

853 updatedDiaObjects['validityStartMjdTai'] = validityStart.get(system=DateTime.MJD, 

854 scale=DateTime.TAI) 

855 

856 # Package alerts 

857 if self.config.doPackageAlerts: 

858 # Append new forced sources to the full history 

859 diaForcedSourcesFull = self.mergeCatalogs(preloadedDiaForcedSources, diaForcedSources, 

860 tableName="DiaForcedSource") 

861 if self.testDataFrameIndex(diaForcedSourcesFull): 861 ↛ 862line 861 didn't jump to line 862 because the condition on line 861 was never true

862 self.log.warning( 

863 "Duplicate DiaForcedSources created after merge with " 

864 "history and new sources. This may cause downstream " 

865 "problems. Dropping duplicates.") 

866 # Drop duplicates via index and keep the first appearance. 

867 diaForcedSourcesFull = diaForcedSourcesFull[ 

868 ~diaForcedSourcesFull.index.duplicated(keep="first")] 

869 

870 self.alertPackager.run(assocResults.associatedDiaSources, 

871 updatedDiaObjects, 

872 preloadedDiaSources, 

873 diaForcedSourcesFull, 

874 diffIm, 

875 exposure, 

876 template, 

877 ssSrc=associatedSsSourcesPlusMpcorb, 

878 doRunForcedMeasurement=self.config.doRunForcedMeasurement, 

879 forcedSourceHistoryThreshold=forcedSourceHistoryThreshold, 

880 schema=self.schema, 

881 ) 

882 except Exception as e: 

883 # Catch *any* error after we have updated the APDB 

884 raise PostApdbUpdateError(errorMsg=repr(e)) from e 

885 

886 return associationResults 

887 

888 def _validateExposure(self, exposure, label): 

889 """Validate exposure metadata early to avoid failures after updating 

890 the APDB. 

891 

892 Parameters 

893 ---------- 

894 exposure : `lsst.afw.image.ExposureF` 

895 Calibrated science image that was subtracted. Corresponds to the 

896 ``exposure`` Butler connection (``{fakesType}calexp``). 

897 label : `str` 

898 Specification of the image being validated, for logging messages. 

899 

900 Raises 

901 ------ 

902 ValueError 

903 Raised when any required metadata field is missing or invalid. 

904 """ 

905 errors = [] 

906 

907 photo_calib = exposure.getPhotoCalib() 

908 if photo_calib is None: 908 ↛ 909line 908 didn't jump to line 909 because the condition on line 908 was never true

909 errors.append( 

910 f"{label}: PhotoCalib is None; flux-to-nJy calibration " 

911 "in alert packaging will fail." 

912 ) 

913 else: 

914 mean = photo_calib.getCalibrationMean() 

915 if not np.isfinite(mean) or mean <= 0.0: 915 ↛ 916line 915 didn't jump to line 916 because the condition on line 915 was never true

916 errors.append( 

917 f"{label}: PhotoCalib calibration mean is {mean!r}; " 

918 "must be a finite, positive value." 

919 ) 

920 

921 if exposure.getWcs() is None: 921 ↛ 922line 921 didn't jump to line 922 because the condition on line 921 was never true

922 errors.append( 

923 f"{label}: WCS is None; sky-to-pixel projection and " 

924 "DIA Object association will fail." 

925 ) 

926 

927 # Skip visitInfo checks for the template 

928 if label != "Template": 

929 visit_info = exposure.getInfo().getVisitInfo() 

930 if visit_info is None: 930 ↛ 931line 930 didn't jump to line 931 because the condition on line 930 was never true

931 errors.append( 

932 f"{label}: VisitInfo is None; observation time, pointing, " 

933 "rotation angle, and exposure duration are unavailable." 

934 ) 

935 else: 

936 obs_date = visit_info.getDate() 

937 if not obs_date.isValid(): 937 ↛ 938line 937 didn't jump to line 938 because the condition on line 937 was never true

938 errors.append( 

939 f"{label}: VisitInfo.date is invalid." 

940 ) 

941 

942 # boresightRaDec — written to APDB rows and alert payloads. 

943 boresight = visit_info.getBoresightRaDec() 

944 ra_deg = boresight.getRa().asDegrees() 

945 dec_deg = boresight.getDec().asDegrees() 

946 if not np.isfinite(ra_deg) or not np.isfinite(dec_deg): 946 ↛ 947line 946 didn't jump to line 947 because the condition on line 946 was never true

947 errors.append( 

948 f"{label}: VisitInfo.boresightRaDec contains NaN " 

949 f"(RA={ra_deg}, Dec={dec_deg}); pointing metadata " 

950 "is missing or corrupt." 

951 ) 

952 

953 rot_deg = visit_info.getBoresightRotAngle().asDegrees() 

954 if not np.isfinite(rot_deg): 954 ↛ 955line 954 didn't jump to line 955 because the condition on line 954 was never true

955 errors.append( 

956 f"{label}: VisitInfo.boresightRotAngle is NaN; the " 

957 "ROTPA keyword will be corrupt in all alert cutout " 

958 "FITS headers." 

959 ) 

960 

961 filter_label = exposure.getFilter() 

962 if filter_label is None: 962 ↛ 963line 962 didn't jump to line 963 because the condition on line 962 was never true

963 errors.append( 

964 f"{label}: filter label is None." 

965 ) 

966 else: 

967 band = filter_label.bandLabel if filter_label.hasBandLabel() else "" 

968 if not band: 968 ↛ 969line 968 didn't jump to line 969 because the condition on line 968 was never true

969 errors.append( 

970 f"{label}: filter label carries no band name." 

971 ) 

972 

973 bbox = exposure.getBBox() 

974 if bbox.getWidth() <= 0 or bbox.getHeight() <= 0: 974 ↛ 975line 974 didn't jump to line 975 because the condition on line 974 was never true

975 errors.append( 

976 f"{label}: bounding box is empty " 

977 f"({bbox.getWidth()}×{bbox.getHeight()} px); the " 

978 "readout or ISR step may have failed." 

979 ) 

980 

981 if exposure.getPsf() is None: 981 ↛ 982line 981 didn't jump to line 982 because the condition on line 981 was never true

982 errors.append( 

983 f"{label}: PSF model is None." 

984 ) 

985 

986 if errors: 986 ↛ 987line 986 didn't jump to line 987 because the condition on line 986 was never true

987 detail = "\n ".join(errors) 

988 raise ValueError( 

989 "Input exposure metadata is invalid; aborting before any " 

990 "APDB writes to prevent non-recoverable data corruption:\n " 

991 + detail 

992 ) 

993 

994 def _selectGoodDiaObjects(self, diaObjects, diaSources): 

995 """ 

996 Extract a subset of diaObjects with multiple associated diaSources that 

997 pass selection requirements. 

998 """ 

999 n_history = self.diaForcedSource.config.historyThreshold 

1000 required_columns = ["reliability", "trailLength"] 

1001 for col in required_columns: 

1002 if col not in diaSources.columns: 

1003 raise RuntimeError("Required column '%s' missing from diaSource table." % col) 

1004 

1005 rel_ok = diaSources["reliability"] >= self.config.forcedReliabilityThreshold 

1006 trailed_ok = diaSources["trailLength"] <= self.config.forcedTrailLengthThreshold 

1007 badFlags = [f for f in self.config.forcedBadFlags if f in diaSources.columns] 

1008 if badFlags: 

1009 self.log.info("Excluding diaSources with %s flags set when calculating" 

1010 " diaObject history for forced photometry." % badFlags) 

1011 # Exclude rows where ANY bad flag is True. 

1012 # If bad flag columns can contain NA, treat NA as True (i.e., bad) via fillna(True). 

1013 bad_any = diaSources[badFlags].fillna(True).any(axis=1) 

1014 mask = rel_ok & trailed_ok & ~bad_any 

1015 ids = diaSources.index.get_level_values("diaObjectId")[mask] 

1016 

1017 # Count occurrences in diaSource 

1018 counts = pd.Series(ids, copy=False).value_counts() 

1019 

1020 # IDs that exceed threshold 

1021 keep_ids = counts[counts >= n_history].index 

1022 

1023 # Since diaObject index is unique, direct index filtering is safe and efficient 

1024 return diaObjects.loc[diaObjects.index.intersection(keep_ids)] 

1025 

1026 def createNewDiaObjects(self, unassociatedDiaSources): 

1027 """Loop through the set of DiaSources and create new DiaObjects 

1028 for unassociated DiaSources. 

1029 

1030 Parameters 

1031 ---------- 

1032 unassociatedDiaSources : `pandas.DataFrame` 

1033 Set of DiaSources to create new DiaObjects from. 

1034 

1035 Returns 

1036 ------- 

1037 results : `lsst.pipe.base.Struct` 

1038 Results struct containing: 

1039 

1040 - diaSources : `pandas.DataFrame` 

1041 DiaSource catalog with updated DiaObject ids. 

1042 - newDiaObjects : `pandas.DataFrame` 

1043 Newly created DiaObjects from the unassociated DiaSources. 

1044 - nNewDiaObjects : `int` 

1045 Number of newly created diaObjects. 

1046 - marginalDiaSources : `pandas.DataFrame` 

1047 Unassociated diaSources with low signal-to-noise and/or 

1048 reliability, which are excluded from the new DiaObjects. 

1049 """ 

1050 marginalDiaSources = make_empty_catalog(self.schema, tableName="DiaSource") 

1051 if len(unassociatedDiaSources) == 0: 

1052 newDiaObjects = make_empty_catalog(self.schema, tableName="DiaObject") 

1053 else: 

1054 if self.config.filterUnAssociatedSources: 

1055 results = self.filterSources(unassociatedDiaSources) 

1056 unassociatedDiaSources = results.goodSources 

1057 marginalDiaSources = results.badSources 

1058 unassociatedDiaSources["diaObjectId"] = unassociatedDiaSources["diaSourceId"] 

1059 newDiaObjects = convertDataFrameToSdmSchema(self.schema, unassociatedDiaSources, 

1060 tableName="DiaObject", skipIndex=True) 

1061 self.metadata["nRejectedNewDiaObjects"] = len(marginalDiaSources) 

1062 return pipeBase.Struct(diaSources=unassociatedDiaSources, 

1063 newDiaObjects=newDiaObjects, 

1064 nNewDiaObjects=len(newDiaObjects), 

1065 marginalDiaSources=marginalDiaSources) 

1066 

1067 def filterSources(self, sources, snrThreshold=None, lowReliabilitySnrThreshold=None, 

1068 reliabilityThreshold=None, lowSnrReliabilityThreshold=None, badFlags=None): 

1069 """Select good sources out of a catalog. 

1070 

1071 Parameters 

1072 ---------- 

1073 sources : `pandas.DataFrame` 

1074 Set of DiaSources to check. 

1075 snrThreshold : `float`, optional 

1076 The minimum signal to noise diaSource to make a new diaObject. 

1077 Included for unit tests. Uses the task config value if not set. 

1078 lowReliabilitySnrThreshold : `float`, optional 

1079 Use ``lowSnrReliabilityThreshold`` as the reliability threshold for 

1080 diaSources with ``snrThreshold`` < SNR < ``lowReliabilitySnrThreshold`` 

1081 Included for unit tests. Uses the task config value if not set. 

1082 reliabilityThreshold : `float`, optional 

1083 The minimum reliability score diaSource to make a new diaObject 

1084 Included for unit tests. Uses the task config value if not set. 

1085 lowSnrReliabilityThreshold : `float`, optional 

1086 Use ``lowSnrReliabilityThreshold`` as the reliability threshold for 

1087 diaSources with ``snrThreshold`` < SNR < ``lowReliabilitySnrThreshold`` 

1088 Included for unit tests. Uses the task config value if not set. 

1089 badFlags : `list` of `str`, optional 

1090 Do not create new diaObjects for any diaSource with any of these 

1091 flags set. 

1092 Included for unit tests. Uses the task config value if not set. 

1093 

1094 Returns 

1095 ------- 

1096 results : `lsst.pipe.base.Struct` 

1097 Results struct containing: 

1098 

1099 - goodSources : `pandas.DataFrame` 

1100 Subset of the input sources that pass all checks. 

1101 - badSources : `pandas.DataFrame` 

1102 Subset of the input sources that fail any check. 

1103 """ 

1104 if snrThreshold is None: 

1105 snrThreshold = self.config.newObjectSnrThreshold 

1106 if lowReliabilitySnrThreshold is None: 

1107 lowReliabilitySnrThreshold = self.config.newObjectLowReliabilitySnrThreshold 

1108 if reliabilityThreshold is None: 

1109 reliabilityThreshold = self.config.newObjectReliabilityThreshold 

1110 if lowSnrReliabilityThreshold is None: 

1111 lowSnrReliabilityThreshold = self.config.newObjectLowSnrReliabilityThreshold 

1112 if badFlags is None: 

1113 badFlags = self.config.newObjectBadFlags 

1114 flagged = sources[badFlags].fillna(False).any(axis=1) 

1115 fluxField = self.config.newObjectFluxField 

1116 fluxErrField = fluxField + "Err" 

1117 signalToNoise = np.abs(np.array(sources[fluxField]/sources[fluxErrField])) 

1118 reliability = np.array(sources['reliability']) 

1119 nFlagged = np.count_nonzero(flagged) 

1120 if nFlagged > 0: 

1121 self.log.info("Not creating new diaObjects for %i unassociated diaSources due to flags", nFlagged) 

1122 

1123 if snrThreshold > 0: 

1124 snr_flag = signalToNoise < snrThreshold 

1125 self.log.info("Not creating new diaObjects for %i unassociated diaSources due to %sFlux" 

1126 " signal to noise < %f", 

1127 np.sum(snr_flag), fluxField, snrThreshold) 

1128 flagged |= snr_flag 

1129 if reliabilityThreshold > 0: 

1130 reliability_flag = reliability < reliabilityThreshold 

1131 self.log.info("Not creating new diaObjects for %i unassociated diaSources due to " 

1132 "reliability<%f", 

1133 np.sum(reliability_flag), reliabilityThreshold) 

1134 flagged |= reliability_flag 

1135 if min(lowReliabilitySnrThreshold, lowSnrReliabilityThreshold) > 0: 

1136 # Only run the combined test if both thresholds are greater than zero 

1137 lowSnrReliability_flag = ((signalToNoise < lowReliabilitySnrThreshold) 

1138 & (reliability < lowSnrReliabilityThreshold)) 

1139 self.log.info("Not creating new diaObjects for %i unassociated diaSources due to %sFlux" 

1140 " signal to noise < %f combined with reliability< %f", 

1141 np.sum(lowSnrReliability_flag), 

1142 fluxField, 

1143 lowReliabilitySnrThreshold, 

1144 lowSnrReliabilityThreshold) 

1145 flagged |= lowSnrReliability_flag 

1146 

1147 if np.count_nonzero(~flagged) > 0: 1147 ↛ 1150line 1147 didn't jump to line 1150 because the condition on line 1147 was always true

1148 goodSources = sources[~flagged].copy(deep=True) 

1149 else: 

1150 goodSources = make_empty_catalog(self.schema, tableName="DiaSource") 

1151 if np.count_nonzero(flagged) > 0: 

1152 badSources = sources[flagged].copy(deep=True) 

1153 else: 

1154 badSources = make_empty_catalog(self.schema, tableName="DiaSource") 

1155 return pipeBase.Struct(goodSources=goodSources, 

1156 badSources=badSources 

1157 ) 

1158 

1159 @timeMethod 

1160 def associateDiaSources(self, diaSourceTable, solarSystemObjectTable, diffIm, diaObjects): 

1161 """Associate DiaSources with DiaObjects. 

1162 

1163 Associate new DiaSources with existing DiaObjects. Create new 

1164 DiaObjects fron unassociated DiaSources. Index DiaSource catalogue 

1165 after associations. Append new DiaObjects and DiaSources to their 

1166 previous history. Test for DiaSource and DiaObject duplications. 

1167 Compute DiaObject Summary statistics from their full DiaSource 

1168 history. Test for duplication in the updated DiaObjects. 

1169 

1170 Parameters 

1171 ---------- 

1172 diaSourceTable : `pandas.DataFrame` 

1173 Newly detected DiaSources. 

1174 solarSystemObjectTable : `astropy.table.Table` 

1175 Preloaded Solar System objects expected to be visible in the image. 

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

1177 Difference image exposure in which the sources in ``diaSourceCat`` 

1178 were detected. 

1179 diaObjects : `pandas.DataFrame` 

1180 Table of DiaObjects from preloaded DiaObjects. 

1181 

1182 Returns 

1183 ------- 

1184 results : `lsst.pipe.base.Struct` 

1185 Results struct containing: 

1186 

1187 - associatedDiaSources : `pandas.DataFrame` 

1188 Associated DiaSources with DiaObjects. 

1189 - newDiaObjects : `pandas.DataFrame` 

1190 Table of new DiaObjects after association. 

1191 - associatedSsSources : `astropy.table.Table` 

1192 Table of new ssSources after association. 

1193 - unassociatedSsObjects : `astropy.table.Table` 

1194 Table of expected ssSources that were not associated with a 

1195 diaSource. 

1196 - newDiaSources : `pandas.DataFrame` 

1197 Subset of `associatedDiaSources` consisting of only the 

1198 unassociated diaSources that were added as new diaObjects. 

1199 - marginalDiaSources : `pandas.DataFrame` 

1200 Unassociated diaSources with marginal detections, which were 

1201 removed from `associatedDiaSources` and were not added as new 

1202 diaObjects. 

1203 """ 

1204 associatedCatalogs = [] 

1205 # First associate diaSources with known asteroids 

1206 if self.config.doSolarSystemAssociation and solarSystemObjectTable is not None: 

1207 ssoAssocResult = self.solarSystemAssociator.run( 

1208 Table.from_pandas(diaSourceTable), 

1209 solarSystemObjectTable, 

1210 diffIm.visitInfo, 

1211 diffIm.getBBox(), 

1212 diffIm.wcs 

1213 ) 

1214 nTotalSsObjects = ssoAssocResult.nTotalSsObjects 

1215 nAssociatedSsObjects = ssoAssocResult.nAssociatedSsObjects 

1216 associatedSsSources = ssoAssocResult.associatedSsSources 

1217 unassociatedSsObjects = ssoAssocResult.unassociatedSsObjects 

1218 if len(ssoAssocResult.ssoAssocDiaSources) > 0: 1218 ↛ 1219line 1218 didn't jump to line 1219 because the condition on line 1218 was never true

1219 associatedCatalogs.append(ssoAssocResult.ssoAssocDiaSources.to_pandas()) 

1220 if len(ssoAssocResult.unAssocDiaSources) > 0: 1220 ↛ 1223line 1220 didn't jump to line 1223 because the condition on line 1220 was never true

1221 # If the table is empty then converting time fields to pandas 

1222 # will raise an error. Pass in an empty Dataframe in that case. 

1223 unAssocSSDiaSources = ssoAssocResult.unAssocDiaSources.to_pandas() 

1224 else: 

1225 unAssocSSDiaSources = make_empty_catalog(self.schema, tableName="DiaSource") 

1226 else: 

1227 unAssocSSDiaSources = diaSourceTable 

1228 nTotalSsObjects = 0 

1229 nAssociatedSsObjects = 0 

1230 associatedSsSources = None 

1231 unassociatedSsObjects = None 

1232 # Associate new DiaSources with existing DiaObjects. 

1233 assocResults = self.associator.run(unAssocSSDiaSources, diaObjects, schema=self.schema) 

1234 createResults = self.createNewDiaObjects(assocResults.unAssocDiaSources) 

1235 

1236 if not assocResults.matchedDiaSources.empty: 

1237 associatedCatalogs.append(assocResults.matchedDiaSources) 

1238 if not createResults.diaSources.empty: 

1239 associatedCatalogs.append(createResults.diaSources) 

1240 if len(associatedCatalogs) == 0: 

1241 associatedDiaSources = make_empty_catalog(self.schema, tableName="DiaSource") 

1242 else: 

1243 # Standardize each component to the schema before concatinating, so 

1244 # that type mis-matches are fixed as early as possible. 

1245 associatedDiaSources = pd.concat( 

1246 [convertDataFrameToSdmSchema(self.schema, df, tableName="DiaSource", skipIndex=True) 

1247 for df in associatedCatalogs]) 

1248 

1249 self._add_association_meta_data(assocResults.nUpdatedDiaObjects, 

1250 assocResults.nUnassociatedDiaObjects, 

1251 createResults.nNewDiaObjects, 

1252 nTotalSsObjects, 

1253 nAssociatedSsObjects) 

1254 self.log.info("%i updated and %i unassociated diaObjects. Creating %i new diaObjects" 

1255 " and dropping %i marginal diaSources.", 

1256 assocResults.nUpdatedDiaObjects, 

1257 assocResults.nUnassociatedDiaObjects, 

1258 createResults.nNewDiaObjects, 

1259 len(createResults.marginalDiaSources), 

1260 ) 

1261 if createResults.nNewDiaObjects > self.config.maxNewDiaObjects > 0: 

1262 raise TooManyDiaObjectsError(nNewDiaObjects=createResults.nNewDiaObjects, 

1263 threshold=self.config.maxNewDiaObjects) 

1264 return pipeBase.Struct(associatedDiaSources=associatedDiaSources, 

1265 newDiaObjects=createResults.newDiaObjects, 

1266 associatedSsSources=associatedSsSources, 

1267 unassociatedSsObjects=unassociatedSsObjects, 

1268 newDiaSources=createResults.diaSources, 

1269 marginalDiaSources=createResults.marginalDiaSources 

1270 ) 

1271 

1272 def standardizeDataFrame(self, dataFrame, tableName, nullColumns=None): 

1273 """Convert a catalog to SDM schema format with NULL ID values 

1274 

1275 Parameters 

1276 ---------- 

1277 dataFrame : `pandas.DataFrame` 

1278 The catalog to standardize/convert 

1279 tableName : `str` 

1280 Schema name of table to which this dataFrame should be standardized 

1281 nullColumns : `list` of `str`, optional 

1282 List of column names to check for default values of 0 that should be 

1283 replaced with `NULL`. 

1284 

1285 

1286 Returns 

1287 ------- 

1288 standardizedAssociatedDiaSources : pandas.DataFrame 

1289 The standardized DiaSource catalog 

1290 """ 

1291 standardizedDataFrame = convertDataFrameToSdmSchema(self.schema, 

1292 dataFrame, 

1293 tableName=tableName, 

1294 skipIndex=True) 

1295 

1296 def _setNullColumn(dataframe, colName): 

1297 """Set specified columns with default values of 0 to NULL.""" 

1298 dataframe.loc[dataframe[colName] == 0, colName] = pd.NA 

1299 

1300 if nullColumns is not None: 1300 ↛ 1303line 1300 didn't jump to line 1303 because the condition on line 1300 was always true

1301 for colName in nullColumns: 

1302 _setNullColumn(standardizedDataFrame, colName) 

1303 return standardizedDataFrame 

1304 

1305 def standardizeTable(self, table, tableName, nullColumns=None): 

1306 """Convert a catalog to SDM schema format with NULL ID values 

1307 

1308 Parameters 

1309 ---------- 

1310 table : `astropy.table.Table` 

1311 The catalog to standardize/convert 

1312 tableName : `str` 

1313 Schema name of table to which this dataFrame should be standardized 

1314 nullColumns : `list` of `str`, optional 

1315 List of column names to check for default values of 0 that should be 

1316 replaced with `NULL`. 

1317 

1318 

1319 Returns 

1320 ------- 

1321 standardizedAssociatedDiaSources : pandas.DataFrame 

1322 The standardized DiaSource catalog 

1323 """ 

1324 dataFrame = table.to_pandas() 

1325 standardizedDataFrame = self.standardizeDataFrame(dataFrame, tableName, nullColumns=nullColumns) 

1326 return standardizedDataFrame 

1327 

1328 @timeMethod 

1329 def mergeAssociatedCatalogs(self, preloadedDiaSources, associatedDiaSources, diaObjects, newDiaObjects, 

1330 diffIm): 

1331 """Merge the associated diaSource and diaObjects to their previous history. 

1332 

1333 Parameters 

1334 ---------- 

1335 preloadedDiaSources : `pandas.DataFrame` 

1336 Previously detected DiaSources, loaded from the APDB. 

1337 associatedDiaSources : `pandas.DataFrame` 

1338 Associated DiaSources with DiaObjects. 

1339 diaObjects : `pandas.DataFrame` 

1340 Table of DiaObjects from preloaded DiaObjects. 

1341 newDiaObjects : `pandas.DataFrame` 

1342 Table of new DiaObjects after association. 

1343 

1344 Raises 

1345 ------ 

1346 RuntimeError 

1347 Raised if duplicate DiaObjects or duplicate DiaSources are found. 

1348 

1349 Returns 

1350 ------- 

1351 mergedDiaSourceHistory : `pandas.DataFrame` 

1352 The combined catalog, with all of the rows from preloadedDiaSources 

1353 catalog ordered before the rows of associatedDiaSources catalog. 

1354 mergedDiaObjects : `pandas.DataFrame` 

1355 Table of new DiaObjects merged with their history. 

1356 updatedDiaObjectIds : `numpy.Array` 

1357 Object Id's from associated diaSources. 

1358 """ 

1359 # Index the DiaSource catalog for this visit after all associations 

1360 # have been made. 

1361 updatedDiaObjectIds = associatedDiaSources["diaObjectId"][ 

1362 associatedDiaSources["diaObjectId"] != 0].to_numpy() 

1363 associatedDiaSources.set_index(["diaObjectId", 

1364 "band", 

1365 "diaSourceId"], 

1366 drop=False, 

1367 inplace=True) 

1368 

1369 # Append new DiaObjects and DiaSources to their previous history. 

1370 if diaObjects.empty: 1370 ↛ 1371line 1370 didn't jump to line 1371 because the condition on line 1370 was never true

1371 mergedDiaObjects = newDiaObjects.set_index("diaObjectId", drop=False) 

1372 elif not newDiaObjects.empty: 1372 ↛ 1373line 1372 didn't jump to line 1373 because the condition on line 1372 was never true

1373 mergedDiaObjects = pd.concat( 

1374 [diaObjects, 

1375 newDiaObjects.set_index("diaObjectId", drop=False)], 

1376 sort=True) 

1377 else: 

1378 mergedDiaObjects = diaObjects 

1379 

1380 # Exclude any objects that are off the image after association. 

1381 mergedDiaObjects, updatedDiaObjectIds = self.purgeDiaObjects(diffIm.getBBox(), diffIm.getWcs(), 

1382 mergedDiaObjects, 

1383 diaObjectIds=updatedDiaObjectIds, 

1384 buffer=-1) 

1385 if self.testDataFrameIndex(mergedDiaObjects): 1385 ↛ 1386line 1385 didn't jump to line 1386 because the condition on line 1385 was never true

1386 raise RuntimeError( 

1387 "Duplicate DiaObjects created after association. This is " 

1388 "likely due to re-running data with an already populated " 

1389 "Apdb. If this was not the case then there was an unexpected " 

1390 "failure in Association while matching and creating new " 

1391 "DiaObjects and should be reported. Exiting.") 

1392 

1393 mergedDiaSourceHistory = self.mergeCatalogs(preloadedDiaSources, associatedDiaSources, 

1394 tableName="DiaSource") 

1395 

1396 # Test for DiaSource duplication first. If duplicates are found, 

1397 # this likely means this is duplicate data being processed and sent 

1398 # to the Apdb. 

1399 if self.testDataFrameIndex(mergedDiaSourceHistory): 1399 ↛ 1400line 1399 didn't jump to line 1400 because the condition on line 1399 was never true

1400 raise RuntimeError( 

1401 "Duplicate DiaSources found after association and merging " 

1402 "with history. This is likely due to re-running data with an " 

1403 "already populated Apdb. If this was not the case then there " 

1404 "was an unexpected failure in Association while matching " 

1405 "sources to objects, and should be reported. Exiting.") 

1406 # Finally, update the diaObject table with the number of associated diaSources 

1407 mergedUpdatedDiaObjects = self.updateObjectTable(mergedDiaObjects, mergedDiaSourceHistory) 

1408 return (mergedDiaSourceHistory, mergedUpdatedDiaObjects, updatedDiaObjectIds) 

1409 

1410 @timeMethod 

1411 def runForcedMeasurement(self, diaObjects, updatedDiaObjects, exposure, diffIm, idGenerator): 

1412 """Forced Source Measurement 

1413 

1414 Forced photometry on the difference and calibrated exposures using the 

1415 new and updated DiaObject locations. 

1416 

1417 Parameters 

1418 ---------- 

1419 diaObjects : `pandas.DataFrame` 

1420 Catalog of DiaObjects. 

1421 updatedDiaObjects : `pandas.DataFrame` 

1422 Catalog of updated DiaObjects. 

1423 exposure : `lsst.afw.image.ExposureF` 

1424 Calibrated exposure differenced with a template to create 

1425 ``diffIm``. 

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

1427 Difference image exposure in which the sources in ``diaSourceCat`` 

1428 were detected. 

1429 idGenerator : `lsst.meas.base.IdGenerator` 

1430 Object that generates source IDs and random number generator seeds. 

1431 

1432 Returns 

1433 ------- 

1434 diaForcedSources : `pandas.DataFrame` 

1435 Catalog of calibrated forced photometered fluxes on both the 

1436 difference and direct images at DiaObject locations. 

1437 """ 

1438 # Force photometer on the Difference and Calibrated exposures using 

1439 # the new and updated DiaObject locations. 

1440 diaForcedSources = self.diaForcedSource.run( 

1441 diaObjects, 

1442 updatedDiaObjects.loc[:, "diaObjectId"].to_numpy(), 

1443 exposure, 

1444 diffIm, 

1445 idGenerator=idGenerator) 

1446 self.log.info(f"Updating {len(diaForcedSources)} diaForcedSources in the APDB") 

1447 diaForcedSources = convertDataFrameToSdmSchema(self.schema, diaForcedSources, 

1448 tableName="DiaForcedSource", skipIndex=True) 

1449 return diaForcedSources 

1450 

1451 @timeMethod 

1452 def loadRefreshedDiaObjects(self, region, preloadedDiaObjects=None): 

1453 """Load DiaObjects from the Apdb based on their HTM location. 

1454 

1455 Parameters 

1456 ---------- 

1457 region : `sphgeom.Region` 

1458 Region containing the current exposure to load diaObjects from the 

1459 APDB. 

1460 preloadedDiaObjects : `pandas.DataFrame`, optional 

1461 Previously detected DiaObjects, loaded from the APDB. `None` if 

1462 the preloaded catalogs are not available. 

1463 

1464 Returns 

1465 ------- 

1466 diaObjects : `pandas.DataFrame` 

1467 DiaObjects loaded from the Apdb that are within the area defined 

1468 by ``region``. 

1469 """ 

1470 refreshedDiaObjects = loadDiaObjectsFromApdb(self.apdb, self._paddedRegion(region), self.schema, 

1471 self.log) 

1472 if preloadedDiaObjects is None: 

1473 return refreshedDiaObjects 

1474 

1475 refreshedIsInPreloaded = refreshedDiaObjects.index.isin(preloadedDiaObjects.index) 

1476 preloadedIsInRefreshed = preloadedDiaObjects.index.isin(refreshedDiaObjects.index) 

1477 nUniqueRefreshed = (~refreshedIsInPreloaded).sum() 

1478 nUniquePreloaded = (~preloadedIsInRefreshed).sum() 

1479 if nUniqueRefreshed > 0: 1479 ↛ 1480line 1479 didn't jump to line 1480 because the condition on line 1479 was never true

1480 self.log.info("Reloading the diaObject table during association yielded " 

1481 "an additional %d objects over the %d preloaded diaObjects.", 

1482 nUniqueRefreshed, len(preloadedDiaObjects)) 

1483 if nUniquePreloaded == 0: 1483 ↛ 1484line 1483 didn't jump to line 1484 because the condition on line 1483 was never true

1484 return refreshedDiaObjects 

1485 # ap_verify CI datasets ship a preloaded diaObject catalog 

1486 # alongside an empty APDB, so some preloaded objects may not 

1487 # appear in the refresh. Combine the two, giving precedence to 

1488 # refreshed entries on overlap so that updated column values are 

1489 # not silently discarded when the refresh adds no new ids. 

1490 return pd.concat([refreshedDiaObjects, preloadedDiaObjects.loc[~preloadedIsInRefreshed]]) 

1491 

1492 @timeMethod 

1493 def loadRefreshedDiaSources(self, region, diaObjects, visitTime): 

1494 """Reload the DiaSource history from the Apdb. 

1495 

1496 Used only in non-time-critical environments where it is more important 

1497 to load the most recent DiaSources than to save time by preloading 

1498 catalogs. 

1499 

1500 Parameters 

1501 ---------- 

1502 region : `sphgeom.Region` 

1503 Region containing the current exposure to load the history from 

1504 the APDB. 

1505 diaObjects : `pandas.DataFrame` 

1506 DiaObjects to load the history for, indexed by ``diaObjectId``. 

1507 visitTime : `astropy.time.Time` 

1508 Time of the current visit. 

1509 

1510 Returns 

1511 ------- 

1512 diaSources : `pandas.DataFrame` 

1513 DiaSource history loaded from the Apdb, indexed by 

1514 ``diaObjectId``, ``band``, and ``diaSourceId``. 

1515 """ 

1516 return loadDiaSourcesFromApdb(self.apdb, self._paddedRegion(region), 

1517 diaObjects.loc[:, "diaObjectId"], visitTime, self.schema, self.log) 

1518 

1519 @timeMethod 

1520 def loadRefreshedDiaForcedSources(self, region, diaObjects, visitTime): 

1521 """Reload the DiaForcedSource history from the Apdb. 

1522 

1523 Used only in non-time-critical environments where it is more important 

1524 to load the most recent DiaForcedSources than to save time by preloading 

1525 catalogs. 

1526 

1527 Parameters 

1528 ---------- 

1529 region : `sphgeom.Region` 

1530 Region containing the current exposure to load the history from 

1531 the APDB. 

1532 diaObjects : `pandas.DataFrame` 

1533 DiaObjects to load the history for, indexed by ``diaObjectId``. 

1534 visitTime : `astropy.time.Time` 

1535 Time of the current visit. 

1536 

1537 Returns 

1538 ------- 

1539 diaForcedSources : `pandas.DataFrame` 

1540 DiaForcedSource history loaded from the Apdb, indexed by 

1541 ``diaObjectId`` and ``diaForcedSourceId``. 

1542 """ 

1543 return loadDiaForcedSourcesFromApdb(self.apdb, self._paddedRegion(region), 

1544 diaObjects.loc[:, "diaObjectId"], visitTime, self.schema, 

1545 self.log) 

1546 

1547 def _paddedRegion(self, region): 

1548 """Pad a region by the configured margin. 

1549 

1550 Parameters 

1551 ---------- 

1552 region : `sphgeom.Region` 

1553 Region containing the current exposure. 

1554 

1555 Returns 

1556 ------- 

1557 region : `sphgeom.Region` 

1558 The region, expanded by ``config.angleMargin``. 

1559 """ 

1560 return paddedRegion(region, lsst.sphgeom.Angle.fromDegrees(self.config.angleMargin/3600.)) 

1561 

1562 @timeMethod 

1563 def writeToApdb(self, updatedDiaObjects, associatedDiaSources, diaForcedSources): 

1564 """Write to the Alert Production Database (Apdb). 

1565 

1566 Store DiaSources, updated DiaObjects, and DiaForcedSources in the 

1567 Alert Production Database (Apdb). 

1568 

1569 Parameters 

1570 ---------- 

1571 updatedDiaObjects : `pandas.DataFrame` 

1572 Catalog of updated DiaObjects. 

1573 associatedDiaSources : `pandas.DataFrame` 

1574 Associated DiaSources with DiaObjects. 

1575 diaForcedSources : `pandas.DataFrame` 

1576 Catalog of calibrated forced photometered fluxes on both the 

1577 difference and direct images at DiaObject locations. 

1578 

1579 Returns 

1580 ------- 

1581 validityStart : `lsst.daf.base.DateTime` 

1582 Time at which the APDB was updated. 

1583 """ 

1584 # Store DiaSources, updated DiaObjects, and DiaForcedSources in the 

1585 # Apdb. 

1586 # Drop empty columns that are nullable in the APDB. 

1587 diaObjectStore = dropEmptyColumns(self.schema, updatedDiaObjects, tableName="DiaObject") 

1588 diaSourceStore = dropEmptyColumns(self.schema, associatedDiaSources, tableName="DiaSource") 

1589 diaForcedSourceStore = dropEmptyColumns(self.schema, diaForcedSources, tableName="DiaForcedSource") 

1590 

1591 validityStart = DateTime.now() 

1592 self.apdb.store( 

1593 validityStart.toAstropy(), 

1594 diaObjectStore, 

1595 diaSourceStore, 

1596 diaForcedSourceStore) 

1597 self.log.info("APDB updated.") 

1598 

1599 return validityStart 

1600 

1601 def testDataFrameIndex(self, df): 

1602 """Test the sorted DataFrame index for duplicates. 

1603 

1604 Wrapped as a separate function to allow for mocking of the this task 

1605 in unittesting. Default of a mock return for this test is True. 

1606 

1607 Parameters 

1608 ---------- 

1609 df : `pandas.DataFrame` 

1610 DataFrame to text. 

1611 

1612 Returns 

1613 ------- 

1614 `bool` 

1615 True if DataFrame contains duplicate rows. 

1616 """ 

1617 return df.index.has_duplicates 

1618 

1619 def _add_association_meta_data(self, 

1620 nUpdatedDiaObjects, 

1621 nUnassociatedDiaObjects, 

1622 nNewDiaObjects, 

1623 nTotalSsObjects, 

1624 nAssociatedSsObjects): 

1625 """Store summaries of the association step in the task metadata. 

1626 

1627 Parameters 

1628 ---------- 

1629 nUpdatedDiaObjects : `int` 

1630 Number of previous DiaObjects associated and updated in this 

1631 ccdVisit. 

1632 nUnassociatedDiaObjects : `int` 

1633 Number of previous DiaObjects that were not associated or updated 

1634 in this ccdVisit. 

1635 nNewDiaObjects : `int` 

1636 Number of newly created DiaObjects for this ccdVisit. 

1637 nTotalSsObjects : `int` 

1638 Number of SolarSystemObjects within the observable detector 

1639 area. 

1640 nAssociatedSsObjects : `int` 

1641 Number of successfully associated SolarSystemObjects. 

1642 """ 

1643 self.metadata['numUpdatedDiaObjects'] = nUpdatedDiaObjects 

1644 self.metadata['numUnassociatedDiaObjects'] = nUnassociatedDiaObjects 

1645 self.metadata['numNewDiaObjects'] = nNewDiaObjects 

1646 self.metadata['numTotalSolarSystemObjects'] = nTotalSsObjects 

1647 self.metadata['numAssociatedSsObjects'] = nAssociatedSsObjects 

1648 

1649 def purgeDiaObjects(self, bbox, wcs, diaObjCat, diaObjectIds=None, buffer=0): 

1650 """Drop diaObjects that are outside the exposure bounding box. 

1651 

1652 Parameters 

1653 ---------- 

1654 bbox : `lsst.geom.Box2I` 

1655 Bounding box of the exposure. 

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

1657 Coordinate system definition (wcs) for the exposure. 

1658 diaObjCat : `pandas.DataFrame` 

1659 DiaObjects loaded from the Apdb. 

1660 buffer : `int`, optional 

1661 Width, in pixels, to pad the exposure bounding box. 

1662 

1663 Returns 

1664 ------- 

1665 diaObjCat : `pandas.DataFrame` 

1666 DiaObjects loaded from the Apdb, restricted to the exposure 

1667 bounding box. 

1668 """ 

1669 # Copy the bbox so the caller's box is not mutated by grow(). 

1670 bbox = type(bbox)(bbox) 

1671 try: 

1672 bbox.grow(buffer) 

1673 raVals = diaObjCat.ra.to_numpy() 

1674 decVals = diaObjCat.dec.to_numpy() 

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

1676 selector = bbox.contains(xVals, yVals) 

1677 nPurged = np.sum(~selector) 

1678 if nPurged > 0: 

1679 if diaObjectIds is not None: 1679 ↛ 1687line 1679 didn't jump to line 1687 because the condition on line 1679 was always true

1680 # We also need to drop any of the associated IDs if this runs after association 

1681 purgedIds = diaObjCat[~selector].diaObjectId 

1682 diaObjectIds = diaObjectIds[~np.isin(diaObjectIds, purgedIds)] 

1683 self.log.info("Dropped %i diaObjects that were outside the bbox " 

1684 "after association, leaving %i in the catalog", 

1685 nPurged, len(diaObjCat) - nPurged) 

1686 else: 

1687 self.log.info("Dropped %i diaObjects that were outside the padded bbox " 

1688 "before association, leaving %i in the catalog", 

1689 nPurged, len(diaObjCat) - nPurged) 

1690 diaObjCat = diaObjCat[selector].copy() 

1691 except (AttributeError, KeyError, ValueError) as e: 

1692 self.log.warning("Error attempting to check diaObject history: %s", e, exc_info=e) 

1693 return diaObjCat, diaObjectIds 

1694 

1695 def mergeCatalogs(self, originalCatalog, newCatalog, tableName): 

1696 """Combine two catalogs, ensuring that the new catalog conforms to the schema. 

1697 

1698 Parameters 

1699 ---------- 

1700 originalCatalog : `pandas.DataFrame` 

1701 The original catalog to be added to. 

1702 newCatalog : `pandas.DataFrame` 

1703 The new catalog to append to `originalCatalog` 

1704 tableName : `str` 

1705 Name of the table in the schema to use. 

1706 

1707 Returns 

1708 ------- 

1709 mergedCatalog : `pandas.DataFrame` 

1710 The combined catalog, with all of the rows from ``originalCatalog`` 

1711 ordered before the rows of ``newCatalog`` 

1712 """ 

1713 if len(newCatalog) > 0: 

1714 catalog = convertDataFrameToSdmSchema(self.schema, newCatalog, 

1715 tableName=tableName, skipIndex=True) 

1716 

1717 mergedCatalog = pd.concat([originalCatalog, catalog], sort=True) 

1718 else: 

1719 mergedCatalog = pd.concat([originalCatalog], sort=True) 

1720 return mergedCatalog.loc[:, originalCatalog.columns] 

1721 

1722 def updateObjectTable(self, diaObjects, diaSources): 

1723 """Update the diaObject table with the new diaSource records. 

1724 

1725 Parameters 

1726 ---------- 

1727 diaObjects : `pandas.DataFrame` 

1728 Table of new DiaObjects merged with their history. 

1729 diaSources : `pandas.DataFrame` 

1730 The combined preloaded and associated diaSource catalog. 

1731 

1732 Returns 

1733 ------- 

1734 updatedDiaObjects : `pandas.DataFrame` 

1735 Table of DiaObjects updated with the number of associated DiaSources 

1736 """ 

1737 # Group on the index level explicitly since diaObjectId is both an 

1738 # index and a (duplicated) column 

1739 nDiaSources = diaSources.groupby(level="diaObjectId").size().rename("nDiaSources") 

1740 diaObjects = diaObjects.drop(columns="nDiaSources", errors="ignore") 

1741 updatedDiaObjects = diaObjects.join(nDiaSources, how="left") 

1742 return updatedDiaObjects 

1743 

1744 @staticmethod 

1745 def checkTableIndex(dataFrame, index): 

1746 if dataFrame.index.name is None: 

1747 # The expected index may or may not be set, depending on whether 

1748 # the table was written originally as a DataFrame or something else 

1749 # Parquet-friendly. 

1750 dataFrame.set_index(index, drop=False, inplace=True)