Debian Codegraph @

brian2/units/unitsafefunctions.py

raw
1 """
2 Unit-aware replacements for numpy functions.
3 """
4
5 from functools import wraps
6
7 import numpy as np
8
9 from .fundamentalunits import (
10 DIMENSIONLESS,
11 Quantity,
12 check_units,
13 fail_for_dimension_mismatch,
14 is_dimensionless,
15 wrap_function_dimensionless,
16 wrap_function_keep_dimensions,
17 wrap_function_remove_dimensions,
18 )
19
20 __all__ = [
21 "log",
22 "log10",
23 "exp",
24 "expm1",
25 "log1p",
26 "exprel",
27 "sin",
28 "cos",
29 "tan",
30 "arcsin",
31 "arccos",
32 "arctan",
33 "sinh",
34 "cosh",
35 "tanh",
36 "arcsinh",
37 "arccosh",
38 "arctanh",
39 "diagonal",
40 "ravel",
41 "trace",
42 "dot",
43 "where",
44 "ones_like",
45 "zeros_like",
46 "arange",
47 "linspace",
48 "ptp",
49 ]
50
51
52 def where(condition, *args, **kwds): # pylint: disable=C0111
53 if len(args) == 0:
54 # nothing to do
55 return np.where(condition, *args, **kwds)
56 elif len(args) == 2:
57 # check that x and y have the same dimensions
58 fail_for_dimension_mismatch(
59 args[0], args[1], "x and y need to have the same dimensions"
60 )
61
62 if is_dimensionless(args[0]):
63 return np.where(condition, *args, **kwds)
64 else:
65 # as both arguments have the same unit, just use the first one's
66 dimensionless_args = [np.asarray(arg) for arg in args]
67 return Quantity.with_dimensions(
68 np.where(condition, *dimensionless_args), args[0].dimensions
69 )
70 else:
71 # illegal number of arguments, let numpy take care of this
72 return np.where(condition, *args, **kwds)
73
74
75 where.__doc__ = np.where.__doc__
76 where._do_not_run_doctests = True
77
78 # Functions that work on dimensionless quantities only
79 sin = wrap_function_dimensionless(np.sin)
80 sinh = wrap_function_dimensionless(np.sinh)
81 arcsin = wrap_function_dimensionless(np.arcsin)
82 arcsinh = wrap_function_dimensionless(np.arcsinh)
83 cos = wrap_function_dimensionless(np.cos)
84 cosh = wrap_function_dimensionless(np.cosh)
85 arccos = wrap_function_dimensionless(np.arccos)
86 arccosh = wrap_function_dimensionless(np.arccosh)
87 tan = wrap_function_dimensionless(np.tan)
88 tanh = wrap_function_dimensionless(np.tanh)
89 arctan = wrap_function_dimensionless(np.arctan)
90 arctanh = wrap_function_dimensionless(np.arctanh)
91
92 log = wrap_function_dimensionless(np.log)
93 log10 = wrap_function_dimensionless(np.log10)
94 exp = wrap_function_dimensionless(np.exp)
95 expm1 = wrap_function_dimensionless(np.expm1)
96 log1p = wrap_function_dimensionless(np.log1p)
97
98 ptp = wrap_function_keep_dimensions(np.ptp)
99
100
101 @check_units(x=1, result=1)
102 def exprel(x):
103 x = np.asarray(x)
104 if issubclass(x.dtype.type, np.integer):
105 result = np.empty_like(x, dtype=np.float64)
106 else:
107 result = np.empty_like(x)
108 # Following the implementation of exprel from scipy.special
109 if x.shape == ():
110 if np.abs(x) < 1e-16:
111 return 1.0
112 elif x > 717:
113 return np.inf
114 else:
115 return np.expm1(x) / x
116 else:
117 small = np.abs(x) < 1e-16
118 big = x > 717
119 in_between = np.logical_not(small | big)
120 result[small] = 1.0
121 result[big] = np.inf
122 result[in_between] = np.expm1(x[in_between]) / x[in_between]
123 return result
124
125
126 ones_like = wrap_function_remove_dimensions(np.ones_like)
127 zeros_like = wrap_function_remove_dimensions(np.zeros_like)
128
129
130 def wrap_function_to_method(func):
131 """
132 Wraps a function so that it calls the corresponding method on the
133 Quantities object (if called with a Quantities object as the first
134 argument). All other arguments are left untouched.
135 """
136
137 @wraps(func)
138 def f(x, *args, **kwds): # pylint: disable=C0111
139 if isinstance(x, Quantity):
140 return getattr(x, func.__name__)(*args, **kwds)
141 else:
142 # no need to wrap anything
143 return func(x, *args, **kwds)
144
145 f.__doc__ = func.__doc__
146 f.__name__ = func.__name__
147 f._do_not_run_doctests = True
148 return f
149
150
151 @wraps(np.arange)
152 def arange(*args, **kwargs):
153 # arange has a bit of a complicated argument structure unfortunately
154 # we leave the actual checking of the number of arguments to numpy, though
155
156 # default values
157 start = kwargs.pop("start", 0)
158 step = kwargs.pop("step", 1)
159 stop = kwargs.pop("stop", None)
160 if len(args) == 1:
161 if stop is not None:
162 raise TypeError("Duplicate definition of 'stop'")
163 stop = args[0]
164 elif len(args) == 2:
165 if start != 0:
166 raise TypeError("Duplicate definition of 'start'")
167 if stop is not None:
168 raise TypeError("Duplicate definition of 'stop'")
169 start, stop = args
170 elif len(args) == 3:
171 if start != 0:
172 raise TypeError("Duplicate definition of 'start'")
173 if stop is not None:
174 raise TypeError("Duplicate definition of 'stop'")
175 if step != 1:
176 raise TypeError("Duplicate definition of 'step'")
177 start, stop, step = args
178 elif len(args) > 3:
179 raise TypeError("Need between 1 and 3 non-keyword arguments")
180 if stop is None:
181 raise TypeError("Missing stop argument.")
182 fail_for_dimension_mismatch(
183 start,
184 stop,
185 error_message=(
186 "Start value {start} and stop value {stop} have to have the same units."
187 ),
188 start=start,
189 stop=stop,
190 )
191 fail_for_dimension_mismatch(
192 stop,
193 step,
194 error_message=(
195 "Stop value {stop} and step value {step} have to have the same units."
196 ),
197 stop=stop,
198 step=step,
199 )
200 dim = getattr(stop, "dim", DIMENSIONLESS)
201 # start is a position-only argument in numpy 2.0
202 # https://numpy.org/devdocs/release/2.0.0-notes.html#arange-s-start-argument-is-positional-only
203 # TODO: check whether this is still the case in the final release
204 if start == 0:
205 return Quantity(
206 np.arange(
207 stop=np.asarray(stop),
208 step=np.asarray(step),
209 **kwargs,
210 ),
211 dim=dim,
212 )
213 else:
214 return Quantity(
215 np.arange(
216 np.asarray(start),
217 stop=np.asarray(stop),
218 step=np.asarray(step),
219 **kwargs,
220 ),
221 dim=dim,
222 )
223
224
225 arange._do_not_run_doctests = True
226
227
228 @wraps(np.linspace)
229 def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
230 fail_for_dimension_mismatch(
231 start,
232 stop,
233 error_message=(
234 "Start value {start} and stop value {stop} have to have the same units."
235 ),
236 start=start,
237 stop=stop,
238 )
239 dim = getattr(start, "dim", DIMENSIONLESS)
240 result = np.linspace(
241 np.asarray(start),
242 np.asarray(stop),
243 num=num,
244 endpoint=endpoint,
245 retstep=retstep,
246 dtype=dtype,
247 )
248 return Quantity(result, dim=dim)
249
250
251 linspace._do_not_run_doctests = True
252
253 # these functions discard subclass info -- maybe a bug in numpy?
254 ravel = wrap_function_to_method(np.ravel)
255 diagonal = wrap_function_to_method(np.diagonal)
256 trace = wrap_function_to_method(np.trace)
257 dot = wrap_function_to_method(np.dot)
258
259 # This is a very minor detail: setting the __module__ attribute allows the
260 # automatic reference doc generation mechanism to attribute the functions to
261 # this module. Maybe also helpful for IDEs and other code introspection tools.
262 sin.__module__ = __name__
263 sinh.__module__ = __name__
264 arcsin.__module__ = __name__
265 arcsinh.__module__ = __name__
266 cos.__module__ = __name__
267 cosh.__module__ = __name__
268 arccos.__module__ = __name__
269 arccosh.__module__ = __name__
270 tan.__module__ = __name__
271 tanh.__module__ = __name__
272 arctan.__module__ = __name__
273 arctanh.__module__ = __name__
274
275 log.__module__ = __name__
276 exp.__module__ = __name__
277 ravel.__module__ = __name__
278 diagonal.__module__ = __name__
279 trace.__module__ = __name__
280 dot.__module__ = __name__
281 arange.__module__ = __name__
282 linspace.__module__ = __name__