Coverage for python/lsst/analysis/tools/interfaces/_analysisTools.py: 22%

134 statements  

« prev     ^ index     » next       coverage.py v7.2.5, created at 2023-05-04 11:09 +0000

1# This file is part of analysis_tools. 

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 __future__ import annotations 

23 

24__all__ = ("AnalysisTool",) 

25 

26from collections.abc import Mapping 

27from functools import wraps 

28from typing import Callable, Iterable, Protocol, runtime_checkable 

29 

30from lsst.pex.config import Field, ListField 

31from lsst.pex.config.configurableActions import ConfigurableActionField 

32from lsst.verify import Measurement 

33 

34from ._actions import AnalysisAction, JointAction, JointResults, NoPlot, PlotAction 

35from ._interfaces import KeyedData, KeyedDataSchema, KeyedResults, PlotTypes 

36from ._stages import BasePrep, BaseProcess, BaseProduce 

37 

38 

39@runtime_checkable 

40class _HasOutputNames(Protocol): 

41 def getOutputNames(self) -> Iterable[str]: 

42 ... 

43 

44 

45def _finalizeWrapper( 

46 f: Callable[[AnalysisTool], None], cls: type[AnalysisTool] 

47) -> Callable[[AnalysisTool], None]: 

48 """Wrap a classes finalize function to ensure the base classes special 

49 finalize method only fires after the most derived finalize method. 

50 

51 Parameters 

52 ---------- 

53 f : `Callable` 

54 Function that is being wrapped 

55 cls : `type` of `AnalysisTool` 

56 The class which is having its function wrapped 

57 

58 Returns 

59 ------- 

60 function : `Callable` 

61 The new function which wraps the old 

62 """ 

63 

64 @wraps(f) 

65 def wrapper(self: AnalysisTool) -> None: 

66 # call the wrapped finalize function 

67 f(self) 

68 # get the method resolution order for the self variable 

69 mro = self.__class__.mro() 

70 

71 # Find which class in the mro that last defines a finalize method 

72 # note that this is in the reverse order from the mro, because the 

73 # last class in an inheritance stack is the first in the mro (aka you 

74 # walk from the furthest child first. 

75 # 

76 # Also note that the most derived finalize method need not be the same 

77 # as the type of self, as that might inherit from a parent somewhere 

78 # between it and the furthest parent. 

79 mostDerived: type | None = None 

80 for klass in mro: 

81 # inspect the classes dictionary to see if it specifically defines 

82 # finalize. This is needed because normal lookup will go through 

83 # the mro, but this needs to be restricted to each class. 

84 if "finalize" in vars(klass): 

85 mostDerived = klass 

86 break 

87 

88 # Find what stage in the MRO walking process the recursive function 

89 # call is in. 

90 this = super(cls, self).__thisclass__ 

91 

92 # If the current place in the MRO walking is also the class that 

93 # defines the most derived instance of finalize, then call the base 

94 # classes private finalize that must be called after everything else. 

95 if mostDerived is not None and this == mostDerived: 

96 self._baseFinalize() 

97 

98 return wrapper 

99 

100 

101class AnalysisTool(AnalysisAction): 

102 r"""A tool which which calculates a single type of analysis on input data, 

103 though it may return more than one result. 

104 

105 Although `AnalysisTool`\ s are considered a single type of analysis, the 

106 classes themselves can be thought of as a container. `AnalysisTool`\ s 

107 are aggregations of `AnalysisAction`\ s to form prep, process, and 

108 produce stages. These stages allow better reuse of individual 

109 `AnalysisActions` and easier introspection in contexts such as a notebook 

110 or interpreter. 

111 

112 An `AnalysisTool` can be thought of an an individual configuration that 

113 specifies which `AnalysisAction` should run for each stage. 

114 

115 The stages themselves are also configurable, allowing control over various 

116 aspects of the individual `AnalysisAction`\ s. 

117 """ 

118 prep = ConfigurableActionField[AnalysisAction](doc="Action to run to prepare inputs", default=BasePrep) 

119 process = ConfigurableActionField[AnalysisAction]( 

120 doc="Action to process data into intended form", default=BaseProcess 

121 ) 

122 produce = ConfigurableActionField[AnalysisAction]( 

123 doc="Action to perform any finalization steps", default=BaseProduce 

124 ) 

125 metric_tags = ListField[str]( 

126 doc="List of tags which will be associated with metric measurement(s)", default=[] 

127 ) 

128 

129 def __init_subclass__(cls: type[AnalysisTool], **kwargs): 

130 super().__init_subclass__(**kwargs) 

131 # Wrap all definitions of the finalize method in a special wrapper that 

132 # ensures that the bases classes private finalize is called last. 

133 if "finalize" in vars(cls): 

134 cls.finalize = _finalizeWrapper(cls.finalize, cls) 

135 

136 parameterizedBand: bool | Field[bool] = True 

137 """Specifies if an `AnalysisTool` may parameterize a band within any field 

138 in any stage, or if the set of bands is already uniquely determined though 

139 configuration. I.e. can this `AnalysisTool` be automatically looped over to 

140 produce a result for multiple bands. 

141 """ 

142 

143 def __call__(self, data: KeyedData, **kwargs) -> KeyedResults: 

144 bands = kwargs.pop("bands", None) 

145 if "plotInfo" in kwargs and kwargs.get("plotInfo") is not None: 

146 kwargs["plotInfo"]["plotName"] = self.identity 

147 if not self.parameterizedBand or bands is None: 

148 if "band" not in kwargs: 

149 # Some tasks require a "band" key for naming. This shouldn't 

150 # affect the results. DM-35813 should make this unnecessary. 

151 kwargs["band"] = "analysisTools" 

152 return self._call_single(data, **kwargs) 

153 results: KeyedResults = {} 

154 for band in bands: 

155 kwargs["band"] = band 

156 subResult = self._call_single(data, **kwargs) 

157 for key, value in subResult.items(): 

158 match value: 

159 case PlotTypes(): 

160 results[f"{band}_{key}"] = value 

161 case Measurement(): 

162 results[key] = value 

163 return results 

164 

165 def _call_single(self, data: KeyedData, **kwargs) -> KeyedResults: 

166 # create a shallow copy of kwargs 

167 kwargs = dict(**kwargs) 

168 kwargs["metric_tags"] = list(self.metric_tags or ()) 

169 prepped: KeyedData = self.prep(data, **kwargs) # type: ignore 

170 processed: KeyedData = self.process(prepped, **kwargs) # type: ignore 

171 finalized: Mapping[str, PlotTypes] | PlotTypes | Mapping[ 

172 str, Measurement 

173 ] | Measurement | JointResults = self.produce( 

174 processed, **kwargs 

175 ) # type: ignore 

176 return self._process_single_results(finalized) 

177 

178 def _getPlotType(self) -> str: 

179 match self.produce: 

180 case PlotAction(): 

181 return type(self.produce).__name__ 

182 case JointAction(plot=NoPlot()): 

183 pass 

184 case JointAction(plot=plotter): 

185 return type(plotter).__name__ 

186 

187 return "" 

188 

189 def _process_single_results( 

190 self, 

191 results: Mapping[str, PlotTypes] | PlotTypes | Mapping[str, Measurement] | Measurement | JointResults, 

192 ) -> KeyedResults: 

193 accumulation = {} 

194 suffix = self._getPlotType() 

195 predicate = f"{self.identity}" if self.identity else "" 

196 match results: 

197 case Mapping(): 

198 for key, value in results.items(): 

199 match value: 

200 case PlotTypes(): 

201 iterable = (predicate, key, suffix) 

202 case Measurement(): 

203 iterable = (predicate, key) 

204 refKey = "_".join(x for x in iterable if x) 

205 accumulation[refKey] = value 

206 case PlotTypes(): 

207 refKey = "_".join(x for x in (predicate, suffix) if x) 

208 accumulation[refKey] = results 

209 case Measurement(): 

210 accumulation[f"{predicate}"] = results 

211 case JointResults(plot=plotResults, metric=metricResults): 

212 if plotResults is not None: 

213 subResult = self._process_single_results(plotResults) 

214 accumulation.update(subResult) 

215 if metricResults is not None: 

216 subResult = self._process_single_results(metricResults) 

217 accumulation.update(subResult) 

218 return accumulation 

219 

220 def getInputSchema(self) -> KeyedDataSchema: 

221 return self.prep.getInputSchema() 

222 

223 def populatePrepFromProcess(self): 

224 """Add additional inputs to the prep stage if supported. 

225 

226 If the configured prep action supports adding to it's input schema, 

227 attempt to add the required inputs schema from the process stage to the 

228 prep stage. 

229 

230 This method will be a no-op if the prep action does not support this 

231 feature. 

232 """ 

233 self.prep.addInputSchema(self.process.getInputSchema()) 

234 

235 def getOutputNames(self) -> Iterable[str]: 

236 """Return the names of the plots produced by this analysis tool. 

237 

238 If there is a `PlotAction` defined in the produce action, these names 

239 will either come from the `PlotAction` if it defines a 

240 ``getOutputNames`` method (likely if it returns a mapping of figures), 

241 or a default value is used and a single figure is assumed. 

242 

243 Returns 

244 ------- 

245 result : `tuple` of `str` 

246 Names for each plot produced by this action. 

247 """ 

248 match self.produce: 

249 case JointAction(plot=NoPlot()): 

250 return tuple() 

251 case _HasOutputNames(): 

252 outNames = tuple(self.produce.getOutputNames()) 

253 case _: 

254 raise ValueError(f"Unsupported Action type {type(self.produce)} for getting output names") 

255 

256 results = [] 

257 suffix = self._getPlotType() 

258 if self.parameterizedBand: 

259 prefix = "_".join(x for x in ("{band}", self.identity) if x) 

260 else: 

261 prefix = f"{self.identity}" if self.identity else "" 

262 

263 if outNames: 

264 for name in outNames: 

265 results.append("_".join(x for x in (prefix, name, suffix) if x)) 

266 else: 

267 results.append("_".join(x for x in (prefix, suffix) if x)) 

268 return results 

269 

270 def finalize(self) -> None: 

271 """Run any finalization code that depends on configuration being 

272 complete. 

273 """ 

274 pass 

275 

276 def _baseFinalize(self) -> None: 

277 self.populatePrepFromProcess() 

278 

279 def freeze(self): 

280 if not self.__dict__.get("_finalizeRun"): 

281 self.finalize() 

282 self.__dict__["_finalizeRun"] = True 

283 super().freeze() 

284 

285 

286# explicitly wrap the finalize of the base class 

287AnalysisTool.finalize = _finalizeWrapper(AnalysisTool.finalize, AnalysisTool)