Coverage for python/lsst/daf/butler/core/composites.py: 25%
54 statements
« prev ^ index » next coverage.py v7.3.1, created at 2023-10-02 08:00 +0000
« prev ^ index » next coverage.py v7.3.1, created at 2023-10-02 08:00 +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 software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
28"""Support for reading and writing composite objects."""
30from __future__ import annotations
32__all__ = ("CompositesConfig", "CompositesMap")
34import logging
35from typing import TYPE_CHECKING
37import yaml
39from .config import ConfigSubset
40from .configSupport import processLookupConfigs
42if TYPE_CHECKING:
43 from lsst.resources import ResourcePathExpression
45 from .._butlerConfig import ButlerConfig
46 from .configSupport import LookupKey
47 from .datasets import DatasetRef, DatasetType
48 from .dimensions import DimensionUniverse
49 from .storageClass import StorageClass
51log = logging.getLogger(__name__)
53# Key to access disassembly information
54DISASSEMBLY_KEY = "disassembled"
57class CompositesConfig(ConfigSubset):
58 """Configuration specifics for Composites."""
60 component = "composites"
61 requiredKeys = ("default", DISASSEMBLY_KEY)
62 defaultConfigFile = "datastores/composites.yaml"
64 def validate(self) -> None:
65 """Validate entries have the correct type."""
66 super().validate()
67 # For now assume flat config with keys mapping to booleans
68 for k, v in self[DISASSEMBLY_KEY].items():
69 if not isinstance(v, bool):
70 raise ValueError(f"CompositesConfig: Key {k} is not a Boolean")
73class CompositesMap:
74 """Determine whether something should be disassembled.
76 Compares a `DatasetType` or `StorageClass` with the map and determines
77 whether disassembly is requested.
79 Parameters
80 ----------
81 config : `str`, `ButlerConfig`, or `CompositesConfig`
82 Configuration to control composites disassembly.
83 universe : `DimensionUniverse`
84 Set of all known dimensions, used to expand and validate any used
85 in lookup keys.
86 """
88 def __init__(
89 self, config: ResourcePathExpression | ButlerConfig | CompositesConfig, *, universe: DimensionUniverse
90 ):
91 if not isinstance(config, CompositesConfig):
92 config = CompositesConfig(config)
93 assert isinstance(config, CompositesConfig)
94 self.config = config
96 # Pre-filter the disassembly lookup table to remove the
97 # placeholder __ key we added for documentation.
98 # It should be harmless but might confuse validation
99 # Retain the entry as a Config so change in place
100 disassemblyMap = self.config[DISASSEMBLY_KEY]
101 for k in set(disassemblyMap):
102 if k.startswith("__"):
103 del disassemblyMap[k]
105 # Calculate the disassembly lookup table -- no need to process
106 # the values
107 self._lut = processLookupConfigs(disassemblyMap, universe=universe)
109 def shouldBeDisassembled(self, entity: DatasetRef | DatasetType | StorageClass) -> bool:
110 """Indicate whether the entity should be disassembled.
112 Parameters
113 ----------
114 entity : `StorageClass` or `DatasetType` or `DatasetRef`
115 Thing to test against the configuration. The ``name`` property
116 is used to determine a match. A `DatasetType` will first check
117 its name, before checking its `StorageClass`. If there are no
118 matches the default will be returned. If the associated
119 `StorageClass` is not a composite, will always return `False`.
121 Returns
122 -------
123 disassemble : `bool`
124 Returns `True` if disassembly should occur; `False` otherwise.
126 Raises
127 ------
128 ValueError
129 The supplied argument is not understood.
130 """
131 if not hasattr(entity, "isComposite"):
132 raise ValueError(f"Supplied entity ({entity}) is not understood.")
134 # If this is not a composite there is nothing to disassemble.
135 if not entity.isComposite():
136 log.debug("%s will not be disassembled (not a composite)", entity)
137 return False
139 matchName: LookupKey | str = f"{entity} (via default)"
140 disassemble = self.config["default"]
142 for key in entity._lookupNames():
143 if key in self._lut:
144 disassemble = self._lut[key]
145 matchName = key
146 break
148 if not isinstance(disassemble, bool):
149 raise TypeError(
150 f"Got disassemble value {disassemble!r} for config entry {matchName!r}; expected bool."
151 )
153 log.debug("%s will%s be disassembled", matchName, "" if disassemble else " not")
154 return disassemble
156 def __str__(self) -> str:
157 result = {}
158 result["default"] = self.config["default"]
159 result["disassembled"] = {}
160 for key in self._lut:
161 result["disassembled"][str(key)] = self._lut[key]
162 return yaml.dump(result)