Coverage for python/lsst/daf/butler/core/composites.py: 25%

60 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2023-02-05 10:07 +0000

1# This file is part of daf_butler. 

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

21 

22from __future__ import annotations 

23 

24"""Support for reading and writing composite objects.""" 

25 

26__all__ = ("CompositesConfig", "CompositesMap") 

27 

28import logging 

29from typing import TYPE_CHECKING, Union 

30 

31import yaml 

32 

33from .config import ConfigSubset 

34from .configSupport import processLookupConfigs 

35 

36if TYPE_CHECKING: 36 ↛ 37line 36 didn't jump to line 37, because the condition on line 36 was never true

37 from .._butlerConfig import ButlerConfig 

38 from .configSupport import LookupKey 

39 from .datasets import DatasetRef, DatasetType 

40 from .dimensions import DimensionUniverse 

41 from .storageClass import StorageClass 

42 

43log = logging.getLogger(__name__) 

44 

45# Key to access disassembly information 

46DISASSEMBLY_KEY = "disassembled" 

47 

48 

49class CompositesConfig(ConfigSubset): 

50 """Configuration specifics for Composites.""" 

51 

52 component = "composites" 

53 requiredKeys = ("default", DISASSEMBLY_KEY) 

54 defaultConfigFile = "datastores/composites.yaml" 

55 

56 def validate(self) -> None: 

57 """Validate entries have the correct type.""" 

58 super().validate() 

59 # For now assume flat config with keys mapping to booleans 

60 for k, v in self[DISASSEMBLY_KEY].items(): 

61 if not isinstance(v, bool): 

62 raise ValueError(f"CompositesConfig: Key {k} is not a Boolean") 

63 

64 

65class CompositesMap: 

66 """Determine whether something should be disassembled. 

67 

68 Compares a `DatasetType` or `StorageClass` with the map and determines 

69 whether disassembly is requested. 

70 

71 Parameters 

72 ---------- 

73 config : `str`, `ButlerConfig`, or `CompositesConfig` 

74 Configuration to control composites disassembly. 

75 universe : `DimensionUniverse` 

76 Set of all known dimensions, used to expand and validate any used 

77 in lookup keys. 

78 """ 

79 

80 def __init__(self, config: Union[str, ButlerConfig, CompositesConfig], *, universe: DimensionUniverse): 

81 if not isinstance(config, CompositesConfig): 

82 config = CompositesConfig(config) 

83 assert isinstance(config, CompositesConfig) 

84 self.config = config 

85 

86 # Pre-filter the disassembly lookup table to remove the 

87 # placeholder __ key we added for documentation. 

88 # It should be harmless but might confuse validation 

89 # Retain the entry as a Config so change in place 

90 disassemblyMap = self.config[DISASSEMBLY_KEY] 

91 for k in set(disassemblyMap): 

92 if k.startswith("__"): 

93 del disassemblyMap[k] 

94 

95 # Calculate the disassembly lookup table -- no need to process 

96 # the values 

97 self._lut = processLookupConfigs(disassemblyMap, universe=universe) 

98 

99 def shouldBeDisassembled(self, entity: Union[DatasetRef, DatasetType, StorageClass]) -> bool: 

100 """Indicate whether the entity should be disassembled. 

101 

102 Parameters 

103 ---------- 

104 entity : `StorageClass` or `DatasetType` or `DatasetRef` 

105 Thing to test against the configuration. The ``name`` property 

106 is used to determine a match. A `DatasetType` will first check 

107 its name, before checking its `StorageClass`. If there are no 

108 matches the default will be returned. If the associated 

109 `StorageClass` is not a composite, will always return `False`. 

110 

111 Returns 

112 ------- 

113 disassemble : `bool` 

114 Returns `True` if disassembly should occur; `False` otherwise. 

115 

116 Raises 

117 ------ 

118 ValueError 

119 The supplied argument is not understood. 

120 """ 

121 if not hasattr(entity, "isComposite"): 

122 raise ValueError(f"Supplied entity ({entity}) is not understood.") 

123 

124 # If this is not a composite there is nothing to disassemble. 

125 if not entity.isComposite(): 

126 log.debug("%s will not be disassembled (not a composite)", entity) 

127 return False 

128 

129 matchName: Union[LookupKey, str] = "{} (via default)".format(entity) 

130 disassemble = self.config["default"] 

131 

132 for key in entity._lookupNames(): 

133 if key in self._lut: 

134 disassemble = self._lut[key] 

135 matchName = key 

136 break 

137 

138 if not isinstance(disassemble, bool): 

139 raise TypeError( 

140 f"Got disassemble value {disassemble!r} for config entry {matchName!r}; expected bool." 

141 ) 

142 

143 log.debug("%s will%s be disassembled", matchName, "" if disassemble else " not") 

144 return disassemble 

145 

146 def __str__(self) -> str: 

147 result = {} 

148 result["default"] = self.config["default"] 

149 result["disassembled"] = {} 

150 for key in self._lut: 

151 result["disassembled"][str(key)] = self._lut[key] 

152 return yaml.dump(result)