Debian Codegraph @

brian2/tests/test_units.py

raw
1 import itertools
2 import pickle
3 import warnings
4
5 import numpy as np
6 import pytest
7 from numpy.testing import assert_equal
8
9 import brian2
10 from brian2.core.preferences import prefs
11 from brian2.tests.utils import assert_allclose
12 from brian2.units.allunits import *
13 from brian2.units.fundamentalunits import (
14 DIMENSIONLESS,
15 UFUNCS_DIMENSIONLESS,
16 UFUNCS_DIMENSIONLESS_TWOARGS,
17 UFUNCS_INTEGERS,
18 UFUNCS_LOGICAL,
19 DimensionMismatchError,
20 Quantity,
21 Unit,
22 check_units,
23 fail_for_dimension_mismatch,
24 get_dimensions,
25 get_or_create_dimension,
26 get_unit,
27 have_same_dimensions,
28 in_unit,
29 is_dimensionless,
30 is_scalar_type,
31 )
32 from brian2.units.stdunits import Hz, cm, kHz, mM, ms, mV, nA, nS
33
34 # To work around an issue in matplotlib 1.3.1 (see
35 # https://github.com/matplotlib/matplotlib/pull/2591), we make `ravel`
36 # return a unitless array and emit a warning explaining the issue.
37 use_matplotlib_units_fix = False
38 try:
39 import matplotlib
40
41 if matplotlib.__version__ == "1.3.1":
42 use_matplotlib_units_fix = True
43 except ImportError:
44 pass
45
46
47 def assert_quantity(q, values, unit):
48 assert isinstance(q, Quantity) or (
49 have_same_dimensions(unit, 1)
50 and (values.shape == () or isinstance(q, np.ndarray))
51 ), q
52 assert_allclose(np.asarray(q), values)
53 assert have_same_dimensions(q, unit), (
54 f"Dimension mismatch: ({get_dimensions(q)}) ({get_dimensions(unit)})"
55 )
56
57
58 @pytest.mark.codegen_independent
59 def test_construction():
60 """Test the construction of quantity objects"""
61 q = 500 * ms
62 assert_quantity(q, 0.5, second)
63 q = np.float64(500) * ms
64 assert_quantity(q, 0.5, second)
65 q = np.array(500) * ms
66 assert_quantity(q, 0.5, second)
67 q = np.array([500, 1000]) * ms
68 assert_quantity(q, np.array([0.5, 1]), second)
69 q = Quantity(500)
70 assert_quantity(q, 500, 1)
71 q = Quantity(500, dim=second.dim)
72 assert_quantity(q, 500, second)
73 q = Quantity([0.5, 1], dim=second.dim)
74 assert_quantity(q, np.array([0.5, 1]), second)
75 q = Quantity(np.array([0.5, 1]), dim=second.dim)
76 assert_quantity(q, np.array([0.5, 1]), second)
77 q = Quantity([500 * ms, 1 * second])
78 assert_quantity(q, np.array([0.5, 1]), second)
79 q = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
80 assert_quantity(q, np.array([0.5, 1]), second)
81 q = [0.5, 1] * second
82 assert_quantity(q, np.array([0.5, 1]), second)
83
84 # dimensionless quantities
85 q = Quantity([1, 2, 3])
86 assert_quantity(q, np.array([1, 2, 3]), Unit(1))
87 q = Quantity(np.array([1, 2, 3]))
88 assert_quantity(q, np.array([1, 2, 3]), Unit(1))
89 q = Quantity([])
90 assert_quantity(q, np.array([]), Unit(1))
91
92 # copying/referencing a quantity
93 q1 = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
94 q2 = Quantity(q1) # no copy
95 assert_quantity(q2, np.asarray(q1), q1)
96 q2[0] = 3 * second
97 assert_equal(q1[0], 3 * second)
98
99 q1 = Quantity.with_dimensions(np.array([0.5, 1]), second=1)
100 q2 = Quantity(q1, copy=True) # copy
101 assert_quantity(q2, np.asarray(q1), q1)
102 q2[0] = 3 * second
103 assert_equal(q1[0], 0.5 * second)
104
105 # Illegal constructor calls
106 with pytest.raises(TypeError):
107 Quantity([500 * ms, 1])
108 with pytest.raises(TypeError):
109 Quantity(["some", "nonsense"])
110 with pytest.raises(DimensionMismatchError):
111 Quantity([500 * ms, 1 * volt])
112
113
114 @pytest.mark.codegen_independent
115 def test_get_dimensions():
116 """
117 Test various ways of getting/comparing the dimensions of a quantity.
118 """
119 q = 500 * ms
120 assert get_dimensions(q) is get_or_create_dimension(q.dimensions._dims)
121 assert get_dimensions(q) is q.dimensions
122 assert q.has_same_dimensions(3 * second)
123 dims = q.dimensions
124 assert_equal(dims.get_dimension("time"), 1.0)
125 assert_equal(dims.get_dimension("length"), 0)
126
127 assert get_dimensions(5) is DIMENSIONLESS
128 assert get_dimensions(5.0) is DIMENSIONLESS
129 assert get_dimensions(np.array(5, dtype=np.int32)) is DIMENSIONLESS
130 assert get_dimensions(np.array(5.0)) is DIMENSIONLESS
131 assert get_dimensions(np.float32(5.0)) is DIMENSIONLESS
132 assert get_dimensions(np.float64(5.0)) is DIMENSIONLESS
133 assert is_scalar_type(5)
134 assert is_scalar_type(5.0)
135 assert is_scalar_type(np.array(5, dtype=np.int32))
136 assert is_scalar_type(np.array(5.0))
137 assert is_scalar_type(np.float32(5.0))
138 assert is_scalar_type(np.float64(5.0))
139 with pytest.raises(TypeError):
140 get_dimensions("a string")
141 # wrong number of indices
142 with pytest.raises(TypeError):
143 get_or_create_dimension([1, 2, 3, 4, 5, 6])
144 # not a sequence
145 with pytest.raises(TypeError):
146 get_or_create_dimension(42)
147
148
149 @pytest.mark.codegen_independent
150 def test_display():
151 """
152 Test displaying a quantity in different units
153 """
154 assert_equal(in_unit(3 * volt, mvolt), "3000. mV")
155 assert_equal(in_unit(10 * mV, ohm * amp), "0.01 ohm A")
156 with pytest.raises(DimensionMismatchError):
157 in_unit(10 * nS, ohm)
158
159 # A bit artificial...
160 assert_equal(in_unit(10.0, Unit(10.0, scale=1)), "1.0")
161
162
163 @pytest.mark.codegen_independent
164 def test_scale():
165 # Check that unit scaling is implemented correctly
166 from brian2.core.namespace import DEFAULT_UNITS
167
168 siprefixes = {
169 "y": 1e-24,
170 "z": 1e-21,
171 "a": 1e-18,
172 "f": 1e-15,
173 "p": 1e-12,
174 "n": 1e-9,
175 "u": 1e-6,
176 "m": 1e-3,
177 "": 1.0,
178 "k": 1e3,
179 "M": 1e6,
180 "G": 1e9,
181 "T": 1e12,
182 "P": 1e15,
183 "E": 1e18,
184 "Z": 1e21,
185 "Y": 1e24,
186 }
187 for prefix in siprefixes:
188 if prefix in ["c", "d", "da", "h"]:
189 continue
190 scaled_unit = DEFAULT_UNITS[f"{prefix}meter"]
191 assert_allclose(float(scaled_unit), siprefixes[prefix])
192 assert_allclose(5 * scaled_unit / meter, 5 * siprefixes[prefix])
193 scaled_unit = DEFAULT_UNITS[f"{prefix}meter2"]
194 assert_allclose(float(scaled_unit), siprefixes[prefix] ** 2)
195 assert_allclose(5 * scaled_unit / meter2, 5 * siprefixes[prefix] ** 2)
196 scaled_unit = DEFAULT_UNITS[f"{prefix}meter3"]
197 assert_allclose(float(scaled_unit), siprefixes[prefix] ** 3)
198 assert_allclose(5 * scaled_unit / meter3, 5 * siprefixes[prefix] ** 3)
199 # liter, gram, and molar are special, they are not base units with a
200 # value of one, even though they do not have any prefix
201 for unit, factor in [
202 ("liter", 1e-3),
203 ("litre", 1e-3),
204 ("gram", 1e-3),
205 ("gramme", 1e-3),
206 ("molar", 1e3),
207 ]:
208 base_unit = DEFAULT_UNITS[unit]
209 scaled_unit = DEFAULT_UNITS[prefix + unit]
210 assert_allclose(float(scaled_unit), siprefixes[prefix] * factor)
211 assert_allclose(5 * scaled_unit / base_unit, 5 * siprefixes[prefix])
212
213
214 @pytest.mark.codegen_independent
215 def test_pickling():
216 """
217 Test pickling of units.
218 """
219 for q in [
220 500 * mV,
221 500 * mV / mV,
222 np.arange(10) * mV,
223 np.arange(12).reshape(4, 3) * mV / ms,
224 ]:
225 pickled = pickle.dumps(q)
226 unpickled = pickle.loads(pickled)
227 assert isinstance(unpickled, type(q))
228 assert have_same_dimensions(unpickled, q)
229 assert_equal(unpickled, q)
230
231
232 @pytest.mark.codegen_independent
233 def test_dimension_singletons():
234 # Make sure that Dimension objects are singletons, even when pickled
235 volt_dim = get_or_create_dimension((2, 1, -3, -1, 0, 0, 0))
236 assert volt.dim is volt_dim
237 import pickle
238
239 pickled_dim = pickle.dumps(volt_dim)
240 unpickled_dim = pickle.loads(pickled_dim)
241 assert unpickled_dim is volt_dim
242 assert unpickled_dim is volt.dim
243
244
245 @pytest.mark.codegen_independent
246 def test_str_repr():
247 """
248 Test that str representations do not raise any errors and that repr
249 fullfills eval(repr(x)) == x. Also test generating LaTeX representations via sympy.
250 """
251 import sympy
252 from numpy import array # necessary for evaluating repr
253
254 units_which_should_exist = [
255 metre,
256 meter,
257 kilogram,
258 kilogramme,
259 second,
260 amp,
261 kelvin,
262 mole,
263 candle,
264 radian,
265 steradian,
266 hertz,
267 newton,
268 pascal,
269 joule,
270 watt,
271 coulomb,
272 volt,
273 farad,
274 ohm,
275 siemens,
276 weber,
277 tesla,
278 henry,
279 lumen,
280 lux,
281 becquerel,
282 gray,
283 sievert,
284 katal,
285 gram,
286 gramme,
287 molar,
288 liter,
289 litre,
290 ]
291
292 # scaled versions of all these units should exist (we just check farad as an example)
293 some_scaled_units = [
294 Yfarad,
295 Zfarad,
296 Efarad,
297 Pfarad,
298 Tfarad,
299 Gfarad,
300 Mfarad,
301 kfarad,
302 hfarad,
303 dafarad,
304 dfarad,
305 cfarad,
306 mfarad,
307 ufarad,
308 nfarad,
309 pfarad,
310 ffarad,
311 afarad,
312 zfarad,
313 yfarad,
314 ]
315
316 # some powered units
317 powered_units = [cmetre2, Yfarad3]
318
319 # Combined units
320 complex_units = [
321 (kgram * metre2) / (amp * second3),
322 5 * (kgram * metre2) / (amp * second3),
323 metre * second**-1,
324 10 * metre * second**-1,
325 array([1, 2, 3]) * kmetre / second,
326 np.ones(3) * nS / cm**2,
327 # Made-up unit:
328 Unit(
329 1,
330 dim=get_or_create_dimension(length=5, time=2),
331 dispname="O",
332 latexname=r"\Omega",
333 ),
334 8000 * umetre**3,
335 [0.0001, 10000] * umetre**3,
336 1 / metre,
337 1 / (coulomb * metre**2),
338 Unit(1) / second,
339 3.0 * mM,
340 5 * mole / liter,
341 7 * liter / meter3,
342 1 / second**2,
343 volt**-2,
344 (volt**2) ** -1,
345 (1 / second) / meter,
346 1 / (1 / second),
347 ]
348
349 unitless = [second / second, 5 * second / second, Unit(1)]
350
351 for u in itertools.chain(
352 units_which_should_exist,
353 some_scaled_units,
354 powered_units,
355 complex_units,
356 unitless,
357 ):
358 assert len(str(u)) > 0
359 if not is_dimensionless(u):
360 assert len(sympy.latex(u))
361 assert get_dimensions(eval(repr(u))) == get_dimensions(u)
362 assert_allclose(eval(repr(u)), u)
363
364 for ar in [np.arange(10000) * mV, np.arange(100).reshape(10, 10) * mV]:
365 latex_str = sympy.latex(ar)
366 assert 0 < len(latex_str) < 1000 # arbitrary threshold, but see #1425
367
368 # test the `DIMENSIONLESS` object
369 assert str(DIMENSIONLESS) == "1"
370 assert repr(DIMENSIONLESS) == "Dimension()"
371
372 # test DimensionMismatchError (only that it works without raising an error
373 for error in [
374 DimensionMismatchError("A description"),
375 DimensionMismatchError("A description", DIMENSIONLESS),
376 DimensionMismatchError("A description", DIMENSIONLESS, second.dim),
377 ]:
378 assert len(str(error))
379 assert len(repr(error))
380
381
382 @pytest.mark.codegen_independent
383 def test_format_quantity():
384 # Avoid that the default f-string (or .format call) discards units when used without
385 # a format spec
386 q = 0.5 * ms
387 assert f"{q}" == f"{q!s}" == str(q)
388 assert f"{q:g}" == f"{float(q)}"
389
390
391 @pytest.mark.codegen_independent
392 def test_slicing():
393 # Slicing and indexing, setting items
394 quantity = np.reshape(np.arange(6), (2, 3)) * mV
395 assert_equal(quantity[:], quantity)
396 assert_equal(quantity[0], np.asarray(quantity)[0] * volt)
397 assert_equal(quantity[0:1], np.asarray(quantity)[0:1] * volt)
398 assert_equal(quantity[0, 1], np.asarray(quantity)[0, 1] * volt)
399 assert_equal(quantity[0:1, 1:], np.asarray(quantity)[0:1, 1:] * volt)
400 bool_matrix = np.array([[True, False, False], [False, False, True]])
401 assert_equal(quantity[bool_matrix], np.asarray(quantity)[bool_matrix] * volt)
402
403
404 @pytest.mark.codegen_independent
405 def test_setting():
406 quantity = np.reshape(np.arange(6), (2, 3)) * mV
407 quantity[0, 1] = 10 * mV
408 assert quantity[0, 1] == 10 * mV
409 quantity[:, 1] = 20 * mV
410 assert np.all(quantity[:, 1] == 20 * mV)
411 quantity[1, :] = np.ones((1, 3)) * volt
412 assert np.all(quantity[1, :] == 1 * volt)
413 # Setting to zero should work without units as well
414 quantity[1, 2] = 0
415 assert quantity[1, 2] == 0 * mV
416
417 def set_to_value(key, value):
418 quantity[key] = value
419
420 with pytest.raises(DimensionMismatchError):
421 set_to_value(0, 1)
422 with pytest.raises(DimensionMismatchError):
423 set_to_value(0, 1 * second)
424 with pytest.raises(DimensionMismatchError):
425 set_to_value((slice(2), slice(3)), np.ones((2, 3)))
426
427
428 @pytest.mark.codegen_independent
429 def test_multiplication_division():
430 quantities = [3 * mV, np.array([1, 2]) * mV, np.ones((3, 3)) * mV]
431 q2 = 5 * second
432
433 for q in quantities:
434 # Scalars and array scalars
435 assert_quantity(q / 3, np.asarray(q) / 3, volt)
436 assert_quantity(3 / q, 3 / np.asarray(q), 1 / volt)
437 assert_quantity(q * 3, np.asarray(q) * 3, volt)
438 assert_quantity(3 * q, 3 * np.asarray(q), volt)
439 assert_quantity(q / np.float64(3), np.asarray(q) / 3, volt)
440 assert_quantity(np.float64(3) / q, 3 / np.asarray(q), 1 / volt)
441 assert_quantity(q * np.float64(3), np.asarray(q) * 3, volt)
442 assert_quantity(np.float64(3) * q, 3 * np.asarray(q), volt)
443 assert_quantity(q / np.array(3), np.asarray(q) / 3, volt)
444 assert_quantity(np.array(3) / q, 3 / np.asarray(q), 1 / volt)
445 assert_quantity(q * np.array(3), np.asarray(q) * 3, volt)
446 assert_quantity(np.array(3) * q, 3 * np.asarray(q), volt)
447
448 # (unitless) arrays
449 assert_quantity(q / np.array([3]), np.asarray(q) / 3, volt)
450 assert_quantity(np.array([3]) / q, 3 / np.asarray(q), 1 / volt)
451 assert_quantity(q * np.array([3]), np.asarray(q) * 3, volt)
452 assert_quantity(np.array([3]) * q, 3 * np.asarray(q), volt)
453
454 # arrays with units
455 assert_quantity(q / q, np.asarray(q) / np.asarray(q), 1)
456 assert_quantity(q * q, np.asarray(q) ** 2, volt**2)
457 assert_quantity(q / q2, np.asarray(q) / np.asarray(q2), volt / second)
458 assert_quantity(q2 / q, np.asarray(q2) / np.asarray(q), second / volt)
459 assert_quantity(q * q2, np.asarray(q) * np.asarray(q2), volt * second)
460
461 # using unsupported objects should fail
462 with pytest.raises(TypeError):
463 q / "string"
464 with pytest.raises(TypeError):
465 "string" / q
466 with pytest.raises(TypeError):
467 "string" * q
468 with pytest.raises(TypeError):
469 q * "string"
470
471
472 @pytest.mark.codegen_independent
473 def test_addition_subtraction():
474 quantities = [3 * mV, np.array([1, 2]) * mV, np.ones((3, 3)) * mV]
475 q2 = 5 * volt
476
477 for q in quantities:
478 # arrays with units
479 assert_quantity(q + q, np.asarray(q) + np.asarray(q), volt)
480 assert_quantity(q - q, 0, volt)
481 assert_quantity(q + q2, np.asarray(q) + np.asarray(q2), volt)
482 assert_quantity(q2 + q, np.asarray(q2) + np.asarray(q), volt)
483 assert_quantity(q - q2, np.asarray(q) - np.asarray(q2), volt)
484 assert_quantity(q2 - q, np.asarray(q2) - np.asarray(q), volt)
485
486 # mismatching units
487 with pytest.raises(DimensionMismatchError):
488 q + 5 * second
489 with pytest.raises(DimensionMismatchError):
490 5 * second + q
491 with pytest.raises(DimensionMismatchError):
492 q - 5 * second
493 with pytest.raises(DimensionMismatchError):
494 5 * second - q
495
496 # scalar
497 with pytest.raises(DimensionMismatchError):
498 q + 5
499 with pytest.raises(DimensionMismatchError):
500 5 + q
501 with pytest.raises(DimensionMismatchError):
502 q + np.float64(5)
503 with pytest.raises(DimensionMismatchError):
504 np.float64(5) + q
505 with pytest.raises(DimensionMismatchError):
506 q - 5
507 with pytest.raises(DimensionMismatchError):
508 5 - q
509 with pytest.raises(DimensionMismatchError):
510 q - np.float64(5)
511 with pytest.raises(DimensionMismatchError):
512 np.float64(5) - q
513
514 # unitless array
515 with pytest.raises(DimensionMismatchError):
516 q + np.array([5])
517 with pytest.raises(DimensionMismatchError):
518 np.array([5]) + q
519 with pytest.raises(DimensionMismatchError):
520 q + np.array([5], dtype=np.float64)
521 with pytest.raises(DimensionMismatchError):
522 np.array([5], dtype=np.float64) + q
523 with pytest.raises(DimensionMismatchError):
524 q - np.array([5])
525 with pytest.raises(DimensionMismatchError):
526 np.array([5]) - q
527 with pytest.raises(DimensionMismatchError):
528 q - np.array([5], dtype=np.float64)
529 with pytest.raises(DimensionMismatchError):
530 np.array([5], dtype=np.float64) - q
531
532 # Check that operations with 0 work
533 assert_quantity(q + 0, np.asarray(q), volt)
534 assert_quantity(0 + q, np.asarray(q), volt)
535 assert_quantity(q - 0, np.asarray(q), volt)
536 assert_quantity(0 - q, -np.asarray(q), volt)
537 assert_quantity(q + np.float64(0), np.asarray(q), volt)
538 assert_quantity(np.float64(0) + q, np.asarray(q), volt)
539 assert_quantity(q - np.float64(0), np.asarray(q), volt)
540 assert_quantity(np.float64(0) - q, -np.asarray(q), volt)
541
542 # using unsupported objects should fail
543 with pytest.raises(TypeError):
544 "string" + q
545 with pytest.raises(TypeError):
546 q + "string"
547 with pytest.raises(TypeError):
548 q - "string"
549 with pytest.raises(TypeError):
550 "string" - q
551
552
553 @pytest.mark.codegen_independent
554 def test_unary_operations():
555 from operator import neg, pos
556
557 for op in [neg, pos]:
558 for x in [2, np.array([2]), np.array([1, 2])]:
559 assert_quantity(op(x * kilogram), op(x), kilogram)
560
561
562 @pytest.mark.codegen_independent
563 def test_binary_operations():
564 """Test whether binary operations work when they should and raise
565 DimensionMismatchErrors when they should.
566 Does not test for the actual result.
567 """
568 from operator import add, eq, ge, gt, le, lt, ne, sub
569
570 def assert_operations_work(a, b):
571 try:
572 # Test python builtins
573 tryops = [add, sub, lt, le, gt, ge, eq, ne]
574 for op in tryops:
575 op(a, b)
576 op(b, a)
577
578 # Test equivalent numpy functions
579 numpy_funcs = [
580 np.add,
581 np.subtract,
582 np.less,
583 np.less_equal,
584 np.greater,
585 np.greater_equal,
586 np.equal,
587 np.not_equal,
588 np.maximum,
589 np.minimum,
590 ]
591 for numpy_func in numpy_funcs:
592 numpy_func(a, b)
593 numpy_func(b, a)
594 except DimensionMismatchError as ex:
595 raise AssertionError(f"Operation raised unexpected exception: {ex}")
596
597 def assert_operations_do_not_work(a, b):
598 # Test python builtins
599 tryops = [add, sub, lt, le, gt, ge, eq, ne]
600 for op in tryops:
601 with pytest.raises(DimensionMismatchError):
602 op(a, b)
603 with pytest.raises(DimensionMismatchError):
604 op(b, a)
605
606 # Test equivalent numpy functions
607 numpy_funcs = [
608 np.add,
609 np.subtract,
610 np.less,
611 np.less_equal,
612 np.greater,
613 np.greater_equal,
614 np.equal,
615 np.not_equal,
616 np.maximum,
617 np.minimum,
618 ]
619 for numpy_func in numpy_funcs:
620 with pytest.raises(DimensionMismatchError):
621 numpy_func(a, b)
622 with pytest.raises(DimensionMismatchError):
623 numpy_func(b, a)
624
625 #
626 # Check that consistent units work
627 #
628
629 # unit arrays
630 a = 1 * kilogram
631 for b in [2 * kilogram, np.array([2]) * kilogram, np.array([1, 2]) * kilogram]:
632 assert_operations_work(a, b)
633
634 # dimensionless units and scalars
635 a = 1
636 for b in [
637 2 * kilogram / kilogram,
638 np.array([2]) * kilogram / kilogram,
639 np.array([1, 2]) * kilogram / kilogram,
640 ]:
641 assert_operations_work(a, b)
642
643 # dimensionless units and unitless arrays
644 a = np.array([1])
645 for b in [
646 2 * kilogram / kilogram,
647 np.array([2]) * kilogram / kilogram,
648 np.array([1, 2]) * kilogram / kilogram,
649 ]:
650 assert_operations_work(a, b)
651
652 #
653 # Check that inconsistent units do not work
654 #
655
656 # unit arrays
657 a = np.array([1]) * second
658 for b in [2 * kilogram, np.array([2]) * kilogram, np.array([1, 2]) * kilogram]:
659 assert_operations_do_not_work(a, b)
660
661 # unitless array
662 a = np.array([1])
663 for b in [2 * kilogram, np.array([2]) * kilogram, np.array([1, 2]) * kilogram]:
664 assert_operations_do_not_work(a, b)
665
666 # scalar
667 a = 1
668 for b in [2 * kilogram, np.array([2]) * kilogram, np.array([1, 2]) * kilogram]:
669 assert_operations_do_not_work(a, b)
670
671 # Check that comparisons with inf/-inf always work
672 values = [
673 2 * kilogram / kilogram,
674 2 * kilogram,
675 np.array([2]) * kilogram,
676 np.array([1, 2]) * kilogram,
677 ]
678 for value in values:
679 assert np.all(value < np.inf)
680 assert np.all(np.inf > value)
681 assert np.all(value <= np.inf)
682 assert np.all(np.inf >= value)
683 assert np.all(value != np.inf)
684 assert np.all(np.inf != value)
685 assert np.all(value >= -np.inf)
686 assert np.all(-np.inf <= value)
687 assert np.all(value > -np.inf)
688 assert np.all(-np.inf < value)
689
690
691 @pytest.mark.codegen_independent
692 def test_power():
693 """
694 Test raising quantities to a power.
695 """
696 values = [2 * kilogram, np.array([2]) * kilogram, np.array([1, 2]) * kilogram]
697 for value in values:
698 assert_quantity(value**3, np.asarray(value) ** 3, kilogram**3)
699 # Test raising to a dimensionless quantity
700 assert_quantity(value ** (3 * volt / volt), np.asarray(value) ** 3, kilogram**3)
701 with pytest.raises(DimensionMismatchError):
702 # FIXME: Not that if float(exponent) is a special value such as 1 or 2
703 # numpy will actually use a ufunc such as identity or square, which will
704 # not raise a DimensionMismatchError. This is a limitation of the current
705 # implementation.
706 value ** (2 * mV)
707 with pytest.raises(TypeError):
708 value ** np.array([2, 3])
709
710
711 @pytest.mark.codegen_independent
712 def test_inplace_operations():
713 q = np.arange(10) * volt
714 q_orig = q.copy()
715 q_ref = q
716
717 q *= 2
718 assert np.array_equal(q, 2 * q_orig)
719 assert np.array_equal(q_ref, q)
720 q /= 2
721 assert np.array_equal(q, q_orig)
722 assert np.array_equal(q_ref, q)
723 q += 1 * volt
724 assert np.array_equal(q, q_orig + 1 * volt)
725 assert np.array_equal(q_ref, q)
726 q -= 1 * volt
727 assert np.array_equal(q, q_orig)
728 assert np.array_equal(q_ref, q)
729 q **= 2
730 assert np.array_equal(q, q_orig**2)
731 assert np.array_equal(q_ref, q)
732 q **= 0.5
733 assert np.array_equal(q, q_orig)
734 assert np.array_equal(q_ref, q)
735
736 def illegal_add(q2):
737 q = np.arange(10) * volt
738 q += q2
739
740 with pytest.raises(DimensionMismatchError):
741 illegal_add(1 * second)
742 with pytest.raises(DimensionMismatchError):
743 illegal_add(1)
744
745 def illegal_sub(q2):
746 q = np.arange(10) * volt
747 q -= q2
748
749 with pytest.raises(DimensionMismatchError):
750 illegal_add(1 * second)
751 with pytest.raises(DimensionMismatchError):
752 illegal_add(1)
753
754 def illegal_pow(q2):
755 q = np.arange(10) * volt
756 q **= q2
757
758 with pytest.raises(DimensionMismatchError):
759 illegal_pow(1 * mV)
760 with pytest.raises(TypeError):
761 illegal_pow(np.arange(10))
762
763 # inplace operations with unsupported objects should fail
764 for inplace_op in [
765 q.__iadd__,
766 q.__isub__,
767 q.__imul__,
768 q.__itruediv__,
769 q.__ifloordiv__,
770 q.__imod__,
771 q.__ipow__,
772 ]:
773 try:
774 result = inplace_op("string")
775 # if it doesn't fail with an error, it should return NotImplemented
776 assert result == NotImplemented
777 except TypeError:
778 pass # raised on numpy >= 0.10
779
780 # make sure that inplace operations do not work on units/dimensions at all
781 for inplace_op in [
782 volt.__iadd__,
783 volt.__isub__,
784 volt.__imul__,
785 volt.__itruediv__,
786 volt.__ifloordiv__,
787 volt.__imod__,
788 volt.__ipow__,
789 ]:
790 with pytest.raises(TypeError):
791 inplace_op(volt)
792 for inplace_op in [
793 volt.dimensions.__imul__,
794 volt.dimensions.__itruediv__,
795 volt.dimensions.__ipow__,
796 ]:
797 with pytest.raises(TypeError):
798 inplace_op(volt.dimensions)
799
800
801 @pytest.mark.codegen_independent
802 def test_unit_discarding_functions():
803 """
804 Test functions that discard units.
805 """
806 from brian2.units.unitsafefunctions import ones_like, zeros_like
807
808 values = [3 * mV, np.array([1, 2]) * mV, np.arange(12).reshape(3, 4) * mV]
809 for value in values:
810 assert_equal(np.sign(value), np.sign(np.asarray(value)))
811 assert_equal(zeros_like(value), np.zeros_like(np.asarray(value)))
812 assert_equal(ones_like(value), np.ones_like(np.asarray(value)))
813 # Calling non-zero on a 0d array is deprecated, don't test it:
814 if value.ndim > 0:
815 assert_equal(np.nonzero(value), np.nonzero(np.asarray(value)))
816
817
818 @pytest.mark.codegen_independent
819 def test_unitsafe_functions():
820 """
821 Test the unitsafe functions wrapping their numpy counterparts.
822 """
823 from brian2.units.unitsafefunctions import (
824 arccos,
825 arccosh,
826 arcsin,
827 arcsinh,
828 arctan,
829 arctanh,
830 cos,
831 cosh,
832 exp,
833 log,
834 sin,
835 sinh,
836 tan,
837 tanh,
838 )
839
840 # All functions with their numpy counterparts
841 funcs = [
842 (sin, np.sin),
843 (sinh, np.sinh),
844 (arcsin, np.arcsin),
845 (arcsinh, np.arcsinh),
846 (cos, np.cos),
847 (cosh, np.cosh),
848 (arccos, np.arccos),
849 (arccosh, np.arccosh),
850 (tan, np.tan),
851 (tanh, np.tanh),
852 (arctan, np.arctan),
853 (arctanh, np.arctanh),
854 (log, np.log),
855 (exp, np.exp),
856 ]
857
858 unitless_values = [
859 3 * mV / mV,
860 np.array([1, 2]) * mV / mV,
861 np.ones((3, 3)) * mV / mV,
862 ]
863 numpy_values = [3, np.array([1, 2]), np.ones((3, 3))]
864 unit_values = [3 * mV, np.array([1, 2]) * mV, np.ones((3, 3)) * mV]
865
866 for func, np_func in funcs:
867 # make sure these functions raise errors when run on values with dimensions
868 for val in unit_values:
869 with pytest.raises(DimensionMismatchError):
870 func(val)
871
872 # make sure the functions are equivalent to their numpy counterparts
873 # when run on unitless values while ignoring warnings about invalid
874 # values or divisions by zero
875 with warnings.catch_warnings():
876 warnings.simplefilter("ignore")
877
878 for val in unitless_values:
879 assert_equal(func(val), np_func(val))
880
881 for val in numpy_values:
882 assert_equal(func(val), np_func(val))
883
884
885 @pytest.mark.codegen_independent
886 def test_special_case_numpy_functions():
887 """
888 Test a couple of functions/methods that need special treatment.
889 """
890 from brian2.units.unitsafefunctions import diagonal, dot, ravel, trace, where
891
892 quadratic_matrix = np.reshape(np.arange(9), (3, 3)) * mV
893
894 # Temporarily suppress warnings related to the matplotlib 1.3 bug
895 with warnings.catch_warnings():
896 warnings.simplefilter("ignore")
897 # Check that function and method do the same thing
898 assert_equal(ravel(quadratic_matrix), quadratic_matrix.ravel())
899 # Check that function gives the same result as on unitless arrays
900 assert_equal(
901 np.asarray(ravel(quadratic_matrix)), ravel(np.asarray(quadratic_matrix))
902 )
903 # Check that the function gives the same results as the original numpy
904 # function
905 assert_equal(
906 np.ravel(np.asarray(quadratic_matrix)), ravel(np.asarray(quadratic_matrix))
907 )
908
909 # Do the same checks for diagonal, trace and dot
910 assert_equal(diagonal(quadratic_matrix), quadratic_matrix.diagonal())
911 assert_equal(
912 np.asarray(diagonal(quadratic_matrix)), diagonal(np.asarray(quadratic_matrix))
913 )
914 assert_equal(
915 np.diagonal(np.asarray(quadratic_matrix)),
916 diagonal(np.asarray(quadratic_matrix)),
917 )
918
919 assert_equal(trace(quadratic_matrix), quadratic_matrix.trace())
920 assert_equal(
921 np.asarray(trace(quadratic_matrix)), trace(np.asarray(quadratic_matrix))
922 )
923 assert_equal(
924 np.trace(np.asarray(quadratic_matrix)), trace(np.asarray(quadratic_matrix))
925 )
926
927 assert_equal(
928 dot(quadratic_matrix, quadratic_matrix), quadratic_matrix.dot(quadratic_matrix)
929 )
930 assert_equal(
931 np.asarray(dot(quadratic_matrix, quadratic_matrix)),
932 dot(np.asarray(quadratic_matrix), np.asarray(quadratic_matrix)),
933 )
934 assert_equal(
935 np.dot(np.asarray(quadratic_matrix), np.asarray(quadratic_matrix)),
936 dot(np.asarray(quadratic_matrix), np.asarray(quadratic_matrix)),
937 )
938
939 assert_equal(
940 np.asarray(quadratic_matrix.prod()), np.asarray(quadratic_matrix).prod()
941 )
942 assert_equal(
943 np.asarray(quadratic_matrix.prod(axis=0)),
944 np.asarray(quadratic_matrix).prod(axis=0),
945 )
946
947 # Check for correct units
948 if use_matplotlib_units_fix:
949 assert have_same_dimensions(1, ravel(quadratic_matrix))
950 else:
951 assert have_same_dimensions(quadratic_matrix, ravel(quadratic_matrix))
952 assert have_same_dimensions(quadratic_matrix, trace(quadratic_matrix))
953 assert have_same_dimensions(quadratic_matrix, diagonal(quadratic_matrix))
954 assert have_same_dimensions(
955 quadratic_matrix[0] ** 2, dot(quadratic_matrix, quadratic_matrix)
956 )
957 assert have_same_dimensions(
958 quadratic_matrix.prod(axis=0), quadratic_matrix[0] ** quadratic_matrix.shape[0]
959 )
960
961 # check the where function
962 # pure numpy array
963 cond = [True, False, False]
964 ar1 = np.array([1, 2, 3])
965 ar2 = np.array([4, 5, 6])
966 assert_equal(np.where(cond), where(cond))
967 assert_equal(np.where(cond, ar1, ar2), where(cond, ar1, ar2))
968
969 # dimensionless quantity
970 assert_equal(
971 np.where(cond, ar1, ar2), np.asarray(where(cond, ar1 * mV / mV, ar2 * mV / mV))
972 )
973
974 # quantity with dimensions
975 ar1 = ar1 * mV
976 ar2 = ar2 * mV
977 assert_equal(
978 np.where(cond, np.asarray(ar1), np.asarray(ar2)),
979 np.asarray(where(cond, ar1, ar2)),
980 )
981
982 # Check some error cases
983 with pytest.raises(ValueError):
984 where(cond, ar1)
985 with pytest.raises(TypeError):
986 where(cond, ar1, ar1, ar2)
987 with pytest.raises(DimensionMismatchError):
988 where(cond, ar1, ar1 / ms)
989
990 # Check setasflat (for numpy < 1.7)
991 if hasattr(Quantity, "setasflat"):
992 a = np.arange(10) * mV
993 b = np.ones(10).reshape(5, 2) * volt
994 c = np.ones(10).reshape(5, 2) * second
995 with pytest.raises(DimensionMismatchError):
996 a.setasflat(c)
997 a.setasflat(b)
998 assert_equal(a.flatten(), b.flatten())
999
1000 # Check cumprod
1001 a = np.arange(1, 10) * mV / mV
1002 assert_equal(a.cumprod(), np.asarray(a).cumprod())
1003 with pytest.raises(TypeError):
1004 (np.arange(1, 5) * mV).cumprod()
1005
1006
1007 # Functions that should not change units
1008 @pytest.mark.codegen_independent
1009 def test_numpy_functions_same_dimensions():
1010 values = [np.array([1, 2]), np.ones((3, 3))]
1011 units = [volt, second, siemens, mV, kHz]
1012
1013 from brian2.units.unitsafefunctions import ptp
1014
1015 # numpy functions
1016 keep_dim_funcs = [
1017 np.abs,
1018 np.cumsum,
1019 np.max,
1020 np.mean,
1021 np.min,
1022 np.negative,
1023 ptp,
1024 np.round,
1025 np.squeeze,
1026 np.std,
1027 np.sum,
1028 np.transpose,
1029 ]
1030
1031 for value, unit in itertools.product(values, units):
1032 q_ar = value * unit
1033 for func in keep_dim_funcs:
1034 test_ar = func(q_ar)
1035 if not get_dimensions(test_ar) is q_ar.dim:
1036 raise AssertionError(
1037 f"'{func.__name__}' failed on {q_ar!r} -- dim was "
1038 f"{q_ar.dim}, is now {get_dimensions(test_ar)}."
1039 )
1040
1041 # Python builtins should work on one-dimensional arrays
1042 value = np.arange(5)
1043 builtins = [abs, max, min, sum]
1044 for unit in units:
1045 q_ar = value * unit
1046 for func in builtins:
1047 test_ar = func(q_ar)
1048 if not get_dimensions(test_ar) is q_ar.dim:
1049 raise AssertionError(
1050 f"'{func.__name__}' failed on {q_ar!r} -- dim "
1051 f"was {q_ar.dim}, is now "
1052 f"{get_dimensions(test_ar)}"
1053 )
1054
1055
1056 @pytest.mark.codegen_independent
1057 def test_numpy_functions_indices():
1058 """
1059 Check numpy functions that return indices.
1060 """
1061 values = [np.array([-4, 3, -2, 1, 0]), np.ones((3, 3)), np.array([17])]
1062 units = [volt, second, siemens, mV, kHz]
1063
1064 # numpy functions
1065 keep_dim_funcs = [np.argmin, np.argmax, np.argsort, np.nonzero]
1066
1067 for value, unit in itertools.product(values, units):
1068 q_ar = value * unit
1069 for func in keep_dim_funcs:
1070 test_ar = func(q_ar)
1071 # Compare it to the result on the same value without units
1072 comparison_ar = func(value)
1073 assert_equal(
1074 test_ar,
1075 comparison_ar,
1076 (
1077 "function %s returned an incorrect result when used on quantities "
1078 % func.__name__
1079 ),
1080 )
1081
1082
1083 @pytest.mark.codegen_independent
1084 def test_numpy_functions_dimensionless():
1085 """
1086 Test that numpy functions that should work on dimensionless quantities only
1087 work dimensionless arrays and return the correct result.
1088 """
1089 unitless_values = [3, np.array([-4, 3, -1, 2]), np.ones((3, 3))]
1090 unit_values = [3 * mV, np.array([-4, 3, -1, 2]) * mV, np.ones((3, 3)) * mV]
1091 with warnings.catch_warnings():
1092 # ignore division by 0 warnings
1093 warnings.simplefilter("ignore", RuntimeWarning)
1094 for value in unitless_values:
1095 for ufunc in UFUNCS_DIMENSIONLESS:
1096 result_unitless = eval(f"np.{ufunc}(value)")
1097 result_array = eval(f"np.{ufunc}(np.array(value))")
1098 assert isinstance(
1099 result_unitless, (np.ndarray, np.number)
1100 ) and not isinstance(result_unitless, Quantity)
1101 assert_equal(result_unitless, result_array)
1102 for ufunc in UFUNCS_DIMENSIONLESS_TWOARGS:
1103 result_unitless = eval(f"np.{ufunc}(value, value)")
1104 result_array = eval(f"np.{ufunc}(np.array(value), np.array(value))")
1105 assert isinstance(
1106 result_unitless, (np.ndarray, np.number)
1107 ) and not isinstance(result_unitless, Quantity)
1108 assert_equal(result_unitless, result_array)
1109
1110 for value, unitless_value in zip(unit_values, unitless_values):
1111 for ufunc in UFUNCS_DIMENSIONLESS:
1112 with pytest.raises(DimensionMismatchError):
1113 eval(f"np.{ufunc}(value)", globals(), {"value": value})
1114 for ufunc in UFUNCS_DIMENSIONLESS_TWOARGS:
1115 with pytest.raises(DimensionMismatchError):
1116 eval(
1117 f"np.{ufunc}(value1, value2)",
1118 globals(),
1119 {"value1": value, "value2": unitless_value},
1120 )
1121 with pytest.raises(DimensionMismatchError):
1122 eval(
1123 f"np.{ufunc}(value2, value1)",
1124 globals(),
1125 {"value1": value, "value2": unitless_value},
1126 )
1127 with pytest.raises(DimensionMismatchError):
1128 eval(f"np.{ufunc}(value, value)", globals(), {"value": value})
1129
1130
1131 @pytest.mark.codegen_independent
1132 def test_numpy_functions_change_dimensions():
1133 """
1134 Test some numpy functions that change the dimensions of the quantity.
1135 """
1136 unit_values = [np.array([1, 2]) * mV, np.ones((3, 3)) * 2 * mV]
1137 for value in unit_values:
1138 assert_quantity(np.var(value), np.var(np.array(value)), volt**2)
1139 assert_quantity(np.square(value), np.square(np.array(value)), volt**2)
1140 assert_quantity(np.sqrt(value), np.sqrt(np.array(value)), volt**0.5)
1141 assert_quantity(
1142 np.reciprocal(value), np.reciprocal(np.array(value)), 1.0 / volt
1143 )
1144
1145
1146 @pytest.mark.codegen_independent
1147 def test_numpy_functions_matmul():
1148 """
1149 Check support for matmul and the ``@`` operator.
1150 """
1151 no_units_eye = np.eye(3)
1152 with_units_eye = no_units_eye * Mohm
1153 matrix_no_units = np.arange(9).reshape((3, 3))
1154 matrix_units = matrix_no_units * nA
1155
1156 # First operand with units
1157 assert_allclose(no_units_eye @ matrix_units, matrix_units)
1158 assert have_same_dimensions(no_units_eye @ matrix_units, matrix_units)
1159 assert_allclose(np.matmul(no_units_eye, matrix_units), matrix_units)
1160 assert have_same_dimensions(np.matmul(no_units_eye, matrix_units), matrix_units)
1161
1162 # Second operand with units
1163 assert_allclose(with_units_eye @ matrix_no_units, matrix_no_units * Mohm)
1164 assert have_same_dimensions(
1165 with_units_eye @ matrix_no_units, matrix_no_units * Mohm
1166 )
1167 assert_allclose(np.matmul(with_units_eye, matrix_no_units), matrix_no_units * Mohm)
1168 assert have_same_dimensions(
1169 np.matmul(with_units_eye, matrix_no_units), matrix_no_units * Mohm
1170 )
1171
1172 # Both operands with units
1173 assert_allclose(
1174 with_units_eye @ matrix_units, no_units_eye @ matrix_no_units * nA * Mohm
1175 )
1176 assert have_same_dimensions(with_units_eye @ matrix_units, nA * Mohm)
1177 assert_allclose(
1178 np.matmul(with_units_eye, matrix_units),
1179 np.matmul(no_units_eye, matrix_no_units) * nA * Mohm,
1180 )
1181 assert have_same_dimensions(np.matmul(with_units_eye, matrix_units), nA * Mohm)
1182
1183
1184 @pytest.mark.codegen_independent
1185 def test_numpy_functions_typeerror():
1186 """
1187 Assures that certain numpy functions raise a TypeError when called on
1188 quantities.
1189 """
1190 unitless_values = [
1191 3 * mV / mV,
1192 np.array([1, 2]) * mV / mV,
1193 np.ones((3, 3)) * mV / mV,
1194 ]
1195 unit_values = [3 * mV, np.array([1, 2]) * mV, np.ones((3, 3)) * mV]
1196 for value in unitless_values + unit_values:
1197 for ufunc in UFUNCS_INTEGERS:
1198 if ufunc == "invert":
1199 # only takes one argument
1200 with pytest.raises(TypeError):
1201 eval(f"np.{ufunc}(value)", globals(), {"value": value})
1202 else:
1203 with pytest.raises(TypeError):
1204 eval(f"np.{ufunc}(value, value)", globals(), {"value": value})
1205
1206
1207 @pytest.mark.codegen_independent
1208 def test_numpy_functions_logical():
1209 """
1210 Assure that logical numpy functions work on all quantities and return
1211 unitless boolean arrays.
1212 """
1213 unit_values1 = [3 * mV, np.array([1, 2]) * mV, np.ones((3, 3)) * mV]
1214 unit_values2 = [3 * second, np.array([1, 2]) * second, np.ones((3, 3)) * second]
1215 for ufunc in UFUNCS_LOGICAL:
1216 for value1, value2 in zip(unit_values1, unit_values2):
1217 try:
1218 # one argument
1219 result_units = eval(f"np.{ufunc}(value1)")
1220 result_array = eval(f"np.{ufunc}(np.array(value1))")
1221 except (ValueError, TypeError):
1222 # two arguments
1223 result_units = eval(f"np.{ufunc}(value1, value2)")
1224 result_array = eval(f"np.{ufunc}(np.array(value1), np.array(value2))")
1225 assert not isinstance(result_units, Quantity)
1226 assert_equal(result_units, result_array)
1227
1228
1229 @pytest.mark.codegen_independent
1230 def test_arange_linspace():
1231 # For dimensionless values, the unit-safe functions should give the same results
1232 assert_equal(brian2.arange(5), np.arange(5))
1233 assert_equal(brian2.arange(1, 5), np.arange(1, 5))
1234 assert_equal(brian2.arange(10, step=2), np.arange(10, step=2))
1235 assert_equal(brian2.arange(0, 5, 0.5), np.arange(0, 5, 0.5))
1236 assert_equal(brian2.linspace(0, 1), np.linspace(0, 1))
1237 assert_equal(brian2.linspace(0, 1, 10), np.linspace(0, 1, 10))
1238
1239 # Make sure units are checked
1240 with pytest.raises(DimensionMismatchError):
1241 brian2.arange(1 * mV, 5)
1242 with pytest.raises(DimensionMismatchError):
1243 brian2.arange(1 * mV, 5 * mV)
1244 with pytest.raises(DimensionMismatchError):
1245 brian2.arange(1, 5 * mV)
1246 with pytest.raises(DimensionMismatchError):
1247 brian2.arange(1 * mV, 5 * ms)
1248 with pytest.raises(DimensionMismatchError):
1249 brian2.arange(1 * mV, 5 * mV, step=1 * ms)
1250 with pytest.raises(DimensionMismatchError):
1251 brian2.arange(1 * ms, 5 * mV)
1252
1253 # Check correct functioning with units
1254 assert_quantity(
1255 brian2.arange(5 * mV, step=1 * mV), float(mV) * np.arange(5, step=1), mV
1256 )
1257 assert_quantity(
1258 brian2.arange(1 * mV, 5 * mV, 1 * mV), float(mV) * np.arange(1, 5, 1), mV
1259 )
1260 assert_quantity(brian2.linspace(1 * mV, 2 * mV), float(mV) * np.linspace(1, 2), mV)
1261
1262 # Check errors for arange with incorrect numbers of arguments/duplicate arguments
1263 with pytest.raises(TypeError):
1264 brian2.arange()
1265 with pytest.raises(TypeError):
1266 brian2.arange(0, 5, 1, 0)
1267 with pytest.raises(TypeError):
1268 brian2.arange(0, stop=1)
1269 with pytest.raises(TypeError):
1270 brian2.arange(0, 5, stop=1)
1271 with pytest.raises(TypeError):
1272 brian2.arange(0, 5, start=1)
1273 with pytest.raises(TypeError):
1274 brian2.arange(0, 5, 1, start=1)
1275 with pytest.raises(TypeError):
1276 brian2.arange(0, 5, 1, stop=2)
1277 with pytest.raises(TypeError):
1278 brian2.arange(0, 5, 1, step=2)
1279
1280
1281 @pytest.mark.codegen_independent
1282 def test_list():
1283 """
1284 Test converting to and from a list.
1285 """
1286 values = [3 * mV, np.array([1, 2]) * mV, np.arange(12).reshape(4, 3) * mV]
1287 for value in values:
1288 l = value.tolist()
1289 from_list = Quantity(l)
1290 assert have_same_dimensions(from_list, value)
1291 assert_equal(from_list, value)
1292
1293
1294 @pytest.mark.codegen_independent
1295 def test_check_units():
1296 """
1297 Test the check_units decorator
1298 """
1299
1300 @check_units(v=volt)
1301 def a_function(v, x):
1302 """
1303 v has to have units of volt, x can have any (or no) unit.
1304 """
1305 pass
1306
1307 # Try correct units
1308 a_function(3 * mV, 5 * second)
1309 a_function(5 * volt, "something")
1310 a_function([1, 2, 3] * volt, None)
1311 # lists that can be converted should also work
1312 a_function([1 * volt, 2 * volt, 3 * volt], None)
1313 # Strings and None are also allowed to pass
1314 a_function("a string", None)
1315 a_function(None, None)
1316
1317 # Try incorrect units
1318 with pytest.raises(DimensionMismatchError):
1319 a_function(5 * second, None)
1320 with pytest.raises(DimensionMismatchError):
1321 a_function(5, None)
1322 with pytest.raises(TypeError):
1323 a_function(object(), None)
1324 with pytest.raises(TypeError):
1325 a_function([1, 2 * volt, 3], None)
1326
1327 @check_units(result=second)
1328 def b_function(return_second):
1329 """
1330 Return a value in seconds if return_second is True, otherwise return
1331 a value in volt.
1332 """
1333 if return_second:
1334 return 5 * second
1335 else:
1336 return 3 * volt
1337
1338 # Should work (returns second)
1339 b_function(True)
1340 # Should fail (returns volt)
1341 with pytest.raises(DimensionMismatchError):
1342 b_function(False)
1343
1344 @check_units(a=bool, b=1, result=bool)
1345 def c_function(a, b):
1346 if a:
1347 return b > 0
1348 else:
1349 return b
1350
1351 assert c_function(True, 1)
1352 assert not c_function(True, -1)
1353 with pytest.raises(TypeError):
1354 c_function(1, 1)
1355 with pytest.raises(TypeError):
1356 c_function(1 * mV, 1)
1357 with pytest.raises(TypeError):
1358 c_function(False, 1)
1359
1360
1361 @pytest.mark.codegen_independent
1362 def test_get_unit():
1363 """
1364 Test get_unit
1365 """
1366 values = [
1367 (volt.dim, volt),
1368 (mV.dim, volt),
1369 ((amp / metre**2).dim, amp / metre**2),
1370 ]
1371 for dim, expected_unit in values:
1372 unit = get_unit(dim)
1373 assert isinstance(unit, Unit)
1374 assert unit == expected_unit
1375 assert float(unit) == 1.0
1376
1377
1378 @pytest.mark.codegen_independent
1379 def test_get_best_unit():
1380 # get_best_unit should not check all values for long arrays, since it is
1381 # a function used for display purposes only. Instead, only the first and
1382 # last few values should matter (see github issue #966)
1383 long_ar = np.ones(10000) * siemens
1384 long_ar[:10] = 1 * nS
1385 long_ar[-10:] = 2 * nS
1386 values = [
1387 (np.arange(10) * mV, mV),
1388 ([0.001, 0.002, 0.003] * second, ms),
1389 (long_ar, nS),
1390 ]
1391 for ar, expected_unit in values:
1392 assert ar.get_best_unit() is expected_unit
1393 assert str(expected_unit) in ar.in_best_unit()
1394
1395
1396 @pytest.mark.codegen_independent
1397 def test_switching_off_unit_checks():
1398 """
1399 Check switching off unit checks (used for external functions).
1400 """
1401 import brian2.units.fundamentalunits as fundamentalunits
1402
1403 x = 3 * second
1404 y = 5 * volt
1405 with pytest.raises(DimensionMismatchError):
1406 x + y
1407 fundamentalunits.unit_checking = False
1408 # Now it should work
1409 assert np.asarray(x + y) == np.array(8)
1410 assert have_same_dimensions(x, y)
1411 assert x.has_same_dimensions(y)
1412 fundamentalunits.unit_checking = True
1413
1414
1415 @pytest.mark.codegen_independent
1416 def test_fail_for_dimension_mismatch():
1417 """
1418 Test the fail_for_dimension_mismatch function.
1419 """
1420 # examples that should not raise an error
1421 dim1, dim2 = fail_for_dimension_mismatch(3)
1422 assert dim1 is DIMENSIONLESS
1423 assert dim2 is DIMENSIONLESS
1424 dim1, dim2 = fail_for_dimension_mismatch(3 * volt / volt)
1425 assert dim1 is DIMENSIONLESS
1426 assert dim2 is DIMENSIONLESS
1427 dim1, dim2 = fail_for_dimension_mismatch(3 * volt / volt, 7)
1428 assert dim1 is DIMENSIONLESS
1429 assert dim2 is DIMENSIONLESS
1430 dim1, dim2 = fail_for_dimension_mismatch(3 * volt, 5 * volt)
1431 assert dim1 is volt.dim
1432 assert dim2 is volt.dim
1433
1434 # examples that should raise an error
1435 with pytest.raises(DimensionMismatchError):
1436 fail_for_dimension_mismatch(6 * volt)
1437 with pytest.raises(DimensionMismatchError):
1438 fail_for_dimension_mismatch(6 * volt, 5 * second)
1439
1440
1441 @pytest.mark.codegen_independent
1442 def test_deepcopy():
1443 d = {"x": 1 * second}
1444 from copy import deepcopy
1445
1446 d_copy = deepcopy(d)
1447 assert d_copy["x"] == 1 * second
1448 d_copy["x"] += 1 * second
1449 assert d_copy["x"] == 2 * second
1450 assert d["x"] == 1 * second
1451
1452
1453 @pytest.mark.codegen_independent
1454 def test_inplace_on_scalars():
1455 # We want "copy semantics" for in-place operations on scalar quantities
1456 # in the same way as for Python scalars
1457 for scalar in [3 * mV, 3 * mV / mV]:
1458 scalar_reference = scalar
1459 scalar_copy = Quantity(scalar, copy=True)
1460 scalar += scalar_copy
1461 assert_equal(scalar_copy, scalar_reference)
1462 scalar *= 1.5
1463 assert_equal(scalar_copy, scalar_reference)
1464 scalar /= 2
1465 assert_equal(scalar_copy, scalar_reference)
1466
1467 # also check that it worked correctly for the scalar itself
1468 assert_allclose(scalar, (scalar_copy + scalar_copy) * 1.5 / 2)
1469
1470 # For arrays, it should use reference semantics
1471 for vector in [[3] * mV, [3] * mV / mV]:
1472 vector_reference = vector
1473 vector_copy = Quantity(vector, copy=True)
1474 vector += vector_copy
1475 assert_equal(vector, vector_reference)
1476 vector *= 1.5
1477 assert_equal(vector, vector_reference)
1478 vector /= 2
1479 assert_equal(vector, vector_reference)
1480
1481 # also check that it worked correctly for the vector itself
1482 assert_allclose(vector, (vector_copy + vector_copy) * 1.5 / 2)
1483
1484
1485 def test_units_vs_quantities():
1486 # Unit objects should stay Unit objects under certain operations
1487 # (important e.g. in the unit definition of Equations, where only units but
1488 # not quantities are allowed)
1489 assert isinstance(meter**2, Unit)
1490 assert isinstance(meter**-1, Unit)
1491 assert isinstance(meter**0.5, Unit)
1492 assert isinstance(meter / second, Unit)
1493 assert isinstance(amp / meter**2, Unit)
1494 assert isinstance(1 / meter, Unit)
1495 assert isinstance(1.0 / meter, Unit)
1496
1497 # Using the unconventional type(x) == y since we want to test that
1498 # e.g. meter**2 stays a Unit and does not become a Quantity however Unit
1499 # inherits from Quantity and therefore both would pass the isinstance test
1500 assert type(2 / meter) == Quantity
1501 assert type(2 * meter) == Quantity
1502 assert type(meter + meter) == Quantity
1503 assert type(meter - meter) == Quantity
1504
1505
1506 @pytest.mark.codegen_independent
1507 def test_all_units_list():
1508 from brian2.units.allunits import all_units
1509
1510 assert meter in all_units
1511 assert volt in all_units
1512 assert cm in all_units
1513 assert Hz in all_units
1514 assert all(isinstance(u, Unit) for u in all_units)
1515
1516
1517 @pytest.mark.codegen_independent
1518 def test_constants():
1519 import brian2.units.constants as constants
1520
1521 # Check that the expected names exist and have the correct dimensions
1522 assert constants.avogadro_constant.dim == (1 / mole).dim
1523 assert constants.boltzmann_constant.dim == (joule / kelvin).dim
1524 assert constants.electric_constant.dim == (farad / meter).dim
1525 assert constants.electron_mass.dim == kilogram.dim
1526 assert constants.elementary_charge.dim == coulomb.dim
1527 assert constants.faraday_constant.dim == (coulomb / mole).dim
1528 assert constants.gas_constant.dim == (joule / mole / kelvin).dim
1529 assert constants.magnetic_constant.dim == (newton / amp2).dim
1530 assert constants.molar_mass_constant.dim == (kilogram / mole).dim
1531 assert constants.zero_celsius.dim == kelvin.dim
1532
1533 # Check the consistency between a few constants
1534 assert_allclose(
1535 constants.gas_constant,
1536 constants.avogadro_constant * constants.boltzmann_constant,
1537 )
1538 assert_allclose(
1539 constants.faraday_constant,
1540 constants.avogadro_constant * constants.elementary_charge,
1541 )
1542
1543
1544 if __name__ == "__main__":
1545 test_construction()
1546 test_get_dimensions()
1547 test_display()
1548 test_scale()
1549 test_power()
1550 test_pickling()
1551 test_str_repr()
1552 test_slicing()
1553 test_setting()
1554 test_multiplication_division()
1555 test_addition_subtraction()
1556 test_unary_operations()
1557 test_binary_operations()
1558 test_inplace_operations()
1559 test_unit_discarding_functions()
1560 test_unitsafe_functions()
1561 test_special_case_numpy_functions()
1562 test_numpy_functions_same_dimensions()
1563 test_numpy_functions_indices()
1564 test_numpy_functions_dimensionless()
1565 test_numpy_functions_change_dimensions()
1566 test_numpy_functions_typeerror()
1567 test_numpy_functions_logical()
1568 test_arange_linspace()
1569 test_list()
1570 test_check_units()
1571 test_get_unit()
1572 test_get_best_unit()
1573 test_switching_off_unit_checks()
1574 test_fail_for_dimension_mismatch()
1575 test_deepcopy()
1576 test_inplace_on_scalars()
1577 test_units_vs_quantities()
1578 test_all_units_list()
1579 test_constants()