Debian Codegraph @

pint/facets/group/objects.py

raw
1 """
2 pint.facets.group.objects
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 collections.abc import Callable, Generator, Iterable
12 from typing import TYPE_CHECKING, Any, Generic
13
14 from ...util import SharedRegistryObject, getattr_maybe_raise
15 from ..plain import MagnitudeT, PlainQuantity, PlainUnit
16 from .definitions import GroupDefinition
17
18 if TYPE_CHECKING:
19 from ..plain import UnitDefinition
20
21 DefineFunc = Callable[
22 [
23 Any,
24 ],
25 None,
26 ]
27 AddUnitFunc = Callable[
28 [
29 UnitDefinition,
30 ],
31 None,
32 ]
33
34
35 class GroupQuantity(Generic[MagnitudeT], PlainQuantity[MagnitudeT]):
36 pass
37
38
39 class GroupUnit(PlainUnit):
40 pass
41
42
43 class Group(SharedRegistryObject):
44 """A group is a set of units.
45
46 Units can be added directly or by including other groups.
47
48 Members are computed dynamically, that is if a unit is added to a group X
49 all groups that include X are affected.
50
51 The group belongs to one Registry.
52
53 See GroupDefinition for the definition file syntax.
54
55 Parameters
56 ----------
57 name
58 If not given, a root Group will be created.
59 """
60
61 def __init__(self, name: str):
62 # The name of the group.
63 self.name = name
64
65 #: Names of the units in this group.
66 #: :type: set[str]
67 self._unit_names: set[str] = set()
68
69 #: Names of the groups in this group.
70 self._used_groups: set[str] = set()
71
72 #: Names of the groups in which this group is contained.
73 self._used_by: set[str] = set()
74
75 # Add this group to the group dictionary
76 self._REGISTRY._groups[self.name] = self
77
78 if name != "root":
79 # All groups are added to root group
80 self._REGISTRY._groups["root"].add_groups(name)
81
82 #: A cache of the included units.
83 #: None indicates that the cache has been invalidated.
84 self._computed_members: frozenset[str] | None = None
85
86 @property
87 def members(self) -> frozenset[str]:
88 """Names of the units that are members of the group.
89
90 Calculated to include to all units in all included _used_groups.
91
92 """
93 if self._computed_members is None:
94 tmp = set(self._unit_names)
95
96 for _, group in self.iter_used_groups():
97 tmp |= group.members
98
99 self._computed_members = frozenset(tmp)
100
101 return self._computed_members
102
103 def invalidate_members(self) -> None:
104 """Invalidate computed members in this Group and all parent nodes."""
105 self._computed_members = None
106 d = self._REGISTRY._groups
107 for name in self._used_by:
108 d[name].invalidate_members()
109
110 def iter_used_groups(self) -> Generator[tuple[str, Group]]:
111 pending = set(self._used_groups)
112 d = self._REGISTRY._groups
113 while pending:
114 name = pending.pop()
115 group = d[name]
116 pending |= group._used_groups
117 yield name, d[name]
118
119 def is_used_group(self, group_name: str) -> bool:
120 for name, _ in self.iter_used_groups():
121 if name == group_name:
122 return True
123 return False
124
125 def add_units(self, *unit_names: str) -> None:
126 """Add units to group."""
127 for unit_name in unit_names:
128 self._unit_names.add(unit_name)
129
130 self.invalidate_members()
131
132 @property
133 def non_inherited_unit_names(self) -> frozenset[str]:
134 return frozenset(self._unit_names)
135
136 def remove_units(self, *unit_names: str) -> None:
137 """Remove units from group."""
138 for unit_name in unit_names:
139 self._unit_names.remove(unit_name)
140
141 self.invalidate_members()
142
143 def add_groups(self, *group_names: str) -> None:
144 """Add groups to group."""
145 d = self._REGISTRY._groups
146 for group_name in group_names:
147 grp = d[group_name]
148
149 if grp.is_used_group(self.name):
150 raise ValueError(
151 "Cyclic relationship found between %s and %s"
152 % (self.name, group_name)
153 )
154
155 self._used_groups.add(group_name)
156 grp._used_by.add(self.name)
157
158 self.invalidate_members()
159
160 def remove_groups(self, *group_names: str) -> None:
161 """Remove groups from group."""
162 d = self._REGISTRY._groups
163 for group_name in group_names:
164 grp = d[group_name]
165
166 self._used_groups.remove(group_name)
167 grp._used_by.remove(self.name)
168
169 self.invalidate_members()
170
171 @classmethod
172 def from_lines(
173 cls, lines: Iterable[str], define_func: DefineFunc, non_int_type: type = float
174 ) -> Group:
175 """Return a Group object parsing an iterable of lines.
176
177 Parameters
178 ----------
179 lines : list[str]
180 iterable
181 define_func : callable
182 Function to define a unit in the registry; it must accept a single string as
183 a parameter.
184
185 Returns
186 -------
187
188 """
189 group_definition = GroupDefinition.from_lines(lines, non_int_type)
190
191 if group_definition is None:
192 raise ValueError(f"Could not define group from {lines}")
193
194 return cls.from_definition(group_definition, define_func)
195
196 @classmethod
197 def from_definition(
198 cls,
199 group_definition: GroupDefinition,
200 add_unit_func: AddUnitFunc | None = None,
201 ) -> Group:
202 grp = cls(group_definition.name)
203
204 add_unit_func = add_unit_func or grp._REGISTRY._add_unit
205
206 # We first add all units defined within the group
207 # to the registry.
208 for definition in group_definition.definitions:
209 add_unit_func(definition)
210
211 # Then we add all units defined within the group
212 # to this group (by name)
213 grp.add_units(*group_definition.unit_names)
214
215 # Finally, we add all grou0ps used by this group
216 # tho this group (by name)
217 if group_definition.using_group_names:
218 grp.add_groups(*group_definition.using_group_names)
219
220 return grp
221
222 def __getattr__(self, item: str):
223 getattr_maybe_raise(self, item)
224 return self._REGISTRY