Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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/>. 

21 

22from lsst.afw.table import SourceCatalog 

23from lsst.pipe.base import Struct, Task 

24from lsst.pex.config import Config, Field 

25from lsst.verify import Measurement 

26 

27from lsst.faro.utils.matcher import mergeCatalogs 

28from lsst.faro.utils.calibrated_catalog import CalibratedCatalog 

29 

30import astropy.units as u 

31import numpy as np 

32from typing import Dict, List 

33 

34__all__ = ( 

35 "NumSourcesTask", 

36 "NumSourcesMatchedTask", 

37 "NumSourcesMergeTask", 

38 "NumpySummaryConfig", 

39 "NumpySummaryTask", 

40) 

41 

42 

43class NumSourcesConfig(Config): 

44 doPrimary = Field( 

45 doc="Only count sources where detect_isPrimary is True.", 

46 dtype=bool, 

47 default=False, 

48 ) 

49 

50 

51class NumSourcesTask(Task): 

52 r"""Simple default task to count the number of sources/objects in catalog.""" 

53 

54 ConfigClass = NumSourcesConfig 

55 _DefaultName = "numSourcesTask" 

56 

57 def run(self, metricName, catalog, **kwargs): 

58 """Run NumSourcesTask 

59 

60 Parameters 

61 ---------- 

62 metricName : `str` 

63 The name of the metric to measure. 

64 catalog : `dict` 

65 `lsst.afw.table` Catalog type 

66 kwargs 

67 Extra keyword arguments used to construct the task. 

68 

69 Returns 

70 ------- 

71 measurement : `Struct` 

72 The measured value of the metric. 

73 """ 

74 self.log.info("Measuring %s", metricName) 

75 if self.config.doPrimary: 

76 nSources = np.sum(catalog["detect_isPrimary"] is True) 

77 else: 

78 nSources = len(catalog) 

79 self.log.info("Number of sources (nSources) = %i" % nSources) 

80 meas = Measurement("nsrcMeas", nSources * u.count) 

81 return Struct(measurement=meas) 

82 

83 

84class NumSourcesMatchedTask(NumSourcesTask): 

85 r"""Extension of NumSourcesTask to count sources in a matched catalog""" 

86 

87 # The only purpose of this task is to call NumSourcesTask's run method 

88 # TODO: Review the necessity of this in DM-31061 

89 def run(self, metricName: str, matchedCatalog: SourceCatalog, **kwargs): 

90 return super().run(metricName, matchedCatalog, **kwargs) 

91 

92 

93class NumSourcesMergeTask(Task): 

94 

95 ConfigClass = Config 

96 _DefaultName = "numSourcesMergeTask" 

97 

98 def run(self, metricName: str, data: Dict[str, List[CalibratedCatalog]]): 

99 bands = list(data.keys()) 

100 if len(bands) != 1: 

101 raise RuntimeError(f'NumSourcesMergeTask task got bands: {bands} but expecting exactly one') 

102 else: 

103 data = data[list(bands)[0]] 

104 self.log.info("Measuring %s", metricName) 

105 catalog = mergeCatalogs( 

106 [x.catalog for x in data], 

107 [x.photoCalib for x in data], 

108 [x.astromCalib for x in data], 

109 ) 

110 nSources = len(catalog) 

111 meas = Measurement("nsrcMeas", nSources * u.count) 

112 return Struct(measurement=meas) 

113 

114 

115class NumpySummaryConfig(Config): 

116 summary = Field( 

117 dtype=str, default="median", doc="Aggregation to use for summary metrics" 

118 ) 

119 

120 

121class NumpySummaryTask(Task): 

122 

123 ConfigClass = NumpySummaryConfig 

124 _DefaultName = "numpySummaryTask" 

125 

126 def run(self, measurements, agg_name, package, metric): 

127 agg = agg_name.lower() 

128 if agg == "summary": 

129 agg = self.config.summary 

130 self.log.info("Computing the %s of %s_%s values", agg, package, metric) 

131 

132 if len(measurements) == 0: 

133 self.log.info("Received zero length measurements list. Returning NaN.") 

134 # In the case of an empty list, there is nothing we can do other than 

135 # to return a NaN 

136 value = u.Quantity(np.nan) 

137 else: 

138 unit = measurements[0].quantity.unit 

139 value = getattr(np, agg)( 

140 u.Quantity( 

141 [x.quantity for x in measurements if np.isfinite(x.quantity)] 

142 ) 

143 ) 

144 # Make sure return has same unit as inputs 

145 # In some cases numpy can return a NaN and the unit gets dropped 

146 value = value.value * unit 

147 return Struct( 

148 measurement=Measurement( 

149 f"metricvalue_{agg_name.lower()}_{package}_{metric}", value 

150 ) 

151 )