Coverage for python/lsst/daf/butler/core/dimensions/_records.py: 24%
161 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-08-12 09:20 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-08-12 09:20 +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/>.
22from __future__ import annotations
24__all__ = ("DimensionRecord", "SerializedDimensionRecord")
26from collections.abc import Hashable
27from typing import TYPE_CHECKING, Any, ClassVar, Optional, Tuple
29import lsst.sphgeom
30from lsst.daf.butler._compat import PYDANTIC_V2, _BaseModelCompat
31from lsst.utils.classes import immutable
32from pydantic import Field, StrictBool, StrictFloat, StrictInt, StrictStr, create_model
34from ..json import from_json_pydantic, to_json_pydantic
35from ..persistenceContext import PersistenceContextVars
36from ..timespan import Timespan, TimespanDatabaseRepresentation
37from ._elements import Dimension, DimensionElement
39if TYPE_CHECKING: # Imports needed only for type annotations; may be circular.
40 from ...registry import Registry
41 from ._coordinate import DataCoordinate
42 from ._graph import DimensionUniverse
43 from ._schema import DimensionElementFields
46def _reconstructDimensionRecord(definition: DimensionElement, mapping: dict[str, Any]) -> DimensionRecord:
47 """Unpickle implementation for `DimensionRecord` subclasses.
49 For internal use by `DimensionRecord`.
50 """
51 return definition.RecordClass(**mapping)
54def _subclassDimensionRecord(definition: DimensionElement) -> type[DimensionRecord]:
55 """Create a dynamic subclass of `DimensionRecord` for the given element.
57 For internal use by `DimensionRecord`.
58 """
59 from ._schema import DimensionElementFields
61 fields = DimensionElementFields(definition)
62 slots = list(fields.standard.names)
63 if definition.spatial:
64 slots.append("region")
65 if definition.temporal:
66 slots.append(TimespanDatabaseRepresentation.NAME)
67 d = {"definition": definition, "__slots__": tuple(slots), "fields": fields}
68 return type(definition.name + ".RecordClass", (DimensionRecord,), d)
71class SpecificSerializedDimensionRecord(_BaseModelCompat, extra="forbid"):
72 """Base model for a specific serialized record content."""
75_SIMPLE_RECORD_CLASS_CACHE: dict[
76 tuple[DimensionElement, DimensionUniverse], type[SpecificSerializedDimensionRecord]
77] = {}
80def _createSimpleRecordSubclass(definition: DimensionElement) -> type[SpecificSerializedDimensionRecord]:
81 from ._schema import DimensionElementFields
83 # Cache on the definition (which hashes as the name) and the
84 # associated universe.
85 cache_key = (definition, definition.universe)
86 if cache_key in _SIMPLE_RECORD_CLASS_CACHE:
87 return _SIMPLE_RECORD_CLASS_CACHE[cache_key]
89 fields = DimensionElementFields(definition)
90 members = {}
91 # Prefer strict typing for external data
92 type_map = {
93 str: StrictStr,
94 float: StrictFloat,
95 bool: StrictBool,
96 int: StrictInt,
97 }
99 for field in fields.standard:
100 field_type = field.getPythonType()
101 field_type = type_map.get(field_type, field_type)
102 if field.nullable:
103 field_type = Optional[field_type] # type: ignore
104 members[field.name] = (field_type, ...)
105 if definition.temporal:
106 members["timespan"] = (Tuple[int, int], ...) # type: ignore
107 if definition.spatial:
108 members["region"] = (str, ...)
110 # mypy does not seem to like create_model
111 model = create_model(
112 f"SpecificSerializedDimensionRecord{definition.name.capitalize()}",
113 __base__=SpecificSerializedDimensionRecord,
114 **members, # type: ignore
115 )
117 _SIMPLE_RECORD_CLASS_CACHE[cache_key] = model
118 return model
121# While supporting pydantic v1 and v2 keep this outside the model.
122_serialized_dimension_record_schema_extra = {
123 "examples": [
124 {
125 "definition": "detector",
126 "record": {
127 "instrument": "HSC",
128 "id": 72,
129 "full_name": "0_01",
130 "name_in_raft": "01",
131 "raft": "0",
132 "purpose": "SCIENCE",
133 },
134 }
135 ]
136}
139class SerializedDimensionRecord(_BaseModelCompat):
140 """Simplified model for serializing a `DimensionRecord`."""
142 definition: str = Field(
143 ...,
144 title="Name of dimension associated with this record.",
145 examples=["exposure"],
146 )
148 # Use strict types to prevent casting
149 record: dict[str, None | StrictFloat | StrictStr | StrictBool | StrictInt | tuple[int, int]] = Field(
150 ...,
151 title="Dimension record keys and values.",
152 examples=[
153 {
154 "definition": "exposure",
155 "record": {
156 "instrument": "LATISS",
157 "exposure": 2021050300044,
158 "obs_id": "AT_O_20210503_00044",
159 },
160 }
161 ],
162 )
164 if PYDANTIC_V2: 164 ↛ 165line 164 didn't jump to line 165
165 model_config = {
166 "json_schema_extra": _serialized_dimension_record_schema_extra, # type: ignore[typeddict-item]
167 }
168 else:
170 class Config:
171 """Local configuration overrides for model."""
173 schema_extra = _serialized_dimension_record_schema_extra
175 @classmethod
176 def direct(
177 cls,
178 *,
179 definition: str,
180 record: dict[str, None | StrictFloat | StrictStr | StrictBool | StrictInt | tuple[int, int]],
181 ) -> SerializedDimensionRecord:
182 """Construct a `SerializedDimensionRecord` directly without validators.
184 This differs from the pydantic "construct" method in that the arguments
185 are explicitly what the model requires, and it will recurse through
186 members, constructing them from their corresponding `direct` methods.
188 This method should only be called when the inputs are trusted.
189 """
190 # This method requires tuples as values of the mapping, but JSON
191 # readers will read things in as lists. Be kind and transparently
192 # transform to tuples
193 _recItems = {k: v if type(v) != list else tuple(v) for k, v in record.items()} # type: ignore
195 # Type ignore because the ternary statement seems to confuse mypy
196 # based on conflicting inferred types of v.
197 key = (
198 definition,
199 frozenset(_recItems.items()),
200 )
201 cache = PersistenceContextVars.serializedDimensionRecordMapping.get()
202 if cache is not None and (result := cache.get(key)) is not None:
203 return result
205 node = cls.model_construct(definition=definition, record=_recItems) # type: ignore
207 if cache is not None:
208 cache[key] = node
209 return node
212@immutable
213class DimensionRecord:
214 """Base class for the Python representation of database records.
216 Parameters
217 ----------
218 **kwargs
219 Field values for this record. Unrecognized keys are ignored. If this
220 is the record for a `Dimension`, its primary key value may be provided
221 with the actual name of the field (e.g. "id" or "name"), the name of
222 the `Dimension`, or both. If this record class has a "timespan"
223 attribute, "datetime_begin" and "datetime_end" keyword arguments may
224 be provided instead of a single "timespan" keyword argument (but are
225 ignored if a "timespan" argument is provided).
227 Notes
228 -----
229 `DimensionRecord` subclasses are created dynamically for each
230 `DimensionElement` in a `DimensionUniverse`, and are accessible via the
231 `DimensionElement.RecordClass` attribute. The `DimensionRecord` base class
232 itself is pure abstract, but does not use the `abc` module to indicate this
233 because it does not have overridable methods.
235 Record classes have attributes that correspond exactly to the
236 `~DimensionElementFields.standard` fields in the related database table,
237 plus "region" and "timespan" attributes for spatial and/or temporal
238 elements (respectively).
240 Instances are usually obtained from a `Registry`, but can be constructed
241 directly from Python as well.
243 `DimensionRecord` instances are immutable.
244 """
246 # Derived classes are required to define __slots__ as well, and it's those
247 # derived-class slots that other methods on the base class expect to see
248 # when they access self.__slots__.
249 __slots__ = ("dataId",)
251 _serializedType = SerializedDimensionRecord
253 def __init__(self, **kwargs: Any):
254 # Accept either the dimension name or the actual name of its primary
255 # key field; ensure both are present in the dict for convenience below.
256 if isinstance(self.definition, Dimension):
257 v = kwargs.get(self.definition.primaryKey.name)
258 if v is None:
259 v = kwargs.get(self.definition.name)
260 if v is None:
261 raise ValueError(
262 f"No value provided for {self.definition.name}.{self.definition.primaryKey.name}."
263 )
264 kwargs[self.definition.primaryKey.name] = v
265 else:
266 v2 = kwargs.setdefault(self.definition.name, v)
267 if v != v2:
268 raise ValueError(
269 "Multiple inconsistent values for "
270 f"{self.definition.name}.{self.definition.primaryKey.name}: {v!r} != {v2!r}."
271 )
272 for name in self.__slots__:
273 object.__setattr__(self, name, kwargs.get(name))
274 if self.definition.temporal is not None and self.timespan is None:
275 object.__setattr__(
276 self,
277 "timespan",
278 Timespan(
279 kwargs.get("datetime_begin"),
280 kwargs.get("datetime_end"),
281 ),
282 )
284 from ._coordinate import DataCoordinate
286 object.__setattr__(
287 self,
288 "dataId",
289 DataCoordinate.fromRequiredValues(
290 self.definition.graph,
291 tuple(kwargs[dimension] for dimension in self.definition.required.names),
292 ),
293 )
295 def __eq__(self, other: Any) -> bool:
296 if type(other) != type(self):
297 return False
298 return self.dataId == other.dataId
300 def __hash__(self) -> int:
301 return hash(self.dataId)
303 def __str__(self) -> str:
304 lines = [f"{self.definition.name}:"]
305 lines.extend(f" {name}: {getattr(self, name)!r}" for name in self.__slots__)
306 return "\n".join(lines)
308 def __repr__(self) -> str:
309 return "{}.RecordClass({})".format(
310 self.definition.name, ", ".join(f"{name}={getattr(self, name)!r}" for name in self.__slots__)
311 )
313 def __reduce__(self) -> tuple:
314 mapping = {name: getattr(self, name) for name in self.__slots__}
315 return (_reconstructDimensionRecord, (self.definition, mapping))
317 def _repr_html_(self) -> str:
318 """Override the default representation in IPython/Jupyter notebooks.
320 This gives a more readable output that understands embedded newlines.
321 """
322 return f"<pre>{self}<pre>"
324 def to_simple(self, minimal: bool = False) -> SerializedDimensionRecord:
325 """Convert this class to a simple python type.
327 This makes it suitable for serialization.
329 Parameters
330 ----------
331 minimal : `bool`, optional
332 Use minimal serialization. Has no effect on for this class.
334 Returns
335 -------
336 names : `list`
337 The names of the dimensions.
338 """
339 # The DataId is sufficient if you are willing to do a deferred
340 # query. This may not be overly useful since to reconstruct
341 # a collection of records will require repeated registry queries.
342 # For now do not implement minimal form.
344 mapping = {name: getattr(self, name) for name in self.__slots__}
345 # If the item in mapping supports simplification update it
346 for k, v in mapping.items():
347 try:
348 mapping[k] = v.to_simple(minimal=minimal)
349 except AttributeError:
350 if isinstance(v, lsst.sphgeom.Region):
351 # YAML serialization specifies the class when it
352 # doesn't have to. This is partly for explicitness
353 # and also history. Here use a different approach.
354 # This code needs to be migrated to sphgeom
355 mapping[k] = v.encode().hex()
356 if isinstance(v, bytes):
357 # We actually can't handle serializing out to bytes for
358 # hash objects, encode it here to a hex string
359 mapping[k] = v.hex()
360 definition = self.definition.to_simple(minimal=minimal)
361 return SerializedDimensionRecord(definition=definition, record=mapping)
363 @classmethod
364 def from_simple(
365 cls,
366 simple: SerializedDimensionRecord,
367 universe: DimensionUniverse | None = None,
368 registry: Registry | None = None,
369 cacheKey: Hashable | None = None,
370 ) -> DimensionRecord:
371 """Construct a new object from the simplified form.
373 This is generally data returned from the `to_simple`
374 method.
376 Parameters
377 ----------
378 simple : `SerializedDimensionRecord`
379 Value return from `to_simple`.
380 universe : `DimensionUniverse`
381 The special graph of all known dimensions of which this graph will
382 be a subset. Can be `None` if `Registry` is provided.
383 registry : `lsst.daf.butler.Registry`, optional
384 Registry from which a universe can be extracted. Can be `None`
385 if universe is provided explicitly.
386 cacheKey : `Hashable` or `None`
387 If this is not None, it will be used as a key for any cached
388 reconstruction instead of calculating a value from the serialized
389 format.
391 Returns
392 -------
393 record : `DimensionRecord`
394 Newly-constructed object.
395 """
396 if universe is None and registry is None:
397 raise ValueError("One of universe or registry is required to convert names to a DimensionGraph")
398 if universe is None and registry is not None:
399 universe = registry.dimensions
400 if universe is None:
401 # this is for mypy
402 raise ValueError("Unable to determine a usable universe")
403 # Type ignore because the ternary statement seems to confuse mypy
404 # based on conflicting inferred types of v.
405 key = cacheKey or (
406 simple.definition,
407 frozenset(simple.record.items()), # type: ignore
408 )
409 cache = PersistenceContextVars.dimensionRecords.get()
410 if cache is not None and (result := cache.get(key)) is not None:
411 return result
413 definition = DimensionElement.from_simple(simple.definition, universe=universe)
415 # Create a specialist subclass model with type validation.
416 # This allows us to do simple checks of external data (possibly
417 # sent as JSON) since for now _reconstructDimensionRecord does not
418 # do any validation.
419 record_model_cls = _createSimpleRecordSubclass(definition)
420 record_model = record_model_cls(**simple.record)
422 # Timespan and region have to be converted to native form
423 # for now assume that those keys are special
424 rec = record_model.model_dump()
426 if (ts := "timespan") in rec:
427 rec[ts] = Timespan.from_simple(rec[ts], universe=universe, registry=registry)
428 if (reg := "region") in rec:
429 encoded = bytes.fromhex(rec[reg])
430 rec[reg] = lsst.sphgeom.Region.decode(encoded)
431 if (hsh := "hash") in rec:
432 rec[hsh] = bytes.fromhex(rec[hsh].decode())
434 dimRec = _reconstructDimensionRecord(definition, rec)
435 if cache is not None:
436 cache[key] = dimRec
437 return dimRec
439 to_json = to_json_pydantic
440 from_json: ClassVar = classmethod(from_json_pydantic)
442 def toDict(self, splitTimespan: bool = False) -> dict[str, Any]:
443 """Return a vanilla `dict` representation of this record.
445 Parameters
446 ----------
447 splitTimespan : `bool`, optional
448 If `True` (`False` is default) transform any "timespan" key value
449 from a `Timespan` instance into a pair of regular
450 ("datetime_begin", "datetime_end") fields.
451 """
452 results = {name: getattr(self, name) for name in self.__slots__}
453 if splitTimespan:
454 timespan = results.pop("timespan", None)
455 if timespan is not None:
456 results["datetime_begin"] = timespan.begin
457 results["datetime_end"] = timespan.end
458 return results
460 # DimensionRecord subclasses are dynamically created, so static type
461 # checkers can't know about them or their attributes. To avoid having to
462 # put "type: ignore", everywhere, add a dummy __getattr__ that tells type
463 # checkers not to worry about missing attributes.
464 def __getattr__(self, name: str) -> Any:
465 raise AttributeError(name)
467 # Class attributes below are shadowed by instance attributes, and are
468 # present just to hold the docstrings for those instance attributes.
470 dataId: DataCoordinate
471 """A dict-like identifier for this record's primary keys
472 (`DataCoordinate`).
473 """
475 definition: ClassVar[DimensionElement]
476 """The `DimensionElement` whose records this class represents
477 (`DimensionElement`).
478 """
480 fields: ClassVar[DimensionElementFields]
481 """A categorized view of the fields in this class
482 (`DimensionElementFields`).
483 """