summaryrefslogtreecommitdiff
path: root/pint/definitions.py
blob: f180f7c16d8721e9ec26c3ee1e73e0940563d6f8 (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
# -*- coding: utf-8 -*-
"""
    pint.definitions
    ~~~~~~~~~~~~~~~~

    Functions and classes related to unit definitions.

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

from .converters import ScaleConverter, OffsetConverter
from .util import UnitsContainer, _is_dim, ParserHelper


class Definition:
    """Base class for definitions.

    :param name: name.
    :param symbol: a short name or symbol for the definition
    :param aliases: iterable of other names.
    :param converter: an instance of Converter.
    """

    def __init__(self, name, symbol, aliases, converter):
        self._name = name
        self._symbol = symbol
        self._aliases = aliases
        self._converter = converter

    @property
    def is_multiplicative(self):
        return self._converter.is_multiplicative

    @classmethod
    def from_string(cls, definition):
        """Parse a definition
        """
        name, definition = definition.split('=', 1)
        name = name.strip()

        result = [res.strip() for res in definition.split('=')]

        # @alias name = alias1 = alias2 = ...
        if name.startswith("@alias "):
            name = name[len("@alias "):].lstrip()
            return AliasDefinition(name, tuple(result))

        value, aliases = result[0], tuple([x for x in result[1:] if x != ''])
        symbol, aliases = (aliases[0], aliases[1:]) if aliases else (None,
                                                                     aliases)
        if symbol == '_':
            symbol = None
        aliases = tuple([x for x in aliases if x != '_'])

        if name.startswith('['):
            return DimensionDefinition(name, symbol, aliases, value)
        elif name.endswith('-'):
            name = name.rstrip('-')
            return PrefixDefinition(name, symbol, aliases, value)
        else:
            return UnitDefinition(name, symbol, aliases, value)

    @property
    def name(self):
        return self._name

    @property
    def symbol(self):
        return self._symbol or self._name

    @property
    def has_symbol(self):
        return bool(self._symbol)

    @property
    def aliases(self):
        return self._aliases

    def add_aliases(self, *alias):
        alias = tuple(a for a in alias if a not in self._aliases)
        self._aliases = self._aliases + alias

    @property
    def converter(self):
        return self._converter

    def __str__(self):
        return self.name


class PrefixDefinition(Definition):
    """Definition of a prefix.
    """

    def __init__(self, name, symbol, aliases, converter):
        if isinstance(converter, str):
            converter = ScaleConverter(eval(converter))
        aliases = tuple(alias.strip('-') for alias in aliases)
        if symbol:
            symbol = symbol.strip('-')
        super(PrefixDefinition, self).__init__(name, symbol, aliases,
                                               converter)


class UnitDefinition(Definition):
    """Definition of a unit.

    :param reference: Units container with reference units.
    :param is_base: indicates if it is a base unit.
    """

    def __init__(self, name, symbol, aliases, converter,
                 reference=None, is_base=False):
        self.reference = reference
        self.is_base = is_base
        if isinstance(converter, str):
            if ';' in converter:
                [converter, modifiers] = converter.split(';', 2)
                modifiers = dict((key.strip(), eval(value)) for key, value in
                                 (part.split(':')
                                  for part in modifiers.split(';')))
            else:
                modifiers = {}

            converter = ParserHelper.from_string(converter)
            if not any(_is_dim(key) for key in converter.keys()):
                self.is_base = False
            elif all(_is_dim(key) for key in converter.keys()):
                self.is_base = True
            else:
                raise ValueError('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.')
            self.reference = UnitsContainer(converter)
            if modifiers.get('offset', 0.) != 0.:
                converter = OffsetConverter(converter.scale,
                                            modifiers['offset'])
            else:
                converter = ScaleConverter(converter.scale)

        super(UnitDefinition, self).__init__(name, symbol, aliases, converter)


class DimensionDefinition(Definition):
    """Definition of a dimension.
    """

    def __init__(self, name, symbol, aliases, converter,
                 reference=None, is_base=False):
        self.reference = reference
        self.is_base = is_base
        if isinstance(converter, str):
            converter = ParserHelper.from_string(converter)
            if not converter:
                self.is_base = True
            elif all(_is_dim(key) for key in converter.keys()):
                self.is_base = False
            else:
                raise ValueError('Base dimensions must be referenced to None. '
                                 'Derived dimensions must only be referenced '
                                 'to dimensions.')
            self.reference = UnitsContainer(converter)

        super(DimensionDefinition, self).__init__(name, symbol, aliases,
                                                  converter=None)


class AliasDefinition(Definition):
    """Additional alias(es) for an already existing unit
    """
    def __init__(self, name, aliases):
        super(AliasDefinition, self).__init__(
            name=name, symbol=None, aliases=aliases, converter=None
        )