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

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

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

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

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

12# (at your option) any later version. 

13# 

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

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

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

17# GNU General Public License for more details. 

18# 

19# You should have received a copy of the GNU General Public License 

20# along with this program. If not, see <https://www.gnu.org/licenses/>. 

21 

22__all__ = ["ApdbMetricTask", "ApdbMetricConfig", "ConfigApdbLoader", 

23 "DirectApdbLoader", "ApdbMetricConnections"] 

24 

25import abc 

26import traceback 

27 

28from lsst.pex.config import Config, ConfigurableField, ConfigurableInstance, \ 

29 ConfigDictField, ConfigChoiceField, FieldValidationError 

30from lsst.pipe.base import Task, Struct, connectionTypes 

31from lsst.dax.apdb import Apdb, ApdbConfig 

32 

33from lsst.verify.tasks import MetricTask, MetricConfig, MetricConnections, \ 

34 MetricComputationError 

35 

36 

37class ConfigApdbLoader(Task): 

38 """A Task that takes a science task config and returns the corresponding 

39 Apdb object. 

40 

41 Parameters 

42 ---------- 

43 *args 

44 **kwargs 

45 Constructor parameters are the same as for `lsst.pipe.base.Task`. 

46 """ 

47 _DefaultName = "configApdb" 

48 ConfigClass = Config 

49 

50 def __init__(self, **kwargs): 

51 super().__init__(**kwargs) 

52 

53 def _getApdb(self, config): 

54 """Extract an Apdb object from an arbitrary task config. 

55 

56 Parameters 

57 ---------- 

58 config : `lsst.pex.config.Config` or `None` 

59 A config that may contain a `lsst.dax.apdb.ApdbConfig`. 

60 Behavior is undefined if there is more than one such member. 

61 

62 Returns 

63 ------- 

64 apdb : `lsst.dax.apdb.Apdb`-like or `None` 

65 A `lsst.dax.apdb.Apdb` object or a drop-in replacement, or `None` 

66 if no `lsst.dax.apdb.ApdbConfig` is present in ``config``. 

67 """ 

68 if config is None: 

69 return None 

70 if isinstance(config, ApdbConfig): 

71 return Apdb(config) 

72 

73 for field in config.values(): 

74 if isinstance(field, ConfigurableInstance): 

75 result = self._getApdbFromConfigurableField(field) 

76 if result: 

77 return result 

78 elif isinstance(field, ConfigChoiceField.instanceDictClass): 

79 try: 

80 # can't test with hasattr because of non-standard getattr 

81 field.names 

82 except FieldValidationError: 

83 result = self._getApdb(field.active) 

84 else: 

85 result = self._getApdbFromConfigIterable(field.active) 

86 if result: 

87 return result 

88 elif isinstance(field, ConfigDictField.DictClass): 

89 result = self._getApdbFromConfigIterable(field.values()) 

90 if result: 

91 return result 

92 elif isinstance(field, Config): 

93 # Can't test for `ConfigField` more directly than this 

94 result = self._getApdb(field) 

95 if result: 

96 return result 

97 return None 

98 

99 def _getApdbFromConfigurableField(self, configurable): 

100 """Extract an Apdb object from a ConfigurableField. 

101 

102 Parameters 

103 ---------- 

104 configurable : `lsst.pex.config.ConfigurableInstance` or `None` 

105 A configurable that may contain a `lsst.dax.apdb.ApdbConfig`. 

106 

107 Returns 

108 ------- 

109 apdb : `lsst.dax.apdb.Apdb`-like or `None` 

110 A `lsst.dax.apdb.Apdb` object or a drop-in replacement, if a 

111 suitable config exists. 

112 """ 

113 if configurable is None: 

114 return None 

115 

116 if configurable.ConfigClass == ApdbConfig: 

117 return configurable.apply() 

118 else: 

119 return self._getApdb(configurable.value) 

120 

121 def _getApdbFromConfigIterable(self, configDict): 

122 """Extract an Apdb object from an iterable of configs. 

123 

124 Parameters 

125 ---------- 

126 configDict: iterable of `lsst.pex.config.Config` or `None` 

127 A config iterable that may contain a `lsst.dax.apdb.ApdbConfig`. 

128 

129 Returns 

130 ------- 

131 apdb : `lsst.dax.apdb.Apdb`-like or `None` 

132 A `lsst.dax.apdb.Apdb` object or a drop-in replacement, if a 

133 suitable config exists. 

134 """ 

135 if configDict: 

136 for config in configDict: 

137 result = self._getApdb(config) 

138 if result: 

139 return result 

140 return None 

141 

142 def run(self, config): 

143 """Create a database consistent with a science task config. 

144 

145 Parameters 

146 ---------- 

147 config : `lsst.pex.config.Config` or `None` 

148 A config that should contain a `lsst.dax.apdb.ApdbConfig`. 

149 Behavior is undefined if there is more than one such member. 

150 

151 Returns 

152 ------- 

153 result : `lsst.pipe.base.Struct` 

154 Result struct with components: 

155 

156 ``apdb`` 

157 A database configured the same way as in ``config``, if one 

158 exists (`lsst.dax.apdb.Apdb` or `None`). 

159 """ 

160 return Struct(apdb=self._getApdb(config)) 

161 

162 

163class DirectApdbLoader(Task): 

164 """A Task that takes a Apdb config and returns the corresponding 

165 Apdb object. 

166 

167 Parameters 

168 ---------- 

169 *args 

170 **kwargs 

171 Constructor parameters are the same as for `lsst.pipe.base.Task`. 

172 """ 

173 

174 _DefaultName = "directApdb" 

175 ConfigClass = Config 

176 

177 def __init__(self, **kwargs): 

178 super().__init__(**kwargs) 

179 

180 def run(self, config): 

181 """Create a database from a config. 

182 

183 Parameters 

184 ---------- 

185 config : `lsst.dax.apdb.ApdbConfig` or `None` 

186 A config for the database connection. 

187 

188 Returns 

189 ------- 

190 result : `lsst.pipe.base.Struct` 

191 Result struct with components: 

192 

193 ``apdb`` 

194 A database configured the same way as in ``config``. 

195 """ 

196 return Struct(apdb=(Apdb(config) if config else None)) 

197 

198 

199class ApdbMetricConnections( 

200 MetricConnections, 

201 dimensions={"instrument"}, 

202): 

203 """An abstract connections class defining a database input. 

204 

205 Notes 

206 ----- 

207 ``ApdbMetricConnections`` defines the following dataset templates: 

208 ``package`` 

209 Name of the metric's namespace. By 

210 :ref:`verify_metrics <verify-metrics-package>` convention, this is 

211 the name of the package the metric is most closely 

212 associated with. 

213 ``metric`` 

214 Name of the metric, excluding any namespace. 

215 """ 

216 dbInfo = connectionTypes.Input( 

217 name="apdb_marker", 

218 doc="The dataset from which an APDB instance can be constructed by " 

219 "`dbLoader`. By default this is assumed to be a marker produced " 

220 "by AP processing.", 

221 storageClass="Config", 

222 multiple=True, 

223 dimensions={"instrument", "visit", "detector"}, 

224 ) 

225 # Replaces MetricConnections.measurement, which is detector-level 

226 measurement = connectionTypes.Output( 

227 name="metricvalue_{package}_{metric}", 

228 doc="The metric value computed by this task.", 

229 storageClass="MetricValue", 

230 dimensions={"instrument"}, 

231 ) 

232 

233 

234class ApdbMetricConfig(MetricConfig, 

235 pipelineConnections=ApdbMetricConnections): 

236 """A base class for APDB metric task configs. 

237 """ 

238 dbLoader = ConfigurableField( 

239 target=DirectApdbLoader, 

240 doc="Task for loading a database from `dbInfo`. Its run method must " 

241 "take one object of the dataset type indicated by `dbInfo` and return " 

242 "a Struct with an 'apdb' member." 

243 ) 

244 

245 

246class ApdbMetricTask(MetricTask): 

247 """A base class for tasks that compute metrics from an alert production 

248 database. 

249 

250 Parameters 

251 ---------- 

252 **kwargs 

253 Constructor parameters are the same as for 

254 `lsst.pipe.base.PipelineTask`. 

255 

256 Notes 

257 ----- 

258 This class should be customized by overriding `makeMeasurement`. You 

259 should not need to override `run`. 

260 """ 

261 # Design note: makeMeasurement is an overrideable method rather than a 

262 # subtask to keep the configs for `MetricsControllerTask` as simple as 

263 # possible. This was judged more important than ensuring that no 

264 # implementation details of MetricTask can leak into 

265 # application-specific code. 

266 

267 ConfigClass = ApdbMetricConfig 

268 

269 def __init__(self, **kwargs): 

270 super().__init__(**kwargs) 

271 

272 self.makeSubtask("dbLoader") 

273 

274 @abc.abstractmethod 

275 def makeMeasurement(self, dbHandle, outputDataId): 

276 """Compute the metric from database data. 

277 

278 Parameters 

279 ---------- 

280 dbHandle : `lsst.dax.apdb.Apdb` 

281 A database instance. 

282 outputDataId : any data ID type 

283 The subset of the database to which this measurement applies. 

284 May be empty to represent the entire dataset. 

285 

286 Returns 

287 ------- 

288 measurement : `lsst.verify.Measurement` or `None` 

289 The measurement corresponding to the input data. 

290 

291 Raises 

292 ------ 

293 MetricComputationError 

294 Raised if an algorithmic or system error prevents calculation of 

295 the metric. See `run` for expected behavior. 

296 """ 

297 

298 def run(self, dbInfo, outputDataId={}): 

299 """Compute a measurement from a database. 

300 

301 Parameters 

302 ---------- 

303 dbInfo : `list` 

304 The datasets (of the type indicated by the config) from 

305 which to load the database. If more than one dataset is provided 

306 (as may be the case if DB writes are fine-grained), all are 

307 assumed identical. 

308 outputDataId: any data ID type, optional 

309 The output data ID for the metric value. Defaults to the empty ID, 

310 representing a value that covers the entire dataset. 

311 

312 Returns 

313 ------- 

314 result : `lsst.pipe.base.Struct` 

315 Result struct with component: 

316 

317 ``measurement`` 

318 the value of the metric (`lsst.verify.Measurement` or `None`) 

319 

320 Raises 

321 ------ 

322 MetricComputationError 

323 Raised if an algorithmic or system error prevents calculation of 

324 the metric. 

325 

326 Notes 

327 ----- 

328 This implementation calls 

329 `~lsst.verify.tasks.ApdbMetricConfig.dbLoader` to acquire a database 

330 handle (taking `None` if no input), then passes it and the value of 

331 ``outputDataId`` to `makeMeasurement`. The result of `makeMeasurement` 

332 is returned to the caller. 

333 """ 

334 db = self.dbLoader.run(dbInfo[0] if dbInfo else None).apdb 

335 

336 if db is not None: 

337 measurement = self.makeMeasurement(db, outputDataId) 

338 else: 

339 measurement = None 

340 

341 return Struct(measurement=measurement) 

342 

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

344 """Do Butler I/O to provide in-memory objects for run. 

345 

346 This specialization of runQuantum passes the output data ID to `run`. 

347 """ 

348 try: 

349 inputs = butlerQC.get(inputRefs) 

350 outputs = self.run(**inputs, 

351 outputDataId=outputRefs.measurement.dataId) 

352 if outputs.measurement is not None: 

353 butlerQC.put(outputs, outputRefs) 

354 else: 

355 self.log.debugf("Skipping measurement of {!r} on {} " 

356 "as not applicable.", self, inputRefs) 

357 except MetricComputationError: 

358 # Apparently lsst.log doesn't have built-in exception support? 

359 self.log.errorf( 

360 "Measurement of {!r} failed on {}->{}\n{}", 

361 self, inputRefs, outputRefs, traceback.format_exc())