Coverage for python/lsst/pipe/base/_task_metadata.py: 15%

206 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-07-23 08:14 +0000

1# This file is part of pipe_base. 

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__ = ["TaskMetadata"] 

23 

24import itertools 

25import numbers 

26import warnings 

27from collections.abc import Collection, Iterator, Mapping, Sequence 

28from typing import Any, Protocol 

29 

30from lsst.daf.butler._compat import _BaseModelCompat 

31from pydantic import Field, StrictBool, StrictFloat, StrictInt, StrictStr 

32 

33_DEPRECATION_REASON = "Will be removed after v25." 

34_DEPRECATION_VERSION = "v24" 

35 

36# The types allowed in a Task metadata field are restricted 

37# to allow predictable serialization. 

38_ALLOWED_PRIMITIVE_TYPES = (str, float, int, bool) 

39 

40 

41class PropertySetLike(Protocol): 

42 """Protocol that looks like a ``lsst.daf.base.PropertySet`` 

43 

44 Enough of the API is specified to support conversion of a 

45 ``PropertySet`` to a `TaskMetadata`. 

46 """ 

47 

48 def paramNames(self, topLevelOnly: bool = True) -> Collection[str]: 

49 ... 

50 

51 def getArray(self, name: str) -> Any: 

52 ... 

53 

54 

55def _isListLike(v: Any) -> bool: 

56 return isinstance(v, Sequence) and not isinstance(v, str) 

57 

58 

59class TaskMetadata(_BaseModelCompat): 

60 """Dict-like object for storing task metadata. 

61 

62 Metadata can be stored at two levels: single task or task plus subtasks. 

63 The later is called full metadata of a task and has a form 

64 

65 topLevelTaskName:subtaskName:subsubtaskName.itemName 

66 

67 Metadata item key of a task (`itemName` above) must not contain `.`, 

68 which serves as a separator in full metadata keys and turns 

69 the value into sub-dictionary. Arbitrary hierarchies are supported. 

70 """ 

71 

72 scalars: dict[str, StrictFloat | StrictInt | StrictBool | StrictStr] = Field(default_factory=dict) 

73 arrays: dict[str, list[StrictFloat] | list[StrictInt] | list[StrictBool] | list[StrictStr]] = Field( 

74 default_factory=dict 

75 ) 

76 metadata: dict[str, "TaskMetadata"] = Field(default_factory=dict) 

77 

78 @classmethod 

79 def from_dict(cls, d: Mapping[str, Any]) -> "TaskMetadata": 

80 """Create a TaskMetadata from a dictionary. 

81 

82 Parameters 

83 ---------- 

84 d : `~collections.abc.Mapping` 

85 Mapping to convert. Can be hierarchical. Any dictionaries 

86 in the hierarchy are converted to `TaskMetadata`. 

87 

88 Returns 

89 ------- 

90 meta : `TaskMetadata` 

91 Newly-constructed metadata. 

92 """ 

93 metadata = cls() 

94 for k, v in d.items(): 

95 metadata[k] = v 

96 return metadata 

97 

98 @classmethod 

99 def from_metadata(cls, ps: PropertySetLike) -> "TaskMetadata": 

100 """Create a TaskMetadata from a PropertySet-like object. 

101 

102 Parameters 

103 ---------- 

104 ps : `PropertySetLike` or `TaskMetadata` 

105 A ``PropertySet``-like object to be transformed to a 

106 `TaskMetadata`. A `TaskMetadata` can be copied using this 

107 class method. 

108 

109 Returns 

110 ------- 

111 tm : `TaskMetadata` 

112 Newly-constructed metadata. 

113 

114 Notes 

115 ----- 

116 Items stored in single-element arrays in the supplied object 

117 will be converted to scalars in the newly-created object. 

118 """ 

119 # Use hierarchical names to assign values from input to output. 

120 # This API exists for both PropertySet and TaskMetadata. 

121 # from_dict() does not work because PropertySet is not declared 

122 # to be a Mapping. 

123 # PropertySet.toDict() is not present in TaskMetadata so is best 

124 # avoided. 

125 metadata = cls() 

126 for key in sorted(ps.paramNames(topLevelOnly=False)): 

127 value = ps.getArray(key) 

128 if len(value) == 1: 

129 value = value[0] 

130 metadata[key] = value 

131 return metadata 

132 

133 def to_dict(self) -> dict[str, Any]: 

134 """Convert the class to a simple dictionary. 

135 

136 Returns 

137 ------- 

138 d : `dict` 

139 Simple dictionary that can contain scalar values, array values 

140 or other dictionary values. 

141 

142 Notes 

143 ----- 

144 Unlike `dict()`, this method hides the model layout and combines 

145 scalars, arrays, and other metadata in the same dictionary. Can be 

146 used when a simple dictionary is needed. Use 

147 `TaskMetadata.from_dict()` to convert it back. 

148 """ 

149 d: dict[str, Any] = {} 

150 d.update(self.scalars) 

151 d.update(self.arrays) 

152 for k, v in self.metadata.items(): 

153 d[k] = v.to_dict() 

154 return d 

155 

156 def add(self, name: str, value: Any) -> None: 

157 """Store a new value, adding to a list if one already exists. 

158 

159 Parameters 

160 ---------- 

161 name : `str` 

162 Name of the metadata property. 

163 value 

164 Metadata property value. 

165 """ 

166 keys = self._getKeys(name) 

167 key0 = keys.pop(0) 

168 if len(keys) == 0: 

169 # If add() is being used, always store the value in the arrays 

170 # property as a list. It's likely there will be another call. 

171 slot_type, value = self._validate_value(value) 

172 if slot_type == "array": 

173 pass 

174 elif slot_type == "scalar": 

175 value = [value] 

176 else: 

177 raise ValueError("add() can only be used for primitive types or sequences of those types.") 

178 

179 if key0 in self.metadata: 

180 raise ValueError(f"Can not add() to key '{name}' since that is a TaskMetadata") 

181 

182 if key0 in self.scalars: 

183 # Convert scalar to array. 

184 # MyPy should be able to figure out that List[Union[T1, T2]] is 

185 # compatible with Union[List[T1], List[T2]] if the list has 

186 # only one element, but it can't. 

187 self.arrays[key0] = [self.scalars.pop(key0)] # type: ignore 

188 

189 if key0 in self.arrays: 

190 # Check that the type is not changing. 

191 if (curtype := type(self.arrays[key0][0])) is not (newtype := type(value[0])): 

192 raise ValueError(f"Type mismatch in add() -- currently {curtype} but adding {newtype}") 

193 self.arrays[key0].extend(value) 

194 else: 

195 self.arrays[key0] = value 

196 

197 return 

198 

199 self.metadata[key0].add(".".join(keys), value) 

200 

201 def getScalar(self, key: str) -> str | int | float | bool: 

202 """Retrieve a scalar item even if the item is a list. 

203 

204 Parameters 

205 ---------- 

206 key : `str` 

207 Item to retrieve. 

208 

209 Returns 

210 ------- 

211 value : `str`, `int`, `float`, or `bool` 

212 Either the value associated with the key or, if the key 

213 corresponds to a list, the last item in the list. 

214 

215 Raises 

216 ------ 

217 KeyError 

218 Raised if the item is not found. 

219 """ 

220 # Used in pipe_tasks. 

221 # getScalar() is the default behavior for __getitem__. 

222 return self[key] 

223 

224 def getArray(self, key: str) -> list[Any]: 

225 """Retrieve an item as a list even if it is a scalar. 

226 

227 Parameters 

228 ---------- 

229 key : `str` 

230 Item to retrieve. 

231 

232 Returns 

233 ------- 

234 values : `list` of any 

235 A list containing the value or values associated with this item. 

236 

237 Raises 

238 ------ 

239 KeyError 

240 Raised if the item is not found. 

241 """ 

242 keys = self._getKeys(key) 

243 key0 = keys.pop(0) 

244 if len(keys) == 0: 

245 if key0 in self.arrays: 

246 return self.arrays[key0] 

247 elif key0 in self.scalars: 

248 return [self.scalars[key0]] 

249 elif key0 in self.metadata: 

250 return [self.metadata[key0]] 

251 raise KeyError(f"'{key}' not found") 

252 

253 try: 

254 return self.metadata[key0].getArray(".".join(keys)) 

255 except KeyError: 

256 # Report the correct key. 

257 raise KeyError(f"'{key}' not found") from None 

258 

259 def names(self, topLevelOnly: bool = True) -> set[str]: 

260 """Return the hierarchical keys from the metadata. 

261 

262 Parameters 

263 ---------- 

264 topLevelOnly : `bool` 

265 If true, return top-level keys, otherwise full metadata item keys. 

266 

267 Returns 

268 ------- 

269 names : `collections.abc.Set` 

270 A set of top-level keys or full metadata item keys, including 

271 the top-level keys. 

272 

273 Notes 

274 ----- 

275 Should never be called in new code with ``topLevelOnly`` set to `True` 

276 -- this is equivalent to asking for the keys and is the default 

277 when iterating through the task metadata. In this case a deprecation 

278 message will be issued and the ability will raise an exception 

279 in a future release. 

280 

281 When ``topLevelOnly`` is `False` all keys, including those from the 

282 hierarchy and the top-level hierarchy, are returned. 

283 """ 

284 if topLevelOnly: 

285 warnings.warn("Use keys() instead. " + _DEPRECATION_REASON, FutureWarning) 

286 return set(self.keys()) 

287 else: 

288 names = set() 

289 for k, v in self.items(): 

290 names.add(k) # Always include the current level 

291 if isinstance(v, TaskMetadata): 

292 names.update({k + "." + item for item in v.names(topLevelOnly=topLevelOnly)}) 

293 return names 

294 

295 def paramNames(self, topLevelOnly: bool) -> set[str]: 

296 """Return hierarchical names. 

297 

298 Parameters 

299 ---------- 

300 topLevelOnly : `bool` 

301 Control whether only top-level items are returned or items 

302 from the hierarchy. 

303 

304 Returns 

305 ------- 

306 paramNames : `set` of `str` 

307 If ``topLevelOnly`` is `True`, returns any keys that are not 

308 part of a hierarchy. If `False` also returns fully-qualified 

309 names from the hierarchy. Keys associated with the top 

310 of a hierarchy are never returned. 

311 """ 

312 # Currently used by the verify package. 

313 paramNames = set() 

314 for k, v in self.items(): 

315 if isinstance(v, TaskMetadata): 

316 if not topLevelOnly: 

317 paramNames.update({k + "." + item for item in v.paramNames(topLevelOnly=topLevelOnly)}) 

318 else: 

319 paramNames.add(k) 

320 return paramNames 

321 

322 @staticmethod 

323 def _getKeys(key: str) -> list[str]: 

324 """Return the key hierarchy. 

325 

326 Parameters 

327 ---------- 

328 key : `str` 

329 The key to analyze. Can be dot-separated. 

330 

331 Returns 

332 ------- 

333 keys : `list` of `str` 

334 The key hierarchy that has been split on ``.``. 

335 

336 Raises 

337 ------ 

338 KeyError 

339 Raised if the key is not a string. 

340 """ 

341 try: 

342 keys = key.split(".") 

343 except Exception: 

344 raise KeyError(f"Invalid key '{key}': only string keys are allowed") from None 

345 return keys 

346 

347 def keys(self) -> tuple[str, ...]: 

348 """Return the top-level keys.""" 

349 return tuple(k for k in self) 

350 

351 def items(self) -> Iterator[tuple[str, Any]]: 

352 """Yield the top-level keys and values.""" 

353 for k, v in itertools.chain(self.scalars.items(), self.arrays.items(), self.metadata.items()): 

354 yield (k, v) 

355 

356 def __len__(self) -> int: 

357 """Return the number of items.""" 

358 return len(self.scalars) + len(self.arrays) + len(self.metadata) 

359 

360 # This is actually a Liskov substitution violation, because 

361 # pydantic.BaseModel says __iter__ should return something else. But the 

362 # pydantic docs say to do exactly this to in order to make a mapping-like 

363 # BaseModel, so that's what we do. 

364 def __iter__(self) -> Iterator[str]: # type: ignore 

365 """Return an iterator over each key.""" 

366 # The order of keys is not preserved since items can move 

367 # from scalar to array. 

368 return itertools.chain(iter(self.scalars), iter(self.arrays), iter(self.metadata)) 

369 

370 def __getitem__(self, key: str) -> Any: 

371 """Retrieve the item associated with the key. 

372 

373 Parameters 

374 ---------- 

375 key : `str` 

376 The key to retrieve. Can be dot-separated hierarchical. 

377 

378 Returns 

379 ------- 

380 value : `TaskMetadata`, `float`, `int`, `bool`, `str` 

381 A scalar value. For compatibility with ``PropertySet``, if the key 

382 refers to an array, the final element is returned and not the 

383 array itself. 

384 

385 Raises 

386 ------ 

387 KeyError 

388 Raised if the item is not found. 

389 """ 

390 keys = self._getKeys(key) 

391 key0 = keys.pop(0) 

392 if len(keys) == 0: 

393 if key0 in self.scalars: 

394 return self.scalars[key0] 

395 if key0 in self.metadata: 

396 return self.metadata[key0] 

397 if key0 in self.arrays: 

398 return self.arrays[key0][-1] 

399 raise KeyError(f"'{key}' not found") 

400 # Hierarchical lookup so the top key can only be in the metadata 

401 # property. Trap KeyError and reraise so that the correct key 

402 # in the hierarchy is reported. 

403 try: 

404 # And forward request to that metadata. 

405 return self.metadata[key0][".".join(keys)] 

406 except KeyError: 

407 raise KeyError(f"'{key}' not found") from None 

408 

409 def get(self, key: str, default: Any = None) -> Any: 

410 """Retrieve the item associated with the key or a default. 

411 

412 Parameters 

413 ---------- 

414 key : `str` 

415 The key to retrieve. Can be dot-separated hierarchical. 

416 default 

417 The value to return if the key does not exist. 

418 

419 Returns 

420 ------- 

421 value : `TaskMetadata`, `float`, `int`, `bool`, `str` 

422 A scalar value. If the key refers to an array, the final element 

423 is returned and not the array itself; this is consistent with 

424 `__getitem__` and `PropertySet.get`, but not ``to_dict().get``. 

425 """ 

426 try: 

427 return self[key] 

428 except KeyError: 

429 return default 

430 

431 def __setitem__(self, key: str, item: Any) -> None: 

432 """Store the given item.""" 

433 keys = self._getKeys(key) 

434 key0 = keys.pop(0) 

435 if len(keys) == 0: 

436 slots: dict[str, dict[str, Any]] = { 

437 "array": self.arrays, 

438 "scalar": self.scalars, 

439 "metadata": self.metadata, 

440 } 

441 primary: dict[str, Any] | None = None 

442 slot_type, item = self._validate_value(item) 

443 primary = slots.pop(slot_type, None) 

444 if primary is None: 

445 raise AssertionError(f"Unknown slot type returned from validator: {slot_type}") 

446 

447 # Assign the value to the right place. 

448 primary[key0] = item 

449 for property in slots.values(): 

450 # Remove any other entries. 

451 property.pop(key0, None) 

452 return 

453 

454 # This must be hierarchical so forward to the child TaskMetadata. 

455 if key0 not in self.metadata: 

456 self.metadata[key0] = TaskMetadata() 

457 self.metadata[key0][".".join(keys)] = item 

458 

459 # Ensure we have cleared out anything with the same name elsewhere. 

460 self.scalars.pop(key0, None) 

461 self.arrays.pop(key0, None) 

462 

463 def __contains__(self, key: str) -> bool: 

464 """Determine if the key exists.""" 

465 keys = self._getKeys(key) 

466 key0 = keys.pop(0) 

467 if len(keys) == 0: 

468 return key0 in self.scalars or key0 in self.arrays or key0 in self.metadata 

469 

470 if key0 in self.metadata: 

471 return ".".join(keys) in self.metadata[key0] 

472 return False 

473 

474 def __delitem__(self, key: str) -> None: 

475 """Remove the specified item. 

476 

477 Raises 

478 ------ 

479 KeyError 

480 Raised if the item is not present. 

481 """ 

482 keys = self._getKeys(key) 

483 key0 = keys.pop(0) 

484 if len(keys) == 0: 

485 # MyPy can't figure out that this way to combine the types in the 

486 # tuple is the one that matters, and annotating a local variable 

487 # helps it out. 

488 properties: tuple[dict[str, Any], ...] = (self.scalars, self.arrays, self.metadata) 

489 for property in properties: 

490 if key0 in property: 

491 del property[key0] 

492 return 

493 raise KeyError(f"'{key}' not found'") 

494 

495 try: 

496 del self.metadata[key0][".".join(keys)] 

497 except KeyError: 

498 # Report the correct key. 

499 raise KeyError(f"'{key}' not found'") from None 

500 

501 def _validate_value(self, value: Any) -> tuple[str, Any]: 

502 """Validate the given value. 

503 

504 Parameters 

505 ---------- 

506 value : Any 

507 Value to check. 

508 

509 Returns 

510 ------- 

511 slot_type : `str` 

512 The type of value given. Options are "scalar", "array", "metadata". 

513 item : Any 

514 The item that was given but possibly modified to conform to 

515 the slot type. 

516 

517 Raises 

518 ------ 

519 ValueError 

520 Raised if the value is not a recognized type. 

521 """ 

522 # Test the simplest option first. 

523 value_type = type(value) 

524 if value_type in _ALLOWED_PRIMITIVE_TYPES: 

525 return "scalar", value 

526 

527 if isinstance(value, TaskMetadata): 

528 return "metadata", value 

529 if isinstance(value, Mapping): 

530 return "metadata", self.from_dict(value) 

531 

532 if _isListLike(value): 

533 # For model consistency, need to check that every item in the 

534 # list has the same type. 

535 value = list(value) 

536 

537 type0 = type(value[0]) 

538 for i in value: 

539 if type(i) != type0: 

540 raise ValueError( 

541 "Type mismatch in supplied list. TaskMetadata requires all" 

542 f" elements have same type but see {type(i)} and {type0}." 

543 ) 

544 

545 if type0 not in _ALLOWED_PRIMITIVE_TYPES: 

546 # Must check to see if we got numpy floats or something. 

547 type_cast: type 

548 if isinstance(value[0], numbers.Integral): 

549 type_cast = int 

550 elif isinstance(value[0], numbers.Real): 

551 type_cast = float 

552 else: 

553 raise ValueError( 

554 f"Supplied list has element of type '{type0}'. " 

555 "TaskMetadata can only accept primitive types in lists." 

556 ) 

557 

558 value = [type_cast(v) for v in value] 

559 

560 return "array", value 

561 

562 # Sometimes a numpy number is given. 

563 if isinstance(value, numbers.Integral): 

564 value = int(value) 

565 return "scalar", value 

566 if isinstance(value, numbers.Real): 

567 value = float(value) 

568 return "scalar", value 

569 

570 raise ValueError(f"TaskMetadata does not support values of type {value!r}.") 

571 

572 

573# Needed because a TaskMetadata can contain a TaskMetadata. 

574TaskMetadata.model_rebuild()