|
| 1 | +"""Generic metadata system for BayBE objects.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import Any, TypeVar |
| 6 | + |
| 7 | +import cattrs |
| 8 | +from attrs import AttrsInstance, define, field, fields |
| 9 | +from attrs.validators import deep_mapping, instance_of |
| 10 | +from attrs.validators import optional as optional_v |
| 11 | +from typing_extensions import override |
| 12 | + |
| 13 | +from baybe.serialization import SerialMixin, converter |
| 14 | +from baybe.utils.basic import classproperty |
| 15 | + |
| 16 | +_TMetaData = TypeVar("_TMetaData", bound="Metadata") |
| 17 | + |
| 18 | + |
| 19 | +@define(frozen=True) |
| 20 | +class Metadata(SerialMixin): |
| 21 | + """Metadata class providing basic information for BayBE objects.""" |
| 22 | + |
| 23 | + description: str | None = field( |
| 24 | + default=None, validator=optional_v(instance_of(str)) |
| 25 | + ) |
| 26 | + """A description of the object.""" |
| 27 | + |
| 28 | + misc: dict[str, Any] = field( |
| 29 | + factory=dict, |
| 30 | + validator=deep_mapping( |
| 31 | + mapping_validator=instance_of(dict), |
| 32 | + key_validator=instance_of(str), |
| 33 | + # FIXME: https://github.com/python-attrs/attrs/issues/1246 |
| 34 | + value_validator=lambda *x: None, |
| 35 | + ), |
| 36 | + kw_only=True, |
| 37 | + ) |
| 38 | + """Additional user-defined metadata.""" |
| 39 | + |
| 40 | + @misc.validator |
| 41 | + def _validate_misc(self, _, value: dict[str, Any]) -> None: |
| 42 | + if inv := set(value).intersection(self._explicit_fields): |
| 43 | + raise ValueError( |
| 44 | + f"Miscellaneous metadata cannot contain the following fields: {inv}. " |
| 45 | + f"Use the corresponding attributes instead." |
| 46 | + ) |
| 47 | + |
| 48 | + @classproperty |
| 49 | + def _explicit_fields(cls: type[AttrsInstance]) -> set[str]: |
| 50 | + """The explicit metadata fields.""" # noqa: D401 |
| 51 | + flds = fields(cls) |
| 52 | + return {fld.name for fld in flds if fld.name != flds.misc.name} |
| 53 | + |
| 54 | + @property |
| 55 | + def is_empty(self) -> bool: |
| 56 | + """Check if metadata contains any meaningful information.""" |
| 57 | + return self.description is None and not self.misc |
| 58 | + |
| 59 | + |
| 60 | +@define(frozen=True) |
| 61 | +class MeasurableMetadata(Metadata): |
| 62 | + """Class providing metadata for BayBE :class:`Parameter` objects.""" |
| 63 | + |
| 64 | + unit: str | None = field(default=None, validator=optional_v(instance_of(str))) |
| 65 | + """The unit of measurement for the parameter.""" |
| 66 | + |
| 67 | + @override |
| 68 | + @property |
| 69 | + def is_empty(self) -> bool: |
| 70 | + """Check if metadata contains any meaningful information.""" |
| 71 | + return super().is_empty and self.unit is None |
| 72 | + |
| 73 | + |
| 74 | +def to_metadata( |
| 75 | + value: dict[str, Any] | _TMetaData, cls: type[_TMetaData], / |
| 76 | +) -> _TMetaData: |
| 77 | + """Convert a dictionary to :class:`Metadata` (with :class:`Metadata` passthrough). |
| 78 | +
|
| 79 | + Args: |
| 80 | + value: The metadata input. |
| 81 | + cls: The specific :class:`Metadata` subclass to convert to. |
| 82 | +
|
| 83 | + Returns: |
| 84 | + The created metadata instance of the requested :class:`Metadata` subclass. |
| 85 | +
|
| 86 | + Raises: |
| 87 | + TypeError: If the input is not a dictionary or of the specified |
| 88 | + :class:`Metadata` type. |
| 89 | + """ |
| 90 | + if isinstance(value, cls): |
| 91 | + return value |
| 92 | + |
| 93 | + if not isinstance(value, dict): |
| 94 | + raise TypeError( |
| 95 | + f"The input must be a dictionary or a '{cls.__name__}' instance. " |
| 96 | + f"Got: {type(value)}" |
| 97 | + ) |
| 98 | + |
| 99 | + # Separate known fields from unknown ones |
| 100 | + return converter.structure(value, cls) |
| 101 | + |
| 102 | + |
| 103 | +@converter.register_structure_hook |
| 104 | +def _separate_metadata_fields(dct: dict[str, Any], cls: type[Metadata]) -> Metadata: |
| 105 | + """Separate known fields from miscellaneous metadata.""" |
| 106 | + dct = dct.copy() |
| 107 | + explicit = {fld: dct.pop(fld, None) for fld in cls._explicit_fields} |
| 108 | + return cls(**explicit, misc=dct) |
| 109 | + |
| 110 | + |
| 111 | +@converter.register_unstructure_hook |
| 112 | +def _flatten_misc_metadata(metadata: Metadata) -> dict[str, Any]: |
| 113 | + """Flatten the metadata for serialization.""" |
| 114 | + cls = type(metadata) |
| 115 | + fn = cattrs.gen.make_dict_unstructure_fn(cls, converter) |
| 116 | + dct = fn(metadata) |
| 117 | + dct = dct | dct.pop(fields(Metadata).misc.name) |
| 118 | + return dct |
0 commit comments