Coverage for python/lsst/daf/butler/registry/_defaults.py: 28%

55 statements  

« prev     ^ index     » next       coverage.py v7.5.0, created at 2024-04-26 02:47 -0700

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

27 

28from __future__ import annotations 

29 

30__all__ = ("RegistryDefaults",) 

31 

32import contextlib 

33from collections.abc import Sequence, Set 

34from typing import TYPE_CHECKING, Any 

35 

36from lsst.utils.classes import immutable 

37 

38from .._exceptions import MissingCollectionError 

39from ..dimensions import DataCoordinate 

40from ._collection_summary import CollectionSummary 

41from .wildcards import CollectionWildcard 

42 

43if TYPE_CHECKING: 

44 from ..registry import Registry 

45 from .sql_registry import SqlRegistry 

46 

47 

48@immutable 

49class RegistryDefaults: 

50 """A struct used to provide the default collections searched or written to 

51 by a `Registry` or `Butler` instance. 

52 

53 Parameters 

54 ---------- 

55 collections : `str` or `~collections.abc.Iterable` [ `str` ], optional 

56 An expression specifying the collections to be searched (in order) when 

57 reading datasets. If a default value for a governor dimension is not 

58 given via ``**kwargs``, and exactly one value for that dimension 

59 appears in the datasets in ``collections``, that value is also used as 

60 the default for that dimension. 

61 This may be a `str` collection name or an iterable thereof. 

62 See :ref:`daf_butler_collection_expressions` for more information. 

63 These collections are not registered automatically and must be 

64 manually registered before they are used by any `Registry` or `Butler` 

65 method, but they may be manually registered after a `Registry` or 

66 `Butler` is initialized with this struct. 

67 run : `str`, optional 

68 Name of the `~CollectionType.RUN` collection new datasets should be 

69 inserted into. If ``collections`` is `None` and ``run`` is not `None`, 

70 ``collections`` will be set to ``[run]``. If not `None`, this 

71 collection will automatically be registered when the default struct is 

72 attached to a `Registry` instance. 

73 infer : `bool`, optional 

74 If `True` (default) infer default data ID values from the values 

75 present in the datasets in ``collections``: if all collections have the 

76 same value (or no value) for a governor dimension, that value will be 

77 the default for that dimension. Nonexistent collections are ignored. 

78 If a default value is provided explicitly for a governor dimension via 

79 ``**kwargs``, no default will be inferred for that dimension. 

80 **kwargs : `str` 

81 Default data ID key-value pairs. These may only identify "governor" 

82 dimensions like ``instrument`` and ``skymap``, though this is only 

83 checked when the defaults struct is actually attached to a `Registry`. 

84 """ 

85 

86 def __init__(self, collections: Any = None, run: str | None = None, infer: bool = True, **kwargs: str): 

87 if collections is None: 

88 if run is not None: 

89 collections = (run,) 

90 else: 

91 collections = () 

92 self.collections = CollectionWildcard.from_expression(collections).require_ordered() 

93 self.run = run 

94 self._infer = infer 

95 self._kwargs = kwargs 

96 

97 def __repr__(self) -> str: 

98 collections = f"collections={self.collections!r}" if self.collections else "" 

99 run = f"run={self.run!r}" if self.run else "" 

100 if self._kwargs: 

101 kwargs = ", ".join([f"{k}={v!r}" for k, v in self._kwargs.items()]) 

102 else: 

103 kwargs = "" 

104 args = ", ".join([arg for arg in (collections, run, kwargs) if arg]) 

105 return f"{type(self).__name__}({args})" 

106 

107 def finish(self, registry: Registry | SqlRegistry) -> None: 

108 """Validate the defaults struct and standardize its data ID. 

109 

110 This should be called only by a `Registry` instance when the defaults 

111 struct is first associated with it. 

112 

113 Parameters 

114 ---------- 

115 registry : `Registry` 

116 Registry instance these defaults are being attached to. 

117 

118 Raises 

119 ------ 

120 TypeError 

121 Raised if a non-governor dimension was included in ``**kwargs`` 

122 at construction. 

123 """ 

124 # Skip re-initialization if it's already been completed. 

125 # Can't just say 'self._finished' because this class is immutable. 

126 if hasattr(self, "_finished"): 

127 return 

128 

129 allGovernorDimensions = registry.dimensions.governor_dimensions 

130 if not self._kwargs.keys() <= allGovernorDimensions.names: 

131 raise TypeError( 

132 "Only governor dimensions may be identified by a default data " 

133 f"ID, not {self._kwargs.keys() - allGovernorDimensions.names}. " 

134 "(These may just be unrecognized keyword arguments passed at " 

135 "Butler construction.)" 

136 ) 

137 if self._infer and self._kwargs.keys() != allGovernorDimensions.names: 

138 summaries = [] 

139 for collection in self.collections: 

140 with contextlib.suppress(MissingCollectionError): 

141 summaries.append(registry.getCollectionSummary(collection)) 

142 

143 if summaries: 

144 summary = CollectionSummary.union(*summaries) 

145 for dimensionName in allGovernorDimensions.names - self._kwargs.keys(): 

146 values: Set[str] = summary.governors.get(dimensionName, frozenset()) 

147 if len(values) == 1: 

148 (value,) = values 

149 self._kwargs[dimensionName] = value 

150 self.dataId = registry.expandDataId(self._kwargs, withDefaults=False) 

151 

152 self._finished = True 

153 

154 collections: Sequence[str] 

155 """The collections to search by default, in order 

156 (`~collections.abc.Sequence` [ `str` ]). 

157 """ 

158 

159 run: str | None 

160 """Name of the run this butler writes outputs to by default (`str` or 

161 `None`). 

162 """ 

163 

164 dataId: DataCoordinate 

165 """The default data ID (`DataCoordinate`). 

166 

167 Dimensions without defaults are simply not included. Only governor 

168 dimensions are ever included in defaults. 

169 

170 This attribute may not be accessed before the defaults struct is 

171 attached to a `Registry` instance. It always satisfies both ``hasFull`` 

172 and ``hasRecords``. 

173 """