Coverage for python/lsst/ap/association/diaPipe.py: 28%
159 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-12 14:12 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-12 14:12 +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#
23"""PipelineTask for associating DiaSources with previous DiaObjects.
25Additionally performs forced photometry on the calibrated and difference
26images at the updated locations of DiaObjects.
28Currently loads directly from the Apdb rather than pre-loading.
29"""
31__all__ = ("DiaPipelineConfig",
32 "DiaPipelineTask",
33 "DiaPipelineConnections")
35import numpy as np
36import pandas as pd
38from lsst.daf.base import DateTime
39import lsst.dax.apdb as daxApdb
40from lsst.meas.base import DetectorVisitIdGeneratorConfig, DiaObjectCalculationTask
41import lsst.pex.config as pexConfig
42import lsst.pipe.base as pipeBase
43import lsst.pipe.base.connectionTypes as connTypes
44from lsst.utils.timer import timeMethod
46from lsst.ap.association import (
47 AssociationTask,
48 DiaForcedSourceTask,
49 LoadDiaCatalogsTask,
50 PackageAlertsTask)
51from lsst.ap.association.ssoAssociation import SolarSystemAssociationTask
54class DiaPipelineConnections(
55 pipeBase.PipelineTaskConnections,
56 dimensions=("instrument", "visit", "detector"),
57 defaultTemplates={"coaddName": "deep", "fakesType": ""}):
58 """Butler connections for DiaPipelineTask.
59 """
60 diaSourceTable = connTypes.Input(
61 doc="Catalog of calibrated DiaSources.",
62 name="{fakesType}{coaddName}Diff_diaSrcTable",
63 storageClass="DataFrame",
64 dimensions=("instrument", "visit", "detector"),
65 )
66 solarSystemObjectTable = connTypes.Input(
67 doc="Catalog of SolarSolarSystem objects expected to be observable in "
68 "this detectorVisit.",
69 name="visitSsObjects",
70 storageClass="DataFrame",
71 dimensions=("instrument", "visit"),
72 )
73 diffIm = connTypes.Input(
74 doc="Difference image on which the DiaSources were detected.",
75 name="{fakesType}{coaddName}Diff_differenceExp",
76 storageClass="ExposureF",
77 dimensions=("instrument", "visit", "detector"),
78 )
79 exposure = connTypes.Input(
80 doc="Calibrated exposure differenced with a template image during "
81 "image differencing.",
82 name="{fakesType}calexp",
83 storageClass="ExposureF",
84 dimensions=("instrument", "visit", "detector"),
85 )
86 template = connTypes.Input(
87 doc="Warped template used to create `subtractedExposure`. Not PSF "
88 "matched.",
89 dimensions=("instrument", "visit", "detector"),
90 storageClass="ExposureF",
91 name="{fakesType}{coaddName}Diff_templateExp",
92 )
93 apdbMarker = connTypes.Output(
94 doc="Marker dataset storing the configuration of the Apdb for each "
95 "visit/detector. Used to signal the completion of the pipeline.",
96 name="apdb_marker",
97 storageClass="Config",
98 dimensions=("instrument", "visit", "detector"),
99 )
100 associatedDiaSources = connTypes.Output(
101 doc="Optional output storing the DiaSource catalog after matching, "
102 "calibration, and standardization for insertion into the Apdb.",
103 name="{fakesType}{coaddName}Diff_assocDiaSrc",
104 storageClass="DataFrame",
105 dimensions=("instrument", "visit", "detector"),
106 )
107 diaForcedSources = connTypes.Output(
108 doc="Optional output storing the forced sources computed at the diaObject positions.",
109 name="{fakesType}{coaddName}Diff_diaForcedSrc",
110 storageClass="DataFrame",
111 dimensions=("instrument", "visit", "detector"),
112 )
113 diaObjects = connTypes.Output(
114 doc="Optional output storing the updated diaObjects associated to these sources.",
115 name="{fakesType}{coaddName}Diff_diaObject",
116 storageClass="DataFrame",
117 dimensions=("instrument", "visit", "detector"),
118 )
119 longTrailedSources = pipeBase.connectionTypes.Output(
120 doc="Optional output temporarily storing long trailed diaSources.",
121 dimensions=("instrument", "visit", "detector"),
122 storageClass="DataFrame",
123 name="{fakesType}{coaddName}Diff_longTrailedSrc",
124 )
126 def __init__(self, *, config=None):
127 super().__init__(config=config)
129 if not config.doWriteAssociatedSources:
130 self.outputs.remove("associatedDiaSources")
131 self.outputs.remove("diaForcedSources")
132 self.outputs.remove("diaObjects")
133 if not config.doSolarSystemAssociation:
134 self.inputs.remove("solarSystemObjectTable")
135 if not config.associator.doTrailedSourceFilter:
136 self.outputs.remove("longTrailedSources")
138 def adjustQuantum(self, inputs, outputs, label, dataId):
139 """Override to make adjustments to `lsst.daf.butler.DatasetRef` objects
140 in the `lsst.daf.butler.core.Quantum` during the graph generation stage
141 of the activator.
143 This implementation checks to make sure that the filters in the dataset
144 are compatible with AP processing as set by the Apdb/DPDD schema.
146 Parameters
147 ----------
148 inputs : `dict`
149 Dictionary whose keys are an input (regular or prerequisite)
150 connection name and whose values are a tuple of the connection
151 instance and a collection of associated `DatasetRef` objects.
152 The exact type of the nested collections is unspecified; it can be
153 assumed to be multi-pass iterable and support `len` and ``in``, but
154 it should not be mutated in place. In contrast, the outer
155 dictionaries are guaranteed to be temporary copies that are true
156 `dict` instances, and hence may be modified and even returned; this
157 is especially useful for delegating to `super` (see notes below).
158 outputs : `dict`
159 Dict of output datasets, with the same structure as ``inputs``.
160 label : `str`
161 Label for this task in the pipeline (should be used in all
162 diagnostic messages).
163 data_id : `lsst.daf.butler.DataCoordinate`
164 Data ID for this quantum in the pipeline (should be used in all
165 diagnostic messages).
167 Returns
168 -------
169 adjusted_inputs : `dict`
170 Dict of the same form as ``inputs`` with updated containers of
171 input `DatasetRef` objects. Connections that are not changed
172 should not be returned at all. Datasets may only be removed, not
173 added. Nested collections may be of any multi-pass iterable type,
174 and the order of iteration will set the order of iteration within
175 `PipelineTask.runQuantum`.
176 adjusted_outputs : `dict`
177 Dict of updated output datasets, with the same structure and
178 interpretation as ``adjusted_inputs``.
180 Raises
181 ------
182 ScalarError
183 Raised if any `Input` or `PrerequisiteInput` connection has
184 ``multiple`` set to `False`, but multiple datasets.
185 NoWorkFound
186 Raised to indicate that this quantum should not be run; not enough
187 datasets were found for a regular `Input` connection, and the
188 quantum should be pruned or skipped.
189 FileNotFoundError
190 Raised to cause QuantumGraph generation to fail (with the message
191 included in this exception); not enough datasets were found for a
192 `PrerequisiteInput` connection.
193 """
194 _, refs = inputs["diffIm"]
195 for ref in refs:
196 if ref.dataId["band"] not in self.config.validBands:
197 raise ValueError(
198 f"Requested '{ref.dataId['band']}' not in "
199 "DiaPipelineConfig.validBands. To process bands not in "
200 "the standard Rubin set (ugrizy) you must add the band to "
201 "the validBands list in DiaPipelineConfig and add the "
202 "appropriate columns to the Apdb schema.")
203 return super().adjustQuantum(inputs, outputs, label, dataId)
206class DiaPipelineConfig(pipeBase.PipelineTaskConfig,
207 pipelineConnections=DiaPipelineConnections):
208 """Config for DiaPipelineTask.
209 """
210 coaddName = pexConfig.Field(
211 doc="coadd name: typically one of deep, goodSeeing, or dcr",
212 dtype=str,
213 default="deep",
214 )
215 apdb = daxApdb.ApdbSql.makeField(
216 doc="Database connection for storing associated DiaSources and "
217 "DiaObjects. Must already be initialized.",
218 )
219 validBands = pexConfig.ListField(
220 dtype=str,
221 default=["u", "g", "r", "i", "z", "y"],
222 doc="List of bands that are valid for AP processing. To process a "
223 "band not on this list, the appropriate band specific columns "
224 "must be added to the Apdb schema in dax_apdb.",
225 )
226 diaCatalogLoader = pexConfig.ConfigurableField(
227 target=LoadDiaCatalogsTask,
228 doc="Task to load DiaObjects and DiaSources from the Apdb.",
229 )
230 associator = pexConfig.ConfigurableField(
231 target=AssociationTask,
232 doc="Task used to associate DiaSources with DiaObjects.",
233 )
234 doSolarSystemAssociation = pexConfig.Field(
235 dtype=bool,
236 default=False,
237 doc="Process SolarSystem objects through the pipeline.",
238 )
239 solarSystemAssociator = pexConfig.ConfigurableField(
240 target=SolarSystemAssociationTask,
241 doc="Task used to associate DiaSources with SolarSystemObjects.",
242 )
243 diaCalculation = pexConfig.ConfigurableField(
244 target=DiaObjectCalculationTask,
245 doc="Task to compute summary statistics for DiaObjects.",
246 )
247 diaForcedSource = pexConfig.ConfigurableField(
248 target=DiaForcedSourceTask,
249 doc="Task used for force photometer DiaObject locations in direct and "
250 "difference images.",
251 )
252 alertPackager = pexConfig.ConfigurableField(
253 target=PackageAlertsTask,
254 doc="Subtask for packaging Ap data into alerts.",
255 )
256 doPackageAlerts = pexConfig.Field(
257 dtype=bool,
258 default=False,
259 doc="Package Dia-data into serialized alerts for distribution and "
260 "write them to disk.",
261 )
262 doWriteAssociatedSources = pexConfig.Field(
263 dtype=bool,
264 default=False,
265 doc="Write out associated DiaSources, DiaForcedSources, and DiaObjects, "
266 "formatted following the Science Data Model.",
267 )
268 imagePixelMargin = pexConfig.RangeField(
269 dtype=int,
270 default=10,
271 min=0,
272 doc="Pad the image by this many pixels before removing off-image "
273 "diaObjects for association.",
274 )
275 idGenerator = DetectorVisitIdGeneratorConfig.make_field()
277 def setDefaults(self):
278 self.apdb.dia_object_index = "baseline"
279 self.apdb.dia_object_columns = []
280 self.diaCalculation.plugins = ["ap_meanPosition",
281 "ap_nDiaSources",
282 "ap_diaObjectFlag",
283 "ap_meanFlux",
284 "ap_percentileFlux",
285 "ap_sigmaFlux",
286 "ap_chi2Flux",
287 "ap_madFlux",
288 "ap_skewFlux",
289 "ap_minMaxFlux",
290 "ap_maxSlopeFlux",
291 "ap_meanErrFlux",
292 "ap_linearFit",
293 "ap_stetsonJ",
294 "ap_meanTotFlux",
295 "ap_sigmaTotFlux"]
298class DiaPipelineTask(pipeBase.PipelineTask):
299 """Task for loading, associating and storing Difference Image Analysis
300 (DIA) Objects and Sources.
301 """
302 ConfigClass = DiaPipelineConfig
303 _DefaultName = "diaPipe"
305 def __init__(self, initInputs=None, **kwargs):
306 super().__init__(**kwargs)
307 self.apdb = self.config.apdb.apply()
308 self.makeSubtask("diaCatalogLoader")
309 self.makeSubtask("associator")
310 self.makeSubtask("diaCalculation")
311 self.makeSubtask("diaForcedSource")
312 if self.config.doPackageAlerts:
313 self.makeSubtask("alertPackager")
314 if self.config.doSolarSystemAssociation:
315 self.makeSubtask("solarSystemAssociator")
317 def runQuantum(self, butlerQC, inputRefs, outputRefs):
318 inputs = butlerQC.get(inputRefs)
319 inputs["idGenerator"] = self.config.idGenerator.apply(butlerQC.quantum.dataId)
320 # Need to set ccdExposureIdBits (now deprecated) to None and pass it,
321 # since there are non-optional positional arguments after it.
322 inputs["ccdExposureIdBits"] = None
323 inputs["band"] = butlerQC.quantum.dataId["band"]
324 if not self.config.doSolarSystemAssociation:
325 inputs["solarSystemObjectTable"] = None
327 outputs = self.run(**inputs)
329 butlerQC.put(outputs, outputRefs)
331 @timeMethod
332 def run(self,
333 diaSourceTable,
334 solarSystemObjectTable,
335 diffIm,
336 exposure,
337 template,
338 ccdExposureIdBits, # TODO: remove on DM-38687.
339 band,
340 idGenerator=None):
341 """Process DiaSources and DiaObjects.
343 Load previous DiaObjects and their DiaSource history. Calibrate the
344 values in the diaSourceCat. Associate new DiaSources with previous
345 DiaObjects. Run forced photometry at the updated DiaObject locations.
346 Store the results in the Alert Production Database (Apdb).
348 Parameters
349 ----------
350 diaSourceTable : `pandas.DataFrame`
351 Newly detected DiaSources.
352 diffIm : `lsst.afw.image.ExposureF`
353 Difference image exposure in which the sources in ``diaSourceCat``
354 were detected.
355 exposure : `lsst.afw.image.ExposureF`
356 Calibrated exposure differenced with a template to create
357 ``diffIm``.
358 template : `lsst.afw.image.ExposureF`
359 Template exposure used to create diffIm.
360 ccdExposureIdBits : `int`
361 Number of bits used for a unique ``ccdVisitId``. Deprecated in
362 favor of ``idGenerator``, and ignored if that is present (will be
363 removed after v26). Pass `None` explicitly to avoid a deprecation
364 warning (a default is impossible given that later positional
365 arguments are not defaulted).
366 band : `str`
367 The band in which the new DiaSources were detected.
368 idGenerator : `lsst.meas.base.IdGenerator`, optional
369 Object that generates source IDs and random number generator seeds.
370 Will be required after ``ccdExposureIdBits`` is removed.
372 Returns
373 -------
374 results : `lsst.pipe.base.Struct`
375 Results struct with components.
377 - ``apdbMaker`` : Marker dataset to store in the Butler indicating
378 that this ccdVisit has completed successfully.
379 (`lsst.dax.apdb.ApdbConfig`)
380 - ``associatedDiaSources`` : Catalog of newly associated
381 DiaSources. (`pandas.DataFrame`)
382 """
383 # Load the DiaObjects and DiaSource history.
384 loaderResult = self.diaCatalogLoader.run(diffIm, self.apdb)
385 if len(loaderResult.diaObjects) > 0:
386 diaObjects = self.purgeDiaObjects(diffIm.getBBox(), diffIm.getWcs(), loaderResult.diaObjects,
387 buffer=self.config.imagePixelMargin)
388 else:
389 diaObjects = loaderResult.diaObjects
391 # Associate new DiaSources with existing DiaObjects.
392 assocResults = self.associator.run(diaSourceTable, diaObjects,
393 exposure_time=diffIm.visitInfo.exposureTime)
395 if self.config.doSolarSystemAssociation:
396 ssoAssocResult = self.solarSystemAssociator.run(
397 assocResults.unAssocDiaSources,
398 solarSystemObjectTable,
399 diffIm)
400 createResults = self.createNewDiaObjects(
401 ssoAssocResult.unAssocDiaSources)
402 associatedDiaSources = pd.concat(
403 [assocResults.matchedDiaSources,
404 ssoAssocResult.ssoAssocDiaSources,
405 createResults.diaSources])
406 nTotalSsObjects = ssoAssocResult.nTotalSsObjects
407 nAssociatedSsObjects = ssoAssocResult.nAssociatedSsObjects
408 else:
409 createResults = self.createNewDiaObjects(
410 assocResults.unAssocDiaSources)
411 associatedDiaSources = pd.concat(
412 [assocResults.matchedDiaSources,
413 createResults.diaSources])
414 nTotalSsObjects = 0
415 nAssociatedSsObjects = 0
417 # Create new DiaObjects from unassociated diaSources.
418 self._add_association_meta_data(assocResults.nUpdatedDiaObjects,
419 assocResults.nUnassociatedDiaObjects,
420 createResults.nNewDiaObjects,
421 nTotalSsObjects,
422 nAssociatedSsObjects)
423 # Index the DiaSource catalog for this visit after all associations
424 # have been made.
425 updatedDiaObjectIds = associatedDiaSources["diaObjectId"][
426 associatedDiaSources["diaObjectId"] != 0].to_numpy()
427 associatedDiaSources.set_index(["diaObjectId",
428 "band",
429 "diaSourceId"],
430 drop=False,
431 inplace=True)
433 # Append new DiaObjects and DiaSources to their previous history.
434 diaObjects = pd.concat(
435 [diaObjects,
436 createResults.newDiaObjects.set_index("diaObjectId", drop=False)],
437 sort=True)
438 if self.testDataFrameIndex(diaObjects):
439 raise RuntimeError(
440 "Duplicate DiaObjects created after association. This is "
441 "likely due to re-running data with an already populated "
442 "Apdb. If this was not the case then there was an unexpected "
443 "failure in Association while matching and creating new "
444 "DiaObjects and should be reported. Exiting.")
445 mergedDiaSourceHistory = pd.concat(
446 [loaderResult.diaSources, associatedDiaSources],
447 sort=True)
448 # Test for DiaSource duplication first. If duplicates are found,
449 # this likely means this is duplicate data being processed and sent
450 # to the Apdb.
451 if self.testDataFrameIndex(mergedDiaSourceHistory):
452 raise RuntimeError(
453 "Duplicate DiaSources found after association and merging "
454 "with history. This is likely due to re-running data with an "
455 "already populated Apdb. If this was not the case then there "
456 "was an unexpected failure in Association while matching "
457 "sources to objects, and should be reported. Exiting.")
459 # Compute DiaObject Summary statistics from their full DiaSource
460 # history.
461 diaCalResult = self.diaCalculation.run(
462 diaObjects,
463 mergedDiaSourceHistory,
464 updatedDiaObjectIds,
465 [band])
466 # Test for duplication in the updated DiaObjects.
467 if self.testDataFrameIndex(diaCalResult.diaObjectCat):
468 raise RuntimeError(
469 "Duplicate DiaObjects (loaded + updated) created after "
470 "DiaCalculation. This is unexpected behavior and should be "
471 "reported. Exiting.")
472 if self.testDataFrameIndex(diaCalResult.updatedDiaObjects):
473 raise RuntimeError(
474 "Duplicate DiaObjects (updated) created after "
475 "DiaCalculation. This is unexpected behavior and should be "
476 "reported. Exiting.")
478 # Force photometer on the Difference and Calibrated exposures using
479 # the new and updated DiaObject locations.
480 diaForcedSources = self.diaForcedSource.run(
481 diaCalResult.diaObjectCat,
482 diaCalResult.updatedDiaObjects.loc[:, "diaObjectId"].to_numpy(),
483 # Passing a ccdExposureIdBits here that isn't None will make
484 # diaForcedSource emit a deprecation warning, so we don't have to
485 # emit our own.
486 ccdExposureIdBits,
487 exposure,
488 diffIm,
489 idGenerator=idGenerator)
491 # Store DiaSources, updated DiaObjects, and DiaForcedSources in the
492 # Apdb.
493 self.apdb.store(
494 DateTime.now(),
495 diaCalResult.updatedDiaObjects,
496 associatedDiaSources,
497 diaForcedSources)
499 if self.config.doPackageAlerts:
500 if len(loaderResult.diaForcedSources) > 1:
501 diaForcedSources = pd.concat(
502 [diaForcedSources, loaderResult.diaForcedSources],
503 sort=True)
504 if self.testDataFrameIndex(diaForcedSources):
505 self.log.warning(
506 "Duplicate DiaForcedSources created after merge with "
507 "history and new sources. This may cause downstream "
508 "problems. Dropping duplicates.")
509 # Drop duplicates via index and keep the first appearance.
510 # Reset due to the index shape being slight different than
511 # expected.
512 diaForcedSources = diaForcedSources.groupby(
513 diaForcedSources.index).first()
514 diaForcedSources.reset_index(drop=True, inplace=True)
515 diaForcedSources.set_index(
516 ["diaObjectId", "diaForcedSourceId"],
517 drop=False,
518 inplace=True)
519 self.alertPackager.run(associatedDiaSources,
520 diaCalResult.diaObjectCat,
521 loaderResult.diaSources,
522 diaForcedSources,
523 diffIm,
524 template)
526 return pipeBase.Struct(apdbMarker=self.config.apdb.value,
527 associatedDiaSources=associatedDiaSources,
528 diaForcedSources=diaForcedSources,
529 diaObjects=diaObjects,
530 longTrailedSources=assocResults.longTrailedSources
531 )
533 def createNewDiaObjects(self, unAssocDiaSources):
534 """Loop through the set of DiaSources and create new DiaObjects
535 for unassociated DiaSources.
537 Parameters
538 ----------
539 unAssocDiaSources : `pandas.DataFrame`
540 Set of DiaSources to create new DiaObjects from.
542 Returns
543 -------
544 results : `lsst.pipe.base.Struct`
545 Results struct containing:
547 - ``diaSources`` : DiaSource catalog with updated DiaObject ids.
548 (`pandas.DataFrame`)
549 - ``newDiaObjects`` : Newly created DiaObjects from the
550 unassociated DiaSources. (`pandas.DataFrame`)
551 - ``nNewDiaObjects`` : Number of newly created diaObjects.(`int`)
552 """
553 if len(unAssocDiaSources) == 0:
554 tmpObj = self._initialize_dia_object(0)
555 newDiaObjects = pd.DataFrame(data=[],
556 columns=tmpObj.keys())
557 else:
558 newDiaObjects = unAssocDiaSources["diaSourceId"].apply(
559 self._initialize_dia_object)
560 unAssocDiaSources["diaObjectId"] = unAssocDiaSources["diaSourceId"]
561 return pipeBase.Struct(diaSources=unAssocDiaSources,
562 newDiaObjects=newDiaObjects,
563 nNewDiaObjects=len(newDiaObjects))
565 def _initialize_dia_object(self, objId):
566 """Create a new DiaObject with values required to be initialized by the
567 Ppdb.
569 Parameters
570 ----------
571 objid : `int`
572 ``diaObjectId`` value for the of the new DiaObject.
574 Returns
575 -------
576 diaObject : `dict`
577 Newly created DiaObject with keys:
579 ``diaObjectId``
580 Unique DiaObjectId (`int`).
581 ``pmParallaxNdata``
582 Number of data points used for parallax calculation (`int`).
583 ``nearbyObj1``
584 Id of the a nearbyObject in the Object table (`int`).
585 ``nearbyObj2``
586 Id of the a nearbyObject in the Object table (`int`).
587 ``nearbyObj3``
588 Id of the a nearbyObject in the Object table (`int`).
589 ``?_psfFluxNdata``
590 Number of data points used to calculate point source flux
591 summary statistics in each bandpass (`int`).
592 """
593 new_dia_object = {"diaObjectId": objId,
594 "pmParallaxNdata": 0,
595 "nearbyObj1": 0,
596 "nearbyObj2": 0,
597 "nearbyObj3": 0,
598 "flags": 0}
599 for f in ["u", "g", "r", "i", "z", "y"]:
600 new_dia_object["%s_psfFluxNdata" % f] = 0
601 return pd.Series(data=new_dia_object)
603 def testDataFrameIndex(self, df):
604 """Test the sorted DataFrame index for duplicates.
606 Wrapped as a separate function to allow for mocking of the this task
607 in unittesting. Default of a mock return for this test is True.
609 Parameters
610 ----------
611 df : `pandas.DataFrame`
612 DataFrame to text.
614 Returns
615 -------
616 `bool`
617 True if DataFrame contains duplicate rows.
618 """
619 return df.index.has_duplicates
621 def _add_association_meta_data(self,
622 nUpdatedDiaObjects,
623 nUnassociatedDiaObjects,
624 nNewDiaObjects,
625 nTotalSsObjects,
626 nAssociatedSsObjects):
627 """Store summaries of the association step in the task metadata.
629 Parameters
630 ----------
631 nUpdatedDiaObjects : `int`
632 Number of previous DiaObjects associated and updated in this
633 ccdVisit.
634 nUnassociatedDiaObjects : `int`
635 Number of previous DiaObjects that were not associated or updated
636 in this ccdVisit.
637 nNewDiaObjects : `int`
638 Number of newly created DiaObjects for this ccdVisit.
639 nTotalSsObjects : `int`
640 Number of SolarSystemObjects within the observable detector
641 area.
642 nAssociatedSsObjects : `int`
643 Number of successfully associated SolarSystemObjects.
644 """
645 self.metadata.add('numUpdatedDiaObjects', nUpdatedDiaObjects)
646 self.metadata.add('numUnassociatedDiaObjects', nUnassociatedDiaObjects)
647 self.metadata.add('numNewDiaObjects', nNewDiaObjects)
648 self.metadata.add('numTotalSolarSystemObjects', nTotalSsObjects)
649 self.metadata.add('numAssociatedSsObjects', nAssociatedSsObjects)
651 def purgeDiaObjects(self, bbox, wcs, diaObjCat, buffer=0):
652 """Drop diaObjects that are outside the exposure bounding box.
654 Parameters
655 ----------
656 bbox : `lsst.geom.Box2I`
657 Bounding box of the exposure.
658 wcs : `lsst.afw.geom.SkyWcs`
659 Coordinate system definition (wcs) for the exposure.
660 diaObjCat : `pandas.DataFrame`
661 DiaObjects loaded from the Apdb.
662 buffer : `int`, optional
663 Width, in pixels, to pad the exposure bounding box.
665 Returns
666 -------
667 diaObjCat : `pandas.DataFrame`
668 DiaObjects loaded from the Apdb, restricted to the exposure
669 bounding box.
670 """
671 try:
672 bbox.grow(buffer)
673 raVals = diaObjCat.ra.to_numpy()
674 decVals = diaObjCat.dec.to_numpy()
675 xVals, yVals = wcs.skyToPixelArray(raVals, decVals, degrees=True)
676 selector = bbox.contains(xVals, yVals)
677 nPurged = np.sum(~selector)
678 if nPurged > 0:
679 diaObjCat = diaObjCat[selector].copy()
680 self.log.info(f"Dropped {nPurged} diaObjects that were outside the bbox "
681 f"leaving {len(diaObjCat)} in the catalog")
682 except Exception as e:
683 self.log.warning("Error attempting to check diaObject history: %s", e)
684 return diaObjCat