File: unitsafefunctions.py

package info (click to toggle)
brian 2.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,872 kB
  • sloc: python: 51,820; cpp: 2,033; makefile: 108; sh: 72
file content (282 lines) | stat: -rw-r--r-- 8,050 bytes parent folder | download | duplicates (2)
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
"""
Unit-aware replacements for numpy functions.
"""

from functools import wraps

import numpy as np

from .fundamentalunits import (
    DIMENSIONLESS,
    Quantity,
    check_units,
    fail_for_dimension_mismatch,
    is_dimensionless,
    wrap_function_dimensionless,
    wrap_function_keep_dimensions,
    wrap_function_remove_dimensions,
)

__all__ = [
    "log",
    "log10",
    "exp",
    "expm1",
    "log1p",
    "exprel",
    "sin",
    "cos",
    "tan",
    "arcsin",
    "arccos",
    "arctan",
    "sinh",
    "cosh",
    "tanh",
    "arcsinh",
    "arccosh",
    "arctanh",
    "diagonal",
    "ravel",
    "trace",
    "dot",
    "where",
    "ones_like",
    "zeros_like",
    "arange",
    "linspace",
    "ptp",
]


def where(condition, *args, **kwds):  # pylint: disable=C0111
    if len(args) == 0:
        # nothing to do
        return np.where(condition, *args, **kwds)
    elif len(args) == 2:
        # check that x and y have the same dimensions
        fail_for_dimension_mismatch(
            args[0], args[1], "x and y need to have the same dimensions"
        )

        if is_dimensionless(args[0]):
            return np.where(condition, *args, **kwds)
        else:
            # as both arguments have the same unit, just use the first one's
            dimensionless_args = [np.asarray(arg) for arg in args]
            return Quantity.with_dimensions(
                np.where(condition, *dimensionless_args), args[0].dimensions
            )
    else:
        # illegal number of arguments, let numpy take care of this
        return np.where(condition, *args, **kwds)


where.__doc__ = np.where.__doc__
where._do_not_run_doctests = True

# Functions that work on dimensionless quantities only
sin = wrap_function_dimensionless(np.sin)
sinh = wrap_function_dimensionless(np.sinh)
arcsin = wrap_function_dimensionless(np.arcsin)
arcsinh = wrap_function_dimensionless(np.arcsinh)
cos = wrap_function_dimensionless(np.cos)
cosh = wrap_function_dimensionless(np.cosh)
arccos = wrap_function_dimensionless(np.arccos)
arccosh = wrap_function_dimensionless(np.arccosh)
tan = wrap_function_dimensionless(np.tan)
tanh = wrap_function_dimensionless(np.tanh)
arctan = wrap_function_dimensionless(np.arctan)
arctanh = wrap_function_dimensionless(np.arctanh)

log = wrap_function_dimensionless(np.log)
log10 = wrap_function_dimensionless(np.log10)
exp = wrap_function_dimensionless(np.exp)
expm1 = wrap_function_dimensionless(np.expm1)
log1p = wrap_function_dimensionless(np.log1p)

ptp = wrap_function_keep_dimensions(np.ptp)


@check_units(x=1, result=1)
def exprel(x):
    x = np.asarray(x)
    if issubclass(x.dtype.type, np.integer):
        result = np.empty_like(x, dtype=np.float64)
    else:
        result = np.empty_like(x)
    # Following the implementation of exprel from scipy.special
    if x.shape == ():
        if np.abs(x) < 1e-16:
            return 1.0
        elif x > 717:
            return np.inf
        else:
            return np.expm1(x) / x
    else:
        small = np.abs(x) < 1e-16
        big = x > 717
        in_between = np.logical_not(small | big)
        result[small] = 1.0
        result[big] = np.inf
        result[in_between] = np.expm1(x[in_between]) / x[in_between]
        return result


ones_like = wrap_function_remove_dimensions(np.ones_like)
zeros_like = wrap_function_remove_dimensions(np.zeros_like)


def wrap_function_to_method(func):
    """
    Wraps a function so that it calls the corresponding method on the
    Quantities object (if called with a Quantities object as the first
    argument). All other arguments are left untouched.
    """

    @wraps(func)
    def f(x, *args, **kwds):  # pylint: disable=C0111
        if isinstance(x, Quantity):
            return getattr(x, func.__name__)(*args, **kwds)
        else:
            # no need to wrap anything
            return func(x, *args, **kwds)

    f.__doc__ = func.__doc__
    f.__name__ = func.__name__
    f._do_not_run_doctests = True
    return f


@wraps(np.arange)
def arange(*args, **kwargs):
    # arange has a bit of a complicated argument structure unfortunately
    # we leave the actual checking of the number of arguments to numpy, though

    # default values
    start = kwargs.pop("start", 0)
    step = kwargs.pop("step", 1)
    stop = kwargs.pop("stop", None)
    if len(args) == 1:
        if stop is not None:
            raise TypeError("Duplicate definition of 'stop'")
        stop = args[0]
    elif len(args) == 2:
        if start != 0:
            raise TypeError("Duplicate definition of 'start'")
        if stop is not None:
            raise TypeError("Duplicate definition of 'stop'")
        start, stop = args
    elif len(args) == 3:
        if start != 0:
            raise TypeError("Duplicate definition of 'start'")
        if stop is not None:
            raise TypeError("Duplicate definition of 'stop'")
        if step != 1:
            raise TypeError("Duplicate definition of 'step'")
        start, stop, step = args
    elif len(args) > 3:
        raise TypeError("Need between 1 and 3 non-keyword arguments")
    if stop is None:
        raise TypeError("Missing stop argument.")
    fail_for_dimension_mismatch(
        start,
        stop,
        error_message=(
            "Start value {start} and stop value {stop} have to have the same units."
        ),
        start=start,
        stop=stop,
    )
    fail_for_dimension_mismatch(
        stop,
        step,
        error_message=(
            "Stop value {stop} and step value {step} have to have the same units."
        ),
        stop=stop,
        step=step,
    )
    dim = getattr(stop, "dim", DIMENSIONLESS)
    # start is a position-only argument in numpy 2.0
    # https://numpy.org/devdocs/release/2.0.0-notes.html#arange-s-start-argument-is-positional-only
    # TODO: check whether this is still the case in the final release
    if start == 0:
        return Quantity(
            np.arange(
                stop=np.asarray(stop),
                step=np.asarray(step),
                **kwargs,
            ),
            dim=dim,
        )
    else:
        return Quantity(
            np.arange(
                np.asarray(start),
                stop=np.asarray(stop),
                step=np.asarray(step),
                **kwargs,
            ),
            dim=dim,
        )


arange._do_not_run_doctests = True


@wraps(np.linspace)
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
    fail_for_dimension_mismatch(
        start,
        stop,
        error_message=(
            "Start value {start} and stop value {stop} have to have the same units."
        ),
        start=start,
        stop=stop,
    )
    dim = getattr(start, "dim", DIMENSIONLESS)
    result = np.linspace(
        np.asarray(start),
        np.asarray(stop),
        num=num,
        endpoint=endpoint,
        retstep=retstep,
        dtype=dtype,
    )
    return Quantity(result, dim=dim)


linspace._do_not_run_doctests = True

# these functions discard subclass info -- maybe a bug in numpy?
ravel = wrap_function_to_method(np.ravel)
diagonal = wrap_function_to_method(np.diagonal)
trace = wrap_function_to_method(np.trace)
dot = wrap_function_to_method(np.dot)

# This is a very minor detail: setting the __module__ attribute allows the
# automatic reference doc generation mechanism to attribute the functions to
# this module. Maybe also helpful for IDEs and other code introspection tools.
sin.__module__ = __name__
sinh.__module__ = __name__
arcsin.__module__ = __name__
arcsinh.__module__ = __name__
cos.__module__ = __name__
cosh.__module__ = __name__
arccos.__module__ = __name__
arccosh.__module__ = __name__
tan.__module__ = __name__
tanh.__module__ = __name__
arctan.__module__ = __name__
arctanh.__module__ = __name__

log.__module__ = __name__
exp.__module__ = __name__
ravel.__module__ = __name__
diagonal.__module__ = __name__
trace.__module__ = __name__
dot.__module__ = __name__
arange.__module__ = __name__
linspace.__module__ = __name__