Debian Codegraph @

pint/facets/context/definitions.py

raw
1 """
2 pint.facets.context.definitions
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 import itertools
12 import numbers
13 import re
14 from collections.abc import Callable, Iterable
15 from dataclasses import dataclass
16 from typing import TYPE_CHECKING
17
18 from ... import errors
19 from ..plain import UnitDefinition
20
21 if TYPE_CHECKING:
22 from ..._typing import Quantity, UnitsContainer
23
24
25 @dataclass(frozen=True)
26 class Relation:
27 """Base class for a relation between different dimensionalities."""
28
29 _varname_re = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
30
31 #: Source dimensionality
32 src: UnitsContainer
33 #: Destination dimensionality
34 dst: UnitsContainer
35 #: Equation connecting both dimensionalities from which the tranformation
36 #: will be built.
37 equation: str
38
39 # Instead of defining __post_init__ here,
40 # it will be added to the container class
41 # so that the name and a meaningfull class
42 # could be used.
43
44 @property
45 def variables(self) -> set[str]:
46 """Find all variables names in the equation."""
47 return set(self._varname_re.findall(self.equation))
48
49 @property
50 def transformation(self) -> Callable[..., Quantity]:
51 """Return a transformation callable that uses the registry
52 to parse the transformation equation.
53 """
54 return lambda ureg, value, **kwargs: ureg.parse_expression(
55 self.equation, value=value, **kwargs
56 )
57
58 @property
59 def bidirectional(self) -> bool:
60 raise NotImplementedError
61
62
63 @dataclass(frozen=True)
64 class ForwardRelation(Relation):
65 """A relation connecting a dimension to another via a transformation function.
66
67 <source dimension> -> <target dimension>: <transformation function>
68 """
69
70 @property
71 def bidirectional(self) -> bool:
72 return False
73
74
75 @dataclass(frozen=True)
76 class BidirectionalRelation(Relation):
77 """A bidirectional relation connecting a dimension to another
78 via a simple transformation function.
79
80 <source dimension> <-> <target dimension>: <transformation function>
81
82 """
83
84 @property
85 def bidirectional(self) -> bool:
86 return True
87
88
89 @dataclass(frozen=True)
90 class ContextDefinition(errors.WithDefErr):
91 """Definition of a Context"""
92
93 #: name of the context
94 name: str
95 #: other na
96 aliases: tuple[str, ...]
97 defaults: dict[str, numbers.Number]
98 relations: tuple[Relation, ...]
99 redefinitions: tuple[UnitDefinition, ...]
100
101 @property
102 def variables(self) -> set[str]:
103 """Return all variable names in all transformations."""
104 return set().union(*(r.variables for r in self.relations))
105
106 @classmethod
107 def from_lines(cls, lines: Iterable[str], non_int_type: type):
108 # TODO: this is to keep it backwards compatible
109 from ...delegates import ParserConfig, txt_defparser
110
111 cfg = ParserConfig(non_int_type)
112 parser = txt_defparser.DefParser(cfg, None)
113 pp = parser.parse_string("\n".join(lines) + "\n@end")
114 for definition in parser.iter_parsed_project(pp):
115 if isinstance(definition, cls):
116 return definition
117
118 def __post_init__(self):
119 if not errors.is_valid_context_name(self.name):
120 raise self.def_err(errors.MSG_INVALID_GROUP_NAME)
121
122 for k in self.aliases:
123 if not errors.is_valid_context_name(k):
124 raise self.def_err(
125 f"refers to '{k}' that " + errors.MSG_INVALID_CONTEXT_NAME
126 )
127
128 for relation in self.relations:
129 invalid = tuple(
130 itertools.filterfalse(
131 errors.is_valid_dimension_name, relation.src.keys()
132 )
133 ) + tuple(
134 itertools.filterfalse(
135 errors.is_valid_dimension_name, relation.dst.keys()
136 )
137 )
138
139 if invalid:
140 raise self.def_err(
141 f"relation refers to {', '.join(invalid)} that "
142 + errors.MSG_INVALID_DIMENSION_NAME
143 )
144
145 for definition in self.redefinitions:
146 if definition.symbol != definition.name or definition.aliases:
147 raise self.def_err(
148 "can't change a unit's symbol or aliases within a context"
149 )
150 if definition.is_base:
151 raise self.def_err("can't define plain units within a context")
152
153 missing_pars = set(self.defaults.keys()) - self.variables
154 if missing_pars:
155 raise self.def_err(
156 f"Context parameters {missing_pars} not found in any equation"
157 )