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

    Functions and classes related to context definitions and application.

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

import re
import weakref
from collections import ChainMap, defaultdict

from .util import (ParserHelper, UnitsContainer,
                   to_units_container, SourceIterator)
from .errors import DefinitionSyntaxError

#: Regex to match the header parts of a context.
_header_re = re.compile(r'@context\s*(?P<defaults>\(.*\))?\s+(?P<name>\w+)\s*(=(?P<aliases>.*))*')

#: Regex to match variable names in an equation.
_varname_re = re.compile(r'[A-Za-z_][A-Za-z0-9_]*')


def _expression_to_function(eq):
    def func(ureg, value, **kwargs):
        return ureg.parse_expression(eq, value=value, **kwargs)
    return func


class Context:
    """A specialized container that defines transformation functions from one
    dimension to another. Each Dimension are specified using a UnitsContainer.
    Simple transformation are given with a function taking a single parameter.

        >>> timedim = UnitsContainer({'[time]': 1})
        >>> spacedim = UnitsContainer({'[length]': 1})
        >>> def f(time):
        ...     'Time to length converter'
        ...     return 3. * time
        >>> c = Context()
        >>> c.add_transformation(timedim, spacedim, f)
        >>> c.transform(timedim, spacedim, 2)
        6

    Conversion functions may take optional keyword arguments and the context
    can have default values for these arguments.

        >>> def f(time, n):
        ...     'Time to length converter, n is the index of refraction of the material'
        ...     return 3. * time / n
        >>> c = Context(n=3)
        >>> c.add_transformation(timedim, spacedim, f)
        >>> c.transform(timedim, spacedim, 2)
        2

    """

    def __init__(self, name=None, aliases=(), defaults=None):

        self.name = name
        self.aliases = aliases

        #: Maps (src, dst) -> transformation function
        self.funcs = {}

        #: Maps defaults variable names to values
        self.defaults = defaults or {}

        #: Maps (src, dst) -> self
        #: Used as a convenience dictionary to be composed by ContextChain
        self.relation_to_context = weakref.WeakValueDictionary()

    @classmethod
    def from_context(cls, context, **defaults):
        """Creates a new context that shares the funcs dictionary with the
        original context. The default values are copied from the original
        context and updated with the new defaults.

        If defaults is empty, return the same context.
        """
        if defaults:
            newdef = dict(context.defaults, **defaults)
            c = cls(context.name, context.aliases, newdef)
            c.funcs = context.funcs
            for edge in context.funcs:
                c.relation_to_context[edge] = c
            return c
        return context

    @classmethod
    def from_lines(cls, lines, to_base_func=None):
        lines = SourceIterator(lines)

        lineno, header = next(lines)
        try:
            r = _header_re.search(header)
            name = r.groupdict()['name'].strip()
            aliases = r.groupdict()['aliases']
            if aliases:
                aliases = tuple(a.strip() for a in r.groupdict()['aliases'].split('='))
            else:
                aliases = ()
            defaults = r.groupdict()['defaults']
        except:
            raise DefinitionSyntaxError("Could not parse the Context header '%s'" % header,
                                        lineno=lineno)

        if defaults:
            def to_num(val):
                val = complex(val)
                if not val.imag:
                    return val.real
                return val

            _txt = defaults
            try:
                defaults = (part.split('=') for part in defaults.strip('()').split(','))
                defaults = dict((str(k).strip(), to_num(v))
                                for k, v in defaults)
            except (ValueError, TypeError):
                raise DefinitionSyntaxError("Could not parse Context definition defaults: '%s'" % _txt,
                                            lineno=lineno)

            ctx = cls(name, aliases, defaults)
        else:
            ctx = cls(name, aliases)

        names = set()
        for lineno, line in lines:
            try:
                rel, eq = line.split(':')
                names.update(_varname_re.findall(eq))

                func = _expression_to_function(eq)

                if '<->' in rel:
                    src, dst = (ParserHelper.from_string(s)
                                for s in rel.split('<->'))
                    if to_base_func:
                        src = to_base_func(src)
                        dst = to_base_func(dst)
                    ctx.add_transformation(src, dst, func)
                    ctx.add_transformation(dst, src, func)
                elif '->' in rel:
                    src, dst = (ParserHelper.from_string(s)
                                for s in rel.split('->'))
                    if to_base_func:
                        src = to_base_func(src)
                        dst = to_base_func(dst)
                    ctx.add_transformation(src, dst, func)
                else:
                    raise Exception
            except:
                raise DefinitionSyntaxError("Could not parse Context %s relation '%s'" % (name, line),
                                            lineno=lineno)

        if defaults:
            missing_pars = defaults.keys() - set(names)
            if missing_pars:
                raise DefinitionSyntaxError('Context parameters {} not found in any equation.'.format(missing_pars))

        return ctx

    def add_transformation(self, src, dst, func):
        """Add a transformation function to the context.
        """
        _key = self.__keytransform__(src, dst)
        self.funcs[_key] = func
        self.relation_to_context[_key] = self

    def remove_transformation(self, src, dst):
        """Add a transformation function to the context.
        """
        _key = self.__keytransform__(src, dst)
        del self.funcs[_key]
        del self.relation_to_context[_key]

    @staticmethod
    def __keytransform__(src, dst):
        return to_units_container(src), to_units_container(dst)

    def transform(self, src, dst, registry, value):
        """Transform a value.
        """
        _key = self.__keytransform__(src, dst)
        return self.funcs[_key](registry, value, **self.defaults)


class ContextChain(ChainMap):
    """A specialized ChainMap for contexts that simplifies finding rules
    to transform from one dimension to another.
    """

    def __init__(self):
        super().__init__()
        self._graph = None
        self._contexts = []

    def insert_contexts(self, *contexts):
        """Insert one or more contexts in reversed order the chained map.
        (A rule in last context will take precedence)

        To facilitate the identification of the context with the matching rule,
        the *relation_to_context* dictionary of the context is used.
        """
        self._contexts.insert(0, contexts)
        self.maps = [ctx.relation_to_context for ctx in reversed(contexts)] + self.maps
        self._graph = None

    def remove_contexts(self, n):
        """Remove the last n inserted contexts from the chain.
        """
        self._contexts = self._contexts[n:]
        self.maps = self.maps[n:]
        self._graph = None

    @property
    def defaults(self):
        if self:
            return next(iter(self.maps[0].values())).defaults
        return {}

    @property
    def graph(self):
        """The graph relating
        """
        if self._graph is None:
            self._graph = defaultdict(set)
            for fr_, to_ in self:
                self._graph[fr_].add(to_)
        return self._graph

    def transform(self, src, dst, registry, value):
        """Transform the value, finding the rule in the chained context.
        (A rule in last context will take precedence)

        :raises: KeyError if the rule is not found.
        """
        return self[(src, dst)].transform(src, dst, registry, value)

    def context_ids(self):
        """Hashable unique identifier of the current contents of the context chain. This
        is not implemented as ``__hash__`` as doing so on a mutable object can provoke
        unpredictable behaviour, as interpreter-level optimizations can cache the output
        of ``__hash__``.
        """
        return tuple(id(ctx) for ctx in self._contexts)