Debian Codegraph @

pint/facets/group/registry.py

raw
1 """
2 pint.facets.group.registry
3 ~~~~~~~~~~~~~~~~~~~~~~~~~~
4
5 :copyright: 2022 by Pint Authors, see AUTHORS for more details.
6 :license: BSD, see LICENSE for more details.
7 """
8
9 from __future__ import annotations
10
11 from typing import TYPE_CHECKING, Any, Generic
12
13 from ... import errors
14 from ...compat import TypeAlias
15
16 if TYPE_CHECKING:
17 from ..._typing import Unit, UnitsContainer
18
19 from ...util import create_class_with_registry, to_units_container
20 from ..plain import (
21 GenericPlainRegistry,
22 QuantityT,
23 UnitDefinition,
24 UnitT,
25 )
26 from . import objects
27 from .definitions import GroupDefinition
28
29
30 class GenericGroupRegistry(
31 Generic[QuantityT, UnitT], GenericPlainRegistry[QuantityT, UnitT]
32 ):
33 """Handle of Groups.
34
35 Group units
36
37 Capabilities:
38 - Register groups.
39 - Parse @group directive.
40 """
41
42 # TODO: Change this to Group: Group to specify class
43 # and use introspection to get system class as a way
44 # to enjoy typing goodies
45 Group = type[objects.Group]
46
47 def __init__(self, **kwargs):
48 super().__init__(**kwargs)
49 #: Map group name to group.
50 self._groups: dict[str, objects.Group] = {}
51 self._groups["root"] = self.Group("root")
52
53 def _init_dynamic_classes(self) -> None:
54 """Generate subclasses on the fly and attach them to self"""
55 super()._init_dynamic_classes()
56 self.Group = create_class_with_registry(self, objects.Group)
57
58 def _after_init(self) -> None:
59 """Invoked at the end of ``__init__``.
60
61 - Create default group and add all orphan units to it
62 - Set default system
63 """
64 super()._after_init()
65
66 #: Copy units not defined in any group to the default group
67 if "group" in self._defaults:
68 grp = self.get_group(self._defaults["group"], True)
69 group_units = frozenset(
70 [
71 member
72 for group in self._groups.values()
73 if group.name != "root"
74 for member in group.members
75 ]
76 )
77 all_units = self.get_group("root", False).members
78 grp.add_units(*(all_units - group_units))
79
80 def _register_definition_adders(self) -> None:
81 super()._register_definition_adders()
82 self._register_adder(GroupDefinition, self._add_group)
83
84 def _add_unit(self, definition: UnitDefinition):
85 super()._add_unit(definition)
86 # TODO: delta units are missing
87 self.get_group("root").add_units(definition.name)
88
89 def _add_group(self, gd: GroupDefinition):
90 if gd.name in self._groups:
91 raise ValueError(f"Group {gd.name} already present in registry")
92 try:
93 # As a Group is a SharedRegistryObject
94 # it adds itself to the registry.
95 self.Group.from_definition(gd)
96 except KeyError as e:
97 raise errors.DefinitionSyntaxError(f"unknown dimension {e} in context")
98
99 def get_group(self, name: str, create_if_needed: bool = True) -> objects.Group:
100 """Return a Group.
101
102 Parameters
103 ----------
104 name : str
105 Name of the group to be
106 create_if_needed : bool
107 If True, create a group if not found. If False, raise an Exception.
108 (Default value = True)
109
110 Returns
111 -------
112 Group
113 Group
114 """
115 if name in self._groups:
116 return self._groups[name]
117
118 if not create_if_needed:
119 raise ValueError("Unknown group %s" % name)
120
121 return self.Group(name)
122
123 def get_compatible_units(
124 self, input_units: UnitsContainer, group: str | None = None
125 ) -> frozenset[Unit]:
126 """ """
127 if group is None:
128 return super().get_compatible_units(input_units)
129
130 input_units = to_units_container(input_units)
131
132 equiv = self._get_compatible_units(input_units, group)
133
134 return frozenset(self.Unit(eq) for eq in equiv)
135
136 def _get_compatible_units(
137 self, input_units: UnitsContainer, group: str | None = None
138 ) -> frozenset[str]:
139 ret = super()._get_compatible_units(input_units)
140
141 if not group:
142 return ret
143
144 if group in self._groups:
145 members = self._groups[group].members
146 else:
147 raise ValueError("Unknown Group with name '%s'" % group)
148 return frozenset(ret & members)
149
150
151 class GroupRegistry(
152 GenericGroupRegistry[objects.GroupQuantity[Any], objects.GroupUnit]
153 ):
154 Quantity: TypeAlias = objects.GroupQuantity[Any]
155 Unit: TypeAlias = objects.GroupUnit