Coverage for python/lsst/cp/verify/mergeResults.py: 38%
Shortcuts 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
Shortcuts 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 cp_verify.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://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 <http://www.gnu.org/licenses/>.
21import lsst.pipe.base as pipeBase
22import lsst.pipe.base.connectionTypes as cT
23import lsst.pex.config as pexConfig
26__all__ = ['CpVerifyExpMergeConfig', 'CpVerifyExpMergeTask',
27 'CpVerifyRunMergeConfig', 'CpVerifyRunMergeTask',
28 'CpVerifyVisitExpMergeConfig', 'CpVerifyVisitExpMergeTask',
29 'CpVerifyVisitRunMergeConfig', 'CpVerifyVisitRunMergeTask']
32class CpVerifyExpMergeConnections(pipeBase.PipelineTaskConnections,
33 dimensions={"instrument", "exposure"},
34 defaultTemplates={}):
35 inputStats = cT.Input(
36 name="detectorStats",
37 doc="Input statistics to merge.",
38 storageClass="StructuredDataDict",
39 dimensions=["instrument", "exposure", "detector"],
40 multiple=True,
41 )
42 camera = cT.PrerequisiteInput(
43 name="camera",
44 storageClass="Camera",
45 doc="Input camera.",
46 dimensions=["instrument", ],
47 isCalibration=True,
48 )
50 outputStats = cT.Output(
51 name="exposureStats",
52 doc="Output statistics.",
53 storageClass="StructuredDataDict",
54 dimensions=["instrument", "exposure"],
55 )
58class CpVerifyExpMergeConfig(pipeBase.PipelineTaskConfig,
59 pipelineConnections=CpVerifyExpMergeConnections):
60 """Configuration parameters for exposure stats merging.
61 """
62 exposureStatKeywords = pexConfig.DictField(
63 keytype=str,
64 itemtype=str,
65 doc="Dictionary of statistics to run on the set of detector values. The key should be the test "
66 "name to record in the output, and the value should be the `lsst.afw.math` statistic name string.",
67 default={},
68 )
71class CpVerifyExpMergeTask(pipeBase.PipelineTask, pipeBase.CmdLineTask):
72 """Merge statistics from detectors together.
73 """
74 ConfigClass = CpVerifyExpMergeConfig
75 _DefaultName = 'cpVerifyExpMerge'
77 def runQuantum(self, butlerQC, inputRefs, outputRefs):
78 inputs = butlerQC.get(inputRefs)
80 dimensions = [exp.dataId.byName() for exp in inputRefs.inputStats]
81 inputs['inputDims'] = dimensions
83 outputs = self.run(**inputs)
84 butlerQC.put(outputs, outputRefs)
86 def run(self, inputStats, camera, inputDims):
87 """Merge statistics.
89 Parameters
90 ----------
91 inputStats : `list` [`dict`]
92 Measured statistics for a detector (from
93 CpVerifyStatsTask).
94 camera : `lsst.afw.cameraGeom.Camera`
95 The camera geometry for this exposure.
96 inputDims : `list` [`dict`]
97 List of dictionaries of input data dimensions/values.
98 Each list entry should contain:
100 ``"exposure"``
101 exposure id value (`int`)
102 ``"detector"``
103 detector id value (`int`)
105 Returns
106 -------
107 outputStats : `dict`
108 Merged full exposure statistics.
110 See Also
111 --------
112 lsst.cp.verify.CpVerifyStatsTask
114 Notes
115 -----
116 The outputStats should have a yaml representation of the form:
118 DET:
119 DetName1:
120 FAILURES:
121 - TEST_NAME
122 STAT: value
123 STAT2: value2
124 DetName2:
125 VERIFY:
126 TEST: boolean
127 TEST2: boolean
128 SUCCESS: boolean
129 """
130 outputStats = {}
131 success = True
133 mergedStats = {}
134 for detStats, dimensions in zip(inputStats, inputDims):
135 detId = dimensions['detector']
136 detName = camera[detId].getName()
137 calcStats = {}
139 mergedStats[detName] = detStats
141 if detStats['SUCCESS'] is True:
142 calcStats['SUCCESS'] = True
143 else:
144 calcStats['SUCCESS'] = False
145 calcStats['FAILURES'] = list()
146 success = False
147 # See if the detector failed
148 if 'DET' in detStats['VERIFY']:
149 for testName, testResult in detStats['VERIFY']['DET'].items():
150 if testResult is False:
151 calcStats['FAILURES'].append(testName)
152 # See if the catalog failed
153 if 'CATALOG' in detStats['VERIFY']:
154 for testName, testResult in detStats['VERIFY']['CATALOG'].items():
155 if testResult is False:
156 calcStats['FAILURES'].append(testName)
157 # See if an amplifier failed
158 for ampName, ampStats in detStats['VERIFY']['AMP'].items():
159 ampSuccess = ampStats.pop('SUCCESS')
160 if not ampSuccess:
161 for testName, testResult in ampStats.items():
162 if testResult is False:
163 calcStats['FAILURES'].append(ampName + " " + testName)
165 outputStats[detName] = calcStats
167 exposureSuccess = True
168 if len(self.config.exposureStatKeywords):
169 outputStats['EXP'] = self.exposureStatistics(mergedStats)
170 outputStats['VERIFY'], exposureSuccess = self.verify(mergedStats, outputStats)
172 outputStats['SUCCESS'] = success & exposureSuccess
174 return pipeBase.Struct(
175 outputStats=outputStats,
176 )
178 def exposureStatistics(self, statisticsDict):
179 """Calculate exposure level statistics based on the existing
180 per-amplifier and per-detector measurements.
182 Parameters
183 ----------
184 statisticsDictionary : `dict [`str`, `dict` [`str`, scalar]],
185 Dictionary of measured statistics. The top level
186 dictionary is keyed on the detector names, and contains
187 the measured statistics from the per-detector
188 measurements.
190 Returns
191 -------
192 outputStatistics : `dict` [`str, scalar]
193 A dictionary of the statistics measured and their values.
194 """
195 raise NotImplementedError("Subclasses must implement verification criteria.")
197 def verify(self, detectorStatistics, statisticsDictionary):
199 """Verify if the measured statistics meet the verification criteria.
201 Parameters
202 ----------
203 detectorStatistics : `dict` [`str`, `dict` [`str`, scalar]]
204 Merged set of input detector level statistics.
205 statisticsDictionary : `dict` [`str`, `dict` [`str`, scalar]]
206 Dictionary of measured statistics. The inner dictionary
207 should have keys that are statistic names (`str`) with
208 values that are some sort of scalar (`int` or `float` are
209 the mostly likely types).
211 Returns
212 -------
213 outputStatistics : `dict` [`str`, `dict` [`str`, `bool`]]
214 A dictionary indexed by the amplifier name, containing
215 dictionaries of the verification criteria.
216 success : `bool`
217 A boolean indicating if all tests have passed.
219 Raises
220 ------
221 NotImplementedError :
222 This method must be implemented by the calibration-type
223 subclass.
224 """
225 raise NotImplementedError("Subclasses must implement verification criteria.")
228class CpVerifyRunMergeConnections(pipeBase.PipelineTaskConnections,
229 dimensions={"instrument"},
230 defaultTemplates={}):
231 inputStats = cT.Input(
232 name="exposureStats",
233 doc="Input statistics to merge.",
234 storageClass="StructuredDataDict",
235 dimensions=["instrument", "exposure"],
236 multiple=True,
237 )
239 outputStats = cT.Output(
240 name="runStats",
241 doc="Output statistics.",
242 storageClass="StructuredDataDict",
243 dimensions=["instrument"],
244 )
247class CpVerifyRunMergeConfig(pipeBase.PipelineTaskConfig,
248 pipelineConnections=CpVerifyRunMergeConnections):
249 """Configuration paramters for exposure stats merging.
250 """
251 runStatKeywords = pexConfig.DictField(
252 keytype=str,
253 itemtype=str,
254 doc="Dictionary of statistics to run on the set of exposure values. The key should be the test "
255 "name to record in the output, and the value should be the `lsst.afw.math` statistic name string.",
256 default={},
257 )
260class CpVerifyRunMergeTask(pipeBase.PipelineTask, pipeBase.CmdLineTask):
261 """Merge statistics from detectors together.
262 """
263 ConfigClass = CpVerifyRunMergeConfig
264 _DefaultName = 'cpVerifyRunMerge'
266 def runQuantum(self, butlerQC, inputRefs, outputRefs):
267 inputs = butlerQC.get(inputRefs)
269 dimensions = [exp.dataId.byName() for exp in inputRefs.inputStats]
270 inputs['inputDims'] = dimensions
272 outputs = self.run(**inputs)
273 butlerQC.put(outputs, outputRefs)
275 def run(self, inputStats, inputDims):
276 """Merge statistics.
278 Parameters
279 ----------
280 inputStats : `list` [`dict`]
281 Measured statistics for a detector.
282 inputDims : `list` [`dict`]
283 List of dictionaries of input data dimensions/values.
284 Each list entry should contain:
286 ``"exposure"``
287 exposure id value (`int`)
289 Returns
290 -------
291 outputStats : `dict`
292 Merged full exposure statistics.
294 Notes
295 -----
296 The outputStats should have a yaml representation as follows.
298 VERIFY:
299 ExposureId1:
300 VERIFY_MEAN: boolean
301 VERIFY_SIGMA: boolean
302 ExposureId2:
303 [...]
304 MEAN_UNIMODAL: boolean
305 SIGMA_UNIMODAL: boolean
306 """
307 outputStats = {}
308 success = True
309 for expStats, dimensions in zip(inputStats, inputDims):
310 expId = dimensions.get('exposure', dimensions.get('visit', None))
311 if expId is None:
312 raise RuntimeError("Could not identify the exposure from %s", dimensions)
314 calcStats = {}
316 expSuccess = expStats.pop('SUCCESS')
317 if expSuccess:
318 calcStats['SUCCESS'] = True
319 else:
320 calcStats['FAILURES'] = list()
321 success = False
322 for detName, detStats in expStats.items():
323 detSuccess = detStats.pop('SUCCESS')
324 if not detSuccess:
325 for testName in expStats[detName]['FAILURES']:
326 calcStats['FAILURES'].append(detName + " " + testName)
328 outputStats[expId] = calcStats
330 runSuccess = True
331 if len(self.config.runStatKeywords):
332 outputStats['VERIFY'], runSuccess = self.verify(outputStats)
334 outputStats['SUCCESS'] = success & runSuccess
336 return pipeBase.Struct(
337 outputStats=outputStats,
338 )
340 def verify(self, statisticsDictionary):
341 """Verify if the measured statistics meet the verification criteria.
343 Parameters
344 ----------
345 statisticsDictionary : `dict` [`str`, `dict`],
346 Dictionary of measured statistics. The inner dictionary
347 should have keys that are statistic names (`str`) with
348 values that are some sort of scalar (`int` or `float` are
349 the mostly likely types).
351 Returns
352 -------
353 outputStatistics : `dict` [`str`, `dict` [`str`, `bool`]]
354 A dictionary indexed by the amplifier name, containing
355 dictionaries of the verification criteria.
356 success : `bool`
357 A boolean indicating if all tests have passed.
359 Raises
360 ------
361 NotImplementedError :
362 This method must be implemented by the calibration-type
363 subclass.
365 """
366 raise NotImplementedError("Subclasses must implement verification criteria.")
369class CpVerifyVisitExpMergeConnections(pipeBase.PipelineTaskConnections,
370 dimensions={"instrument", "visit"},
371 defaultTemplates={}):
372 inputStats = cT.Input(
373 name="detectorStats",
374 doc="Input statistics to merge.",
375 storageClass="StructuredDataDict",
376 dimensions=["instrument", "visit", "detector"],
377 multiple=True,
378 )
379 camera = cT.PrerequisiteInput(
380 name="camera",
381 storageClass="Camera",
382 doc="Input camera.",
383 dimensions=["instrument", ],
384 isCalibration=True,
385 )
387 outputStats = cT.Output(
388 name="exposureStats",
389 doc="Output statistics.",
390 storageClass="StructuredDataDict",
391 dimensions=["instrument", "visit"],
392 )
395class CpVerifyVisitExpMergeConfig(CpVerifyExpMergeConfig,
396 pipelineConnections=CpVerifyVisitExpMergeConnections):
397 pass
400class CpVerifyVisitExpMergeTask(CpVerifyExpMergeTask):
401 """Merge visit based data."""
403 ConfigClass = CpVerifyVisitExpMergeConfig
404 _DefaultName = 'cpVerifyVisitExpMerge'
406 pass
409class CpVerifyVisitRunMergeConnections(pipeBase.PipelineTaskConnections,
410 dimensions={"instrument"},
411 defaultTemplates={}):
412 inputStats = cT.Input(
413 name="exposureStats",
414 doc="Input statistics to merge.",
415 storageClass="StructuredDataDict",
416 dimensions=["instrument", "visit"],
417 multiple=True,
418 )
420 outputStats = cT.Output(
421 name="runStats",
422 doc="Output statistics.",
423 storageClass="StructuredDataDict",
424 dimensions=["instrument"],
425 )
428class CpVerifyVisitRunMergeConfig(CpVerifyRunMergeConfig,
429 pipelineConnections=CpVerifyVisitRunMergeConnections):
430 pass
433class CpVerifyVisitRunMergeTask(CpVerifyRunMergeTask):
434 """Merge visit based data."""
436 ConfigClass = CpVerifyVisitRunMergeConfig
437 _DefaultName = 'cpVerifyVisitRunMerge'
439 pass