summaryrefslogtreecommitdiff
path: root/pint/facets/plain/definitions.py
blob: 79a44f1b324e2b0b6ddb1484709a6c0e78ca95a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
"""
    pint.facets.plain.definitions
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    :copyright: 2022 by Pint Authors, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""

from __future__ import annotations

import itertools
import numbers
import typing as ty
from dataclasses import dataclass
from functools import cached_property
from typing import Callable, Any

from ..._typing import Magnitude
from ... import errors
from ...converters import Converter
from ...util import UnitsContainer


class NotNumeric(Exception):
    """Internal exception. Do not expose outside Pint"""

    def __init__(self, value: Any):
        self.value = value


########################
# Convenience functions
########################


@dataclass(frozen=True)
class Equality:
    """An equality statement contains a left and right hand separated
    by and equal (=) sign.

        lhs = rhs

    lhs and rhs are space stripped.
    """

    lhs: str
    rhs: str


@dataclass(frozen=True)
class CommentDefinition:
    """A comment"""

    comment: str


@dataclass(frozen=True)
class DefaultsDefinition:
    """Directive to store default values."""

    group: ty.Optional[str]
    system: ty.Optional[str]

    def items(self):
        if self.group is not None:
            yield "group", self.group
        if self.system is not None:
            yield "system", self.system


@dataclass(frozen=True)
class PrefixDefinition(errors.WithDefErr):
    """Definition of a prefix."""

    #: name of the prefix
    name: str
    #: scaling value for this prefix
    value: numbers.Number
    #: canonical symbol
    defined_symbol: str | None = ""
    #: additional names for the same prefix
    aliases: ty.Tuple[str, ...] = ()

    @property
    def symbol(self) -> str:
        return self.defined_symbol or self.name

    @property
    def has_symbol(self) -> bool:
        return bool(self.defined_symbol)

    @cached_property
    def converter(self):
        return Converter.from_arguments(scale=self.value)

    def __post_init__(self):
        if not errors.is_valid_prefix_name(self.name):
            raise self.def_err(errors.MSG_INVALID_PREFIX_NAME)

        if self.defined_symbol and not errors.is_valid_prefix_symbol(self.name):
            raise self.def_err(
                f"the symbol {self.defined_symbol} " + errors.MSG_INVALID_PREFIX_SYMBOL
            )

        for alias in self.aliases:
            if not errors.is_valid_prefix_alias(alias):
                raise self.def_err(
                    f"the alias {alias} " + errors.MSG_INVALID_PREFIX_ALIAS
                )


@dataclass(frozen=True)
class UnitDefinition(errors.WithDefErr):
    """Definition of a unit."""

    #: canonical name of the unit
    name: str
    #: canonical symbol
    defined_symbol: str | None
    #: additional names for the same unit
    aliases: tuple[str]
    #: A functiont that converts a value in these units into the reference units
    converter: Callable[
        [
            Magnitude,
        ],
        Magnitude,
    ] | Converter | None
    #: Reference units.
    reference: UnitsContainer | None

    def __post_init__(self):
        if not errors.is_valid_unit_name(self.name):
            raise self.def_err(errors.MSG_INVALID_UNIT_NAME)

        # TODO: check why  reference: UnitsContainer | None
        assert isinstance(self.reference, UnitsContainer)

        if not any(map(errors.is_dim, self.reference.keys())):
            invalid = tuple(
                itertools.filterfalse(errors.is_valid_unit_name, self.reference.keys())
            )
            if invalid:
                raise self.def_err(
                    f"refers to {', '.join(invalid)} that "
                    + errors.MSG_INVALID_UNIT_NAME
                )
            is_base = False

        elif all(map(errors.is_dim, self.reference.keys())):
            invalid = tuple(
                itertools.filterfalse(
                    errors.is_valid_dimension_name, self.reference.keys()
                )
            )
            if invalid:
                raise self.def_err(
                    f"refers to {', '.join(invalid)} that "
                    + errors.MSG_INVALID_DIMENSION_NAME
                )

            is_base = True
            scale = getattr(self.converter, "scale", 1)
            if scale != 1:
                return self.def_err(
                    "Base unit definitions cannot have a scale different to 1. "
                    f"(`{scale}` found)"
                )
        else:
            raise self.def_err(
                "Cannot mix dimensions and units in the same definition. "
                "Base units must be referenced only to dimensions. "
                "Derived units must be referenced only to units."
            )

        super.__setattr__(self, "_is_base", is_base)

        if self.defined_symbol and not errors.is_valid_unit_symbol(self.name):
            raise self.def_err(
                f"the symbol {self.defined_symbol} " + errors.MSG_INVALID_UNIT_SYMBOL
            )

        for alias in self.aliases:
            if not errors.is_valid_unit_alias(alias):
                raise self.def_err(
                    f"the alias {alias} " + errors.MSG_INVALID_UNIT_ALIAS
                )

    @property
    def is_base(self) -> bool:
        """Indicates if it is a base unit."""

        # TODO: why is this here
        return self._is_base

    @property
    def is_multiplicative(self) -> bool:
        # TODO: Check how to avoid this check
        assert isinstance(self.converter, Converter)
        return self.converter.is_multiplicative

    @property
    def is_logarithmic(self) -> bool:
        # TODO: Check how to avoid this check
        assert isinstance(self.converter, Converter)
        return self.converter.is_logarithmic

    @property
    def symbol(self) -> str:
        return self.defined_symbol or self.name

    @property
    def has_symbol(self) -> bool:
        return bool(self.defined_symbol)


@dataclass(frozen=True)
class DimensionDefinition(errors.WithDefErr):
    """Definition of a root dimension"""

    #: name of the dimension
    name: str

    @property
    def is_base(self):
        return True

    def __post_init__(self):
        if not errors.is_valid_dimension_name(self.name):
            raise self.def_err(errors.MSG_INVALID_DIMENSION_NAME)


@dataclass(frozen=True)
class DerivedDimensionDefinition(DimensionDefinition):
    """Definition of a derived dimension."""

    #: reference dimensions.
    reference: UnitsContainer

    @property
    def is_base(self):
        return False

    def __post_init__(self):
        if not errors.is_valid_dimension_name(self.name):
            raise self.def_err(errors.MSG_INVALID_DIMENSION_NAME)

        if not all(map(errors.is_dim, self.reference.keys())):
            return self.def_err(
                "derived dimensions must only reference other dimensions"
            )

        invalid = tuple(
            itertools.filterfalse(errors.is_valid_dimension_name, self.reference.keys())
        )

        if invalid:
            raise self.def_err(
                f"refers to {', '.join(invalid)} that "
                + errors.MSG_INVALID_DIMENSION_NAME
            )


@dataclass(frozen=True)
class AliasDefinition(errors.WithDefErr):
    """Additional alias(es) for an already existing unit."""

    #: name of the already existing unit
    name: str
    #: aditional names for the same unit
    aliases: ty.Tuple[str, ...]

    def __post_init__(self):
        if not errors.is_valid_unit_name(self.name):
            raise self.def_err(errors.MSG_INVALID_UNIT_NAME)

        for alias in self.aliases:
            if not errors.is_valid_unit_alias(alias):
                raise self.def_err(
                    f"the alias {alias} " + errors.MSG_INVALID_UNIT_ALIAS
                )


@dataclass(frozen=True)
class ScaleConverter(Converter):
    """A linear transformation without offset."""

    scale: float

    def to_reference(self, value: Magnitude, inplace: bool = False) -> Magnitude:
        if inplace:
            value *= self.scale
        else:
            value = value * self.scale

        return value

    def from_reference(self, value: Magnitude, inplace: bool = False) -> Magnitude:
        if inplace:
            value /= self.scale
        else:
            value = value / self.scale

        return value