Coverage for python/lsst/faro/base/BaseSubTasks.py: 44%
59 statements
« prev ^ index » next coverage.py v6.5.0, created at 2022-10-21 02:49 -0700
« prev ^ index » next coverage.py v6.5.0, created at 2022-10-21 02:49 -0700
1# This file is part of faro.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
22from lsst.afw.table import SourceCatalog
23from lsst.pipe.base import Struct, Task
24from lsst.pex.config import Field, DictField
25from lsst.verify import Measurement
27from lsst.faro.utils.matcher import mergeCatalogs
28from lsst.faro.utils.calibrated_catalog import CalibratedCatalog
29from lsst.faro.base.ConfigBase import MeasurementTaskConfig
30import astropy.units as u
31import numpy as np
32from typing import Dict, List
34__all__ = (
35 "NumSourcesTask",
36 "NumSourcesConfig",
37 "NumSourcesMatchedTask",
38 "NumSourcesMergeTask",
39 "NumpySummaryConfig",
40 "NumpySummaryTask",
41)
44class NumSourcesConfig(MeasurementTaskConfig):
45 doPrimary = Field(
46 doc="Only count sources where detect_isPrimary is True.",
47 dtype=bool,
48 default=False,
49 )
50 columns = DictField(
51 doc="""Columns required for metric calculation. Should be all columns in SourceTable contexts,
52 and columns that do not change name with band in ObjectTable contexts""",
53 keytype=str,
54 itemtype=str,
55 default={"detect_isPrimary": "detect_isPrimary"}
56 )
57 columnsBand = DictField(
58 doc="""Columns required for metric calculation that change with band in ObjectTable contexts""",
59 keytype=str,
60 itemtype=str,
61 default={}
62 )
65class NumSourcesTask(Task):
66 r"""Simple default task to count the number of sources/objects in catalog."""
68 ConfigClass = NumSourcesConfig
69 _DefaultName = "numSourcesTask"
71 def run(self, metricName, catalog, **kwargs):
72 """Run NumSourcesTask
73 Parameters
74 ----------
75 metricName : `str`
76 The name of the metric to measure.
77 catalog : `dict`
78 `lsst.afw.table` Catalog type
79 kwargs
80 Extra keyword arguments used to construct the task.
81 Returns
82 -------
83 measurement : `Struct`
84 The measured value of the metric.
85 """
86 self.log.info("Measuring %s", metricName)
87 if self.config.doPrimary:
88 nSources = np.sum(catalog[self.config._getColumnName("detect_isPrimary")] is True)
89 else:
90 nSources = len(catalog)
91 self.log.info("Number of sources (nSources) = %i" % nSources)
92 meas = Measurement("nsrcMeas", nSources * u.count)
93 return Struct(measurement=meas)
96class NumSourcesMatchedTask(NumSourcesTask):
97 r"""Extension of NumSourcesTask to count sources in a matched catalog"""
99 # The only purpose of this task is to call NumSourcesTask's run method
100 # TODO: Review the necessity of this in DM-31061
101 def run(self, metricName: str, matchedCatalog: SourceCatalog, **kwargs):
102 return super().run(metricName, matchedCatalog, **kwargs)
105class NumSourcesMergeTask(Task):
107 ConfigClass = MeasurementTaskConfig
108 _DefaultName = "numSourcesMergeTask"
110 def run(self, metricName: str, data: Dict[str, List[CalibratedCatalog]]):
111 bands = list(data.keys())
112 if len(bands) != 1:
113 raise RuntimeError(f'NumSourcesMergeTask task got bands: {bands} but expecting exactly one')
114 else:
115 data = data[list(bands)[0]]
116 self.log.info("Measuring %s", metricName)
117 catalog = mergeCatalogs(
118 [x.catalog for x in data],
119 [x.photoCalib for x in data],
120 [x.astromCalib for x in data],
121 )
122 nSources = len(catalog)
123 meas = Measurement("nsrcMeas", nSources * u.count)
124 return Struct(measurement=meas)
127class NumpySummaryConfig(MeasurementTaskConfig):
128 summary = Field(
129 dtype=str, default="median", doc="Aggregation to use for summary metrics"
130 )
133class NumpySummaryTask(Task):
135 ConfigClass = NumpySummaryConfig
136 _DefaultName = "numpySummaryTask"
138 def run(self, measurements, agg_name, package, metric):
139 agg = agg_name.lower()
140 if agg == "summary":
141 agg = self.config.summary
142 self.log.info("Computing the %s of %s_%s values", agg, package, metric)
144 if len(measurements) == 0:
145 self.log.info("Received zero length measurements list. Returning NaN.")
146 # In the case of an empty list, there is nothing we can do other than
147 # to return a NaN
148 value = u.Quantity(np.nan)
149 else:
150 unit = measurements[0].quantity.unit
151 value = getattr(np, agg)(
152 u.Quantity(
153 [x.quantity for x in measurements if np.isfinite(x.quantity)]
154 )
155 )
156 # Make sure return has same unit as inputs
157 # In some cases numpy can return a NaN and the unit gets dropped
158 value = value.value * unit
159 return Struct(
160 measurement=Measurement(
161 f"metricvalue_{agg_name.lower()}_{package}_{metric}", value
162 )
163 )