Debian Codegraph @

brian2/units/fundamentalunits.py

raw
1 """
2 Defines physical units and quantities
3
4 ===================== ======== ======
5 Quantity Unit Symbol
6 --------------------- -------- ------
7 Length metre m
8 Mass kilogram kg
9 Time second s
10 Electric current ampere A
11 Temperature kelvin K
12 Quantity of substance mole mol
13 Luminosity candle cd
14 ===================== ======== ======
15 """
16
17 import collections
18 import functools
19 import itertools
20 import numbers
21 import operator
22 import sys
23 from collections.abc import Callable
24 from warnings import warn
25
26 import numpy as np
27
28 try:
29 from numpy.exceptions import VisibleDeprecationWarning # numpy 2.x
30 except ImportError:
31 from numpy import VisibleDeprecationWarning # numpy 1.x
32
33 from sympy import latex
34
35 __all__ = [
36 "DimensionMismatchError",
37 "get_or_create_dimension",
38 "get_dimensions",
39 "is_dimensionless",
40 "have_same_dimensions",
41 "in_unit",
42 "in_best_unit",
43 "Quantity",
44 "Unit",
45 "register_new_unit",
46 "check_units",
47 "is_scalar_type",
48 "get_unit",
49 ]
50
51
52 unit_checking = True
53
54
55 def _flatten(iterable):
56 """
57 Flatten a given list `iterable`.
58 """
59 for e in iterable:
60 if isinstance(e, list):
61 yield from _flatten(e)
62 else:
63 yield e
64
65
66 def _short_str(arr):
67 """
68 Return a short string representation of an array, suitable for use in
69 error messages.
70 """
71 arr = np.asanyarray(arr)
72 old_printoptions = np.get_printoptions()
73 np.set_printoptions(edgeitems=2, threshold=5)
74 arr_string = str(arr)
75 np.set_printoptions(**old_printoptions)
76 return arr_string
77
78
79 # ===============================================================================
80 # Numpy ufuncs
81 # ===============================================================================
82
83 # Note: A list of numpy ufuncs can be found here:
84 # http://docs.scipy.org/doc/numpy/reference/ufuncs.html#available-ufuncs
85
86 #: ufuncs that work on all dimensions and preserve the dimensions, e.g. abs
87 UFUNCS_PRESERVE_DIMENSIONS = [
88 "absolute",
89 "rint",
90 "negative",
91 "positive",
92 "conj",
93 "conjugate",
94 "floor",
95 "ceil",
96 "trunc",
97 ]
98
99 #: ufuncs that work on all dimensions but change the dimensions, e.g. square
100 UFUNCS_CHANGE_DIMENSIONS = [
101 "multiply",
102 "divide",
103 "true_divide",
104 "floor_divide",
105 "sqrt",
106 "square",
107 "reciprocal",
108 "dot",
109 "matmul",
110 ]
111
112 #: ufuncs that work with matching dimensions, e.g. add
113 UFUNCS_MATCHING_DIMENSIONS = [
114 "add",
115 "subtract",
116 "maximum",
117 "minimum",
118 "remainder",
119 "mod",
120 "fmod",
121 ]
122
123 #: ufuncs that compare values, i.e. work only with matching dimensions but do
124 #: not result in a value with dimensions, e.g. equals
125 UFUNCS_COMPARISONS = [
126 "less",
127 "less_equal",
128 "greater",
129 "greater_equal",
130 "equal",
131 "not_equal",
132 ]
133
134 #: Logical operations that work on all quantities and return boolean arrays
135 UFUNCS_LOGICAL = [
136 "logical_and",
137 "logical_or",
138 "logical_xor",
139 "logical_not",
140 "isreal",
141 "iscomplex",
142 "isfinite",
143 "isinf",
144 "isnan",
145 ]
146
147 #: ufuncs that only work on dimensionless quantities
148 UFUNCS_DIMENSIONLESS = [
149 "sin",
150 "sinh",
151 "arcsin",
152 "arcsinh",
153 "cos",
154 "cosh",
155 "arccos",
156 "arccosh",
157 "tan",
158 "tanh",
159 "arctan",
160 "arctanh",
161 "log",
162 "log2",
163 "log10",
164 "log1p",
165 "exp",
166 "exp2",
167 "expm1",
168 ]
169
170 #: ufuncs that only work on two dimensionless quantities
171 UFUNCS_DIMENSIONLESS_TWOARGS = ["logaddexp", "logaddexp2", "arctan2", "hypot"]
172
173 #: ufuncs that only work on integers and therefore never on quantities
174 UFUNCS_INTEGERS = [
175 "bitwise_and",
176 "bitwise_or",
177 "bitwise_xor",
178 "invert",
179 "left_shift",
180 "right_shift",
181 ]
182
183
184 # ==============================================================================
185 # Utility functions
186 # ==============================================================================
187
188
189 def fail_for_dimension_mismatch(
190 obj1, obj2=None, error_message=None, **error_quantities
191 ):
192 """
193 Compare the dimensions of two objects.
194
195 Parameters
196 ----------
197 obj1, obj2 : {array-like, `Quantity`}
198 The object to compare. If `obj2` is ``None``, assume it to be
199 dimensionless
200 error_message : str, optional
201 An error message that is used in the DimensionMismatchError
202 error_quantities : dict mapping str to `Quantity`, optional
203 Quantities in this dictionary will be converted using the `_short_str`
204 helper method and inserted into the ``error_message`` (which should
205 have placeholders with the corresponding names). The reason for doing
206 this in a somewhat complicated way instead of directly including all the
207 details in ``error_messsage`` is that converting large quantity arrays
208 to strings can be rather costly and we don't want to do it if no error
209 occured.
210
211 Returns
212 -------
213 dim1, dim2 : `Dimension`, `Dimension`
214 The physical dimensions of the two arguments (so that later code does
215 not need to get the dimensions again).
216
217 Raises
218 ------
219 DimensionMismatchError
220 If the dimensions of `obj1` and `obj2` do not match (or, if `obj2` is
221 ``None``, in case `obj1` is not dimensionsless).
222
223 Notes
224 -----
225 Implements special checking for ``0``, treating it as having "any
226 dimensions".
227 """
228 if not unit_checking:
229 return None, None
230
231 dim1 = get_dimensions(obj1)
232 if obj2 is None:
233 dim2 = DIMENSIONLESS
234 else:
235 dim2 = get_dimensions(obj2)
236
237 if dim1 is not dim2 and not (dim1 is None or dim2 is None):
238 # Special treatment for "0":
239 # if it is not a Quantity, it has "any dimension".
240 # This allows expressions like 3*mV + 0 to pass (useful in cases where
241 # zero is treated as the neutral element, e.g. in the Python sum
242 # builtin) or comparisons like 3 * mV == 0 to return False instead of
243 # failing # with a DimensionMismatchError. Note that 3*mV == 0*second
244 # is not allowed, though.
245 if (dim1 is DIMENSIONLESS and np.all(obj1 == 0)) or (
246 dim2 is DIMENSIONLESS and np.all(obj2 == 0)
247 ):
248 return dim1, dim2
249
250 # We do another check here, this should allow Brian1 units to pass as
251 # having the same dimensions as a Brian2 unit
252 if dim1 == dim2:
253 return dim1, dim2
254
255 if error_message is None:
256 error_message = "Dimension mismatch"
257 else:
258 error_quantities = {
259 name: _short_str(q) for name, q in error_quantities.items()
260 }
261 error_message = error_message.format(**error_quantities)
262 # If we are comparing an object to a specific unit, we don't want to
263 # restate this unit (it is probably mentioned in the text already)
264 if obj2 is None or isinstance(obj2, (Dimension, Unit)):
265 raise DimensionMismatchError(error_message, dim1)
266 else:
267 raise DimensionMismatchError(error_message, dim1, dim2)
268 else:
269 return dim1, dim2
270
271
272 def wrap_function_dimensionless(func):
273 """
274 Returns a new function that wraps the given function `func` so that it
275 raises a DimensionMismatchError if the function is called on a quantity
276 with dimensions (excluding dimensionless quantities). Quantities are
277 transformed to unitless numpy arrays before calling `func`.
278
279 These checks/transformations apply only to the very first argument, all
280 other arguments are ignored/untouched.
281 """
282
283 def f(x, *args, **kwds): # pylint: disable=C0111
284 fail_for_dimension_mismatch(
285 x,
286 error_message=(
287 "%s expects a dimensionless argument but got {value}" % func.__name__
288 ),
289 value=x,
290 )
291 return func(np.asarray(x), *args, **kwds)
292
293 f._arg_units = [1]
294 f._return_unit = 1
295 f.__name__ = func.__name__
296 f.__doc__ = func.__doc__
297 f._do_not_run_doctests = True
298 return f
299
300
301 def wrap_function_keep_dimensions(func):
302 """
303 Returns a new function that wraps the given function `func` so that it
304 keeps the dimensions of its input. Quantities are transformed to
305 unitless numpy arrays before calling `func`, the output is a quantity
306 with the original dimensions re-attached.
307
308 These transformations apply only to the very first argument, all
309 other arguments are ignored/untouched, allowing to work functions like
310 ``sum`` to work as expected with additional ``axis`` etc. arguments.
311 """
312
313 def f(x, *args, **kwds): # pylint: disable=C0111
314 return Quantity(func(np.asarray(x), *args, **kwds), dim=x.dim)
315
316 f._arg_units = [None]
317 f._return_unit = lambda u: u
318 f.__name__ = func.__name__
319 f.__doc__ = func.__doc__
320 f._do_not_run_doctests = True
321 return f
322
323
324 def wrap_function_change_dimensions(func, change_dim_func):
325 """
326 Returns a new function that wraps the given function `func` so that it
327 changes the dimensions of its input. Quantities are transformed to
328 unitless numpy arrays before calling `func`, the output is a quantity
329 with the original dimensions passed through the function
330 `change_dim_func`. A typical use would be a ``sqrt`` function that uses
331 ``lambda d: d ** 0.5`` as ``change_dim_func``.
332
333 These transformations apply only to the very first argument, all
334 other arguments are ignored/untouched.
335 """
336
337 def f(x, *args, **kwds): # pylint: disable=C0111
338 ar = np.asarray(x)
339 return Quantity(func(ar, *args, **kwds), dim=change_dim_func(ar, x.dim))
340
341 f._arg_units = [None]
342 f._return_unit = change_dim_func
343 f.__name__ = func.__name__
344 f.__doc__ = func.__doc__
345 f._do_not_run_doctests = True
346 return f
347
348
349 def wrap_function_remove_dimensions(func):
350 """
351 Returns a new function that wraps the given function `func` so that it
352 removes any dimensions from its input. Useful for functions that are
353 returning integers (indices) or booleans, irrespective of the datatype
354 contained in the array.
355
356 These transformations apply only to the very first argument, all
357 other arguments are ignored/untouched.
358 """
359
360 def f(x, *args, **kwds): # pylint: disable=C0111
361 return func(np.asarray(x), *args, **kwds)
362
363 f._arg_units = [None]
364 f._return_unit = 1
365 f.__name__ = func.__name__
366 f.__doc__ = func.__doc__
367 f._do_not_run_doctests = True
368 return f
369
370
371 # SI dimensions (see table at the top of the file) and various descriptions,
372 # each description maps to an index i, and the power of each dimension
373 # is stored in the variable dims[i]
374 _di = {
375 "Length": 0,
376 "length": 0,
377 "metre": 0,
378 "metres": 0,
379 "meter": 0,
380 "meters": 0,
381 "m": 0,
382 "Mass": 1,
383 "mass": 1,
384 "kilogram": 1,
385 "kilograms": 1,
386 "kg": 1,
387 "Time": 2,
388 "time": 2,
389 "second": 2,
390 "seconds": 2,
391 "s": 2,
392 "Electric Current": 3,
393 "electric current": 3,
394 "Current": 3,
395 "current": 3,
396 "ampere": 3,
397 "amperes": 3,
398 "A": 3,
399 "Temperature": 4,
400 "temperature": 4,
401 "kelvin": 4,
402 "kelvins": 4,
403 "K": 4,
404 "Quantity of Substance": 5,
405 "Quantity of substance": 5,
406 "quantity of substance": 5,
407 "Substance": 5,
408 "substance": 5,
409 "mole": 5,
410 "moles": 5,
411 "mol": 5,
412 "Luminosity": 6,
413 "luminosity": 6,
414 "candle": 6,
415 "candles": 6,
416 "cd": 6,
417 }
418
419 _ilabel = ["m", "kg", "s", "A", "K", "mol", "cd"]
420
421 # The same labels with the names used for constructing them in Python code
422 _iclass_label = ["metre", "kilogram", "second", "amp", "kelvin", "mole", "candle"]
423
424 # SI unit _prefixes as integer exponents of 10, see table at end of file.
425 _siprefixes = {
426 "y": -24,
427 "z": -21,
428 "a": -18,
429 "f": -15,
430 "p": -12,
431 "n": -9,
432 "u": -6,
433 "m": -3,
434 "c": -2,
435 "d": -1,
436 "": 0,
437 "da": 1,
438 "h": 2,
439 "k": 3,
440 "M": 6,
441 "G": 9,
442 "T": 12,
443 "P": 15,
444 "E": 18,
445 "Z": 21,
446 "Y": 24,
447 }
448
449
450 class Dimension:
451 """
452 Stores the indices of the 7 basic SI unit dimension (length, mass, etc.).
453
454 Provides a subset of arithmetic operations appropriate to dimensions:
455 multiplication, division and powers, and equality testing.
456
457 Parameters
458 ----------
459 dims : sequence of `float`
460 The dimension indices of the 7 basic SI unit dimensions.
461
462 Notes
463 -----
464 Users shouldn't use this class directly, it is used internally in Quantity
465 and Unit. Even internally, never use ``Dimension(...)`` to create a new
466 instance, use `get_or_create_dimension` instead. This function makes
467 sure that only one Dimension instance exists for every combination of
468 indices, allowing for a very fast dimensionality check with ``is``.
469 """
470
471 __slots__ = ["_dims"]
472
473 __array_priority__ = 1000
474 #### INITIALISATION ####
475
476 def __init__(self, dims):
477 self._dims = dims
478
479 #### METHODS ####
480 def get_dimension(self, d):
481 """
482 Return a specific dimension.
483
484 Parameters
485 ----------
486 d : `str`
487 A string identifying the SI basic unit dimension. Can be either a
488 description like "length" or a basic unit like "m" or "metre".
489
490 Returns
491 -------
492 dim : `float`
493 The dimensionality of the dimension `d`.
494 """
495 return self._dims[_di[d]]
496
497 @property
498 def is_dimensionless(self):
499 """
500 Whether this Dimension is dimensionless.
501
502 Notes
503 -----
504 Normally, instead one should check dimension for being identical to
505 `DIMENSIONLESS`.
506 """
507 return all([x == 0 for x in self._dims])
508
509 @property
510 def dim(self):
511 """
512 Returns the `Dimension` object itself. This can be useful, because it
513 allows to check for the dimension of an object by checking its ``dim``
514 attribute -- this will return a `Dimension` object for `Quantity`,
515 `Unit` and `Dimension`.
516 """
517 return self
518
519 #### REPRESENTATION ####
520 def _str_representation(self, python_code=False):
521 """
522 String representation in basic SI units, or ``"1"`` for dimensionless.
523 Use ``python_code=False`` for display purposes and ``True`` for valid
524 Python code.
525 """
526
527 if python_code:
528 power_operator = " ** "
529 else:
530 power_operator = "^"
531
532 parts = []
533 for i in range(len(self._dims)):
534 if self._dims[i]:
535 if python_code:
536 s = _iclass_label[i]
537 else:
538 s = _ilabel[i]
539 if self._dims[i] != 1:
540 s += power_operator + str(self._dims[i])
541 parts.append(s)
542 if python_code:
543 s = " * ".join(parts)
544 if not len(s):
545 return f"{self.__class__.__name__}()"
546 else:
547 s = " ".join(parts)
548 if not len(s):
549 return "1"
550 return s.strip()
551
552 def _latex(self, *args):
553 parts = []
554 for i in range(len(self._dims)):
555 if self._dims[i]:
556 s = _ilabel[i]
557 if self._dims[i] != 1:
558 s += "^{%s}" % str(self._dims[i])
559 parts.append(s)
560 s = "\\,".join(parts)
561 if not len(s):
562 return "1"
563 return s.strip()
564
565 def _repr_latex(self):
566 return f"${latex(self)}$"
567
568 def __repr__(self):
569 return self._str_representation(python_code=True)
570
571 def __str__(self):
572 return self._str_representation(python_code=False)
573
574 #### ARITHMETIC ####
575 # Note that none of the dimension arithmetic objects do sanity checking
576 # on their inputs, although most will throw an exception if you pass the
577 # wrong sort of input
578 def __mul__(self, value):
579 return get_or_create_dimension(
580 [x + y for x, y in zip(self._dims, value._dims, strict=True)]
581 )
582
583 def __div__(self, value):
584 return get_or_create_dimension(
585 [x - y for x, y in zip(self._dims, value._dims, strict=True)]
586 )
587
588 def __truediv__(self, value):
589 return self.__div__(value)
590
591 def __pow__(self, value):
592 value = np.asarray(value)
593 if value.size > 1:
594 raise TypeError("Too many exponents")
595 return get_or_create_dimension([x * value for x in self._dims])
596
597 def __imul__(self, value):
598 raise TypeError("Dimension object is immutable")
599
600 def __idiv__(self, value):
601 raise TypeError("Dimension object is immutable")
602
603 def __itruediv__(self, value):
604 raise TypeError("Dimension object is immutable")
605
606 def __ipow__(self, value):
607 raise TypeError("Dimension object is immutable")
608
609 #### COMPARISON ####
610 def __eq__(self, value):
611 try:
612 return np.allclose(self._dims, value._dims)
613 except AttributeError:
614 # Only compare equal to another Dimensions object
615 return False
616
617 def __ne__(self, value):
618 return not self.__eq__(value)
619
620 def __hash__(self):
621 return hash(self._dims)
622
623 #### MAKE DIMENSION PICKABLE ####
624 def __getstate__(self):
625 return self._dims
626
627 def __setstate__(self, state):
628 self._dims = state
629
630 def __reduce__(self):
631 # Make sure that unpickling Dimension objects does not bypass the singleton system
632 return (get_or_create_dimension, (self._dims,))
633
634 ### Dimension objects are singletons and deepcopy is therefore not necessary
635 def __deepcopy__(self, memodict):
636 return self
637
638
639 #: The singleton object for dimensionless Dimensions.
640 DIMENSIONLESS = Dimension((0, 0, 0, 0, 0, 0, 0))
641
642 _dimensions = {(0, 0, 0, 0, 0, 0, 0): DIMENSIONLESS}
643
644
645 def get_or_create_dimension(*args, **kwds):
646 """
647 Create a new Dimension object or get a reference to an existing one.
648 This function takes care of only creating new objects if they were not
649 created before and otherwise returning a reference to an existing object.
650 This allows to compare dimensions very efficiently using ``is``.
651
652 Parameters
653 ----------
654 args : sequence of `float`
655 A sequence with the indices of the 7 elements of an SI dimension.
656 kwds : keyword arguments
657 a sequence of ``keyword=value`` pairs where the keywords are the names of
658 the SI dimensions, or the standard unit.
659
660 Examples
661 --------
662 The following are all definitions of the dimensions of force
663
664 >>> from brian2 import *
665 >>> get_or_create_dimension(length=1, mass=1, time=-2)
666 metre * kilogram * second ** -2
667 >>> get_or_create_dimension(m=1, kg=1, s=-2)
668 metre * kilogram * second ** -2
669 >>> get_or_create_dimension([1, 1, -2, 0, 0, 0, 0])
670 metre * kilogram * second ** -2
671
672 Notes
673 -----
674 The 7 units are (in order):
675
676 Length, Mass, Time, Electric Current, Temperature,
677 Quantity of Substance, Luminosity
678
679 and can be referred to either by these names or their SI unit names,
680 e.g. length, metre, and m all refer to the same thing here.
681 """
682 if len(args):
683 # initialisation by list
684 dims = args[0]
685 try:
686 if len(dims) != 7:
687 raise TypeError()
688 except TypeError:
689 raise TypeError("Need a sequence of exactly 7 items") from None
690 else:
691 # initialisation by keywords
692 dims = [0, 0, 0, 0, 0, 0, 0]
693 for k in kwds:
694 # _di stores the index of the dimension with name 'k'
695 dims[_di[k]] = kwds[k]
696
697 dims = tuple(dims)
698
699 # check whether this Dimension object has already been created
700 if dims in _dimensions:
701 return _dimensions[dims]
702 else:
703 new_dim = Dimension(dims)
704 _dimensions[dims] = new_dim
705 return new_dim
706
707
708 class DimensionMismatchError(Exception):
709 """
710 Exception class for attempted operations with inconsistent dimensions.
711
712 For example, ``3*mvolt + 2*amp`` raises this exception. The purpose of this
713 class is to help catch errors based on incorrect units. The exception will
714 print a representation of the dimensions of the two inconsistent objects
715 that were operated on.
716
717 Parameters
718 ----------
719 description : ``str``
720 A description of the type of operation being performed, e.g. Addition,
721 Multiplication, etc.
722 dims : `Dimension`
723 The physical dimensions of the objects involved in the operation, any
724 number of them is possible
725 """
726
727 def __init__(self, description, *dims):
728 # Call the base class constructor to make Exception pickable, see:
729 # http://bugs.python.org/issue1692335
730 Exception.__init__(self, description, *dims)
731 self.dims = dims
732 self.desc = description
733
734 def __repr__(self):
735 dims_repr = [repr(dim) for dim in self.dims]
736 return f"{self.__class__.__name__}({self.desc!r}, {', '.join(dims_repr)})"
737
738 def __str__(self):
739 s = self.desc
740 if len(self.dims) == 0:
741 pass
742 elif len(self.dims) == 1:
743 s += f" (unit is {get_unit_for_display(self.dims[0])}"
744 elif len(self.dims) == 2:
745 d1, d2 = self.dims
746 s += (
747 f" (units are {get_unit_for_display(d1)} and {get_unit_for_display(d2)}"
748 )
749 else:
750 s += (
751 " (units are"
752 f" {' '.join([f'({get_unit_for_display(d)})' for d in self.dims])}"
753 )
754 if len(self.dims):
755 s += ")."
756 return s
757
758
759 def is_scalar_type(obj):
760 """
761 Tells you if the object is a 1d number type.
762
763 Parameters
764 ----------
765 obj : `object`
766 The object to check.
767
768 Returns
769 -------
770 scalar : `bool`
771 ``True`` if `obj` is a scalar that can be interpreted as a
772 dimensionless `Quantity`.
773 """
774 try:
775 return obj.ndim == 0 and is_dimensionless(obj)
776 except AttributeError:
777 return np.isscalar(obj) and not isinstance(obj, str)
778
779
780 def get_dimensions(obj):
781 """
782 Return the dimensions of any object that has them.
783
784 Slightly more general than `Quantity.dimensions` because it will
785 return `DIMENSIONLESS` if the object is of number type but not a `Quantity`
786 (e.g. a `float` or `int`).
787
788 Parameters
789 ----------
790 obj : `object`
791 The object to check.
792
793 Returns
794 -------
795 dim : `Dimension`
796 The physical dimensions of the `obj`.
797 """
798 try:
799 return obj.dim
800 except AttributeError:
801 # The following is not very pretty, but it will avoid the costly
802 # isinstance check for the common types
803 if type(obj) in [
804 bool,
805 int,
806 float,
807 np.int32,
808 np.int64,
809 np.float32,
810 np.float64,
811 np.ndarray,
812 np.bool_,
813 ] or isinstance(obj, (numbers.Number, np.number, np.ndarray)):
814 return DIMENSIONLESS
815 try:
816 return Quantity(obj).dim
817 except TypeError:
818 raise TypeError(
819 f"Object of type {type(obj)} does not have dimensions"
820 ) from None
821
822
823 def is_dimensionless(obj):
824 """
825 Test if a value is dimensionless or not.
826
827 Parameters
828 ----------
829 obj : `object`
830 The object to check.
831
832 Returns
833 -------
834 dimensionless : `bool`
835 ``True`` if `obj` is dimensionless.
836 """
837 return get_dimensions(obj) is DIMENSIONLESS
838
839
840 def have_same_dimensions(obj1, obj2):
841 """Test if two values have the same dimensions.
842
843 Parameters
844 ----------
845 obj1, obj2 : {`Quantity`, array-like, number}
846 The values of which to compare the dimensions.
847
848 Returns
849 -------
850 same : `bool`
851 ``True`` if `obj1` and `obj2` have the same dimensions.
852 """
853
854 if not unit_checking:
855 return True # ignore units when unit checking is disabled
856
857 # If dimensions are consistently created using get_or_create_dimensions,
858 # the fast "is" comparison should always return the correct result.
859 # To be safe, we also do an equals comparison in case it fails. This
860 # should only add a small amount of unnecessary computation for cases in
861 # which this function returns False which very likely leads to a
862 # DimensionMismatchError anyway.
863 dim1 = get_dimensions(obj1)
864 dim2 = get_dimensions(obj2)
865 return (dim1 is dim2) or (dim1 == dim2) or dim1 is None or dim2 is None
866
867
868 def in_unit(x, u, precision=None):
869 """
870 Display a value in a certain unit with a given precision.
871
872 Parameters
873 ----------
874 x : {`Quantity`, array-like, number}
875 The value to display
876 u : {`Quantity`, `Unit`}
877 The unit to display the value `x` in.
878 precision : `int`, optional
879 The number of digits of precision (in the given unit, see Examples).
880 If no value is given, numpy's `get_printoptions` value is used.
881
882 Returns
883 -------
884 s : `str`
885 A string representation of `x` in units of `u`.
886
887 Examples
888 --------
889 >>> from brian2 import *
890 >>> in_unit(3 * volt, mvolt)
891 '3000. mV'
892 >>> in_unit(123123 * msecond, second, 2)
893 '123.12 s'
894 >>> in_unit(10 * uA/cm**2, nA/um**2)
895 '1.00000000e-04 nA/(um^2)'
896 >>> in_unit(10 * mV, ohm * amp)
897 '0.01 ohm A'
898 >>> in_unit(10 * nS, ohm) # doctest: +NORMALIZE_WHITESPACE
899 ... # doctest: +IGNORE_EXCEPTION_DETAIL
900 Traceback (most recent call last):
901 ...
902 DimensionMismatchError: Non-matching unit for method "in_unit",
903 dimensions were (m^-2 kg^-1 s^3 A^2) (m^2 kg s^-3 A^-2)
904
905 See Also
906 --------
907 Quantity.in_unit
908 """
909 if is_dimensionless(x):
910 fail_for_dimension_mismatch(x, u, 'Non-matching unit for function "in_unit"')
911 return str(np.asarray(x / u))
912 else:
913 return x.in_unit(u, precision=precision)
914
915
916 def in_best_unit(x, precision=None):
917 """
918 Represent the value in the "best" unit.
919
920 Parameters
921 ----------
922 x : {`Quantity`, array-like, number}
923 The value to display
924 precision : `int`, optional
925 The number of digits of precision (in the best unit, see Examples).
926 If no value is given, numpy's `get_printoptions` value is used.
927
928 Returns
929 -------
930 representation : `str`
931 A string representation of this `Quantity`.
932
933 Examples
934 --------
935 >>> from brian2.units import *
936 >>> in_best_unit(0.00123456 * volt)
937 '1.23456 mV'
938 >>> in_best_unit(0.00123456 * volt, 2)
939 '1.23 mV'
940 >>> in_best_unit(0.123456)
941 '0.123456'
942 >>> in_best_unit(0.123456, 2)
943 '0.12'
944
945 See Also
946 --------
947 Quantity.in_best_unit
948 """
949 if is_dimensionless(x):
950 if precision is None:
951 precision = np.get_printoptions()["precision"]
952 return str(np.round(x, precision))
953
954 u = x.get_best_unit()
955 return x.in_unit(u, precision=precision)
956
957
958 def quantity_with_dimensions(floatval, dims):
959 """
960 Create a new `Quantity` with the given dimensions. Calls
961 `get_or_create_dimensions` with the dimension tuple of the `dims`
962 argument to make sure that unpickling (which calls this function) does not
963 accidentally create new Dimension objects which should instead refer to
964 existing ones.
965
966 Parameters
967 ----------
968 floatval : `float`
969 The floating point value of the quantity.
970 dims : `Dimension`
971 The physical dimensions of the quantity.
972
973 Returns
974 -------
975 q : `Quantity`
976 A quantity with the given dimensions.
977
978 Examples
979 --------
980 >>> from brian2 import *
981 >>> quantity_with_dimensions(0.001, volt.dim)
982 1. * mvolt
983
984 See Also
985 --------
986 get_or_create_dimensions
987 """
988 return Quantity(floatval, get_or_create_dimension(dims._dims))
989
990
991 class Quantity(np.ndarray):
992 """
993 A number with an associated physical dimension. In most cases, it is not
994 necessary to create a Quantity object by hand, instead use multiplication
995 and division of numbers with the constant unit names ``second``,
996 ``kilogram``, etc.
997
998 Notes
999 -----
1000 The `Quantity` class defines arithmetic operations which check for
1001 consistency of dimensions and raise the DimensionMismatchError exception
1002 if they are inconsistent. It also defines default and other representations
1003 for a number for printing purposes.
1004
1005 See the documentation on the Unit class for more details
1006 about the available unit names like mvolt, etc.
1007
1008 *Casting rules*
1009
1010 The rules that define the casting operations for
1011 Quantity object are:
1012
1013 1. Quantity op Quantity = Quantity
1014 Performs dimension checking if appropriate
1015 2. (Scalar or Array) op Quantity = Quantity
1016 Assumes that the scalar or array is dimensionless
1017
1018 There is one exception to the above rule, the number ``0`` is interpreted
1019 as having "any dimension".
1020
1021 Examples
1022 --------
1023 >>> from brian2 import *
1024 >>> I = 3 * amp # I is a Quantity object
1025 >>> R = 2 * ohm # same for R
1026 >>> I * R
1027 6. * volt
1028 >>> (I * R).in_unit(mvolt)
1029 '6000. mV'
1030 >>> (I * R) / mvolt
1031 6000.0
1032 >>> X = I + R # doctest: +IGNORE_EXCEPTION_DETAIL
1033 Traceback (most recent call last):
1034 ...
1035 DimensionMismatchError: Addition, dimensions were (A) (m^2 kg s^-3 A^-2)
1036 >>> Is = np.array([1, 2, 3]) * amp
1037 >>> Is * R
1038 array([ 2., 4., 6.]) * volt
1039 >>> np.asarray(Is * R) # gets rid of units
1040 array([ 2., 4., 6.])
1041
1042 See also
1043 --------
1044 Unit
1045
1046 Attributes
1047 ----------
1048 dimensions
1049 is_dimensionless
1050 dim : Dimensions
1051 The physical dimensions of this quantity.
1052
1053 Methods
1054 -------
1055 with_dimensions
1056 has_same_dimensions
1057 in_unit
1058 in_best_unit
1059 """
1060
1061 __slots__ = ["dim"]
1062
1063 __array_priority__ = 1000
1064
1065 # ==========================================================================
1066 # Construction and handling of numpy ufuncs
1067 # ==========================================================================
1068 def __new__(cls, arr, dim=None, dtype=None, copy=False, force_quantity=False):
1069 # Do not create dimensionless quantities, use pure numpy arrays instead
1070 if dim is DIMENSIONLESS and not force_quantity:
1071 if copy:
1072 arr = np.array(arr, dtype=dtype)
1073 else:
1074 arr = np.asarray(arr, dtype=dtype)
1075 if arr.shape == ():
1076 # For scalar values, return a simple Python object instead of
1077 # a numpy scalar
1078 return arr.item()
1079 return arr
1080
1081 # All np.ndarray subclasses need something like this, see
1082 # http://www.scipy.org/Subclasses
1083 if copy:
1084 subarr = np.array(arr, dtype=dtype).view(cls)
1085 else:
1086 subarr = np.asarray(arr, dtype=dtype).view(cls)
1087 # We only want numerical datatypes
1088 if not issubclass(np.dtype(subarr.dtype).type, (np.number, np.bool_)):
1089 raise TypeError("Quantities can only be created from numerical data.")
1090
1091 # If a dimension is given, force this dimension
1092 if dim is not None:
1093 subarr.dim = dim
1094 return subarr
1095
1096 # Use the given dimension or the dimension of the given array (if any)
1097 try:
1098 subarr.dim = arr.dim
1099 except AttributeError:
1100 if not isinstance(arr, (np.ndarray, np.number, numbers.Number)):
1101 # check whether it is an iterable containing Quantity objects
1102 try:
1103 is_quantity = [isinstance(x, Quantity) for x in _flatten(arr)]
1104 except TypeError:
1105 # Not iterable
1106 is_quantity = [False]
1107 if len(is_quantity) == 0:
1108 # Empty list
1109 subarr.dim = DIMENSIONLESS
1110 elif all(is_quantity):
1111 dims = [x.dim for x in _flatten(arr)]
1112 one_dim = dims[0]
1113 for d in dims:
1114 if d != one_dim:
1115 raise DimensionMismatchError(
1116 "Mixing quantities "
1117 "with different "
1118 "dimensions is not "
1119 "allowed",
1120 d,
1121 one_dim,
1122 ) from None
1123 subarr.dim = dims[0]
1124 elif any(is_quantity):
1125 raise TypeError(
1126 "Mixing quantities and non-quantities is not allowed."
1127 ) from None
1128
1129 return subarr
1130
1131 def __array_finalize__(self, orig):
1132 self.dim = getattr(orig, "dim", DIMENSIONLESS)
1133
1134 def __array_ufunc__(self, uf, method, *inputs, **kwargs):
1135 if method not in ("__call__", "reduce"):
1136 return NotImplemented
1137 uf_method = getattr(uf, method)
1138 if "out" in kwargs:
1139 # In contrast to numpy, we will not change a scalar value in-place,
1140 # i.e. a scalar Quantity will act like a Python float and not like
1141 # a numpy scalar in that regard.
1142 if self.ndim == 0:
1143 del kwargs["out"]
1144 else:
1145 # The output needs to be an array to avoid infinite recursion
1146 # Note that it is also part of the input arguments, so we don't
1147 # need to check its dimensions
1148 assert len(kwargs["out"]) == 1
1149 kwargs["out"] = (np.asarray(kwargs["out"][0]),)
1150 if uf.__name__ in (UFUNCS_LOGICAL + ["sign", "ones_like"]):
1151 # do not touch return value
1152 return uf_method(*[np.asarray(a) for a in inputs], **kwargs)
1153 elif uf.__name__ in UFUNCS_PRESERVE_DIMENSIONS:
1154 return Quantity(
1155 uf_method(*[np.asarray(a) for a in inputs], **kwargs),
1156 dim=self.dim,
1157 )
1158 elif uf.__name__ in UFUNCS_CHANGE_DIMENSIONS + ["power"]:
1159 if uf.__name__ == "sqrt":
1160 dim = self.dim**0.5
1161 elif uf.__name__ == "power":
1162 fail_for_dimension_mismatch(
1163 inputs[1],
1164 error_message=(
1165 "The exponent for a "
1166 "power operation has to "
1167 "be dimensionless but "
1168 "was {value}"
1169 ),
1170 value=inputs[1],
1171 )
1172 if np.asarray(inputs[1]).size != 1:
1173 raise TypeError(
1174 "Only length-1 arrays can be used as an exponent for"
1175 " quantities."
1176 )
1177 dim = get_dimensions(inputs[0]) ** np.asarray(inputs[1])
1178 elif uf.__name__ == "square":
1179 dim = self.dim**2
1180 elif uf.__name__ in ("divide", "true_divide", "floor_divide"):
1181 dim = get_dimensions(inputs[0]) / get_dimensions(inputs[1])
1182 elif uf.__name__ == "reciprocal":
1183 dim = get_dimensions(inputs[0]) ** -1
1184 elif uf.__name__ in ("multiply", "dot", "matmul"):
1185 if method == "__call__":
1186 dim = get_dimensions(inputs[0]) * get_dimensions(inputs[1])
1187 else:
1188 dim = get_dimensions(inputs[0])
1189 else:
1190 return NotImplemented
1191 return Quantity(
1192 uf_method(*[np.asarray(a) for a in inputs], **kwargs), dim=dim
1193 )
1194 elif uf.__name__ in UFUNCS_INTEGERS:
1195 # Numpy should already raise a TypeError by itself
1196 raise TypeError(f"{uf.__name__} cannot be used on quantities.")
1197 elif uf.__name__ in UFUNCS_MATCHING_DIMENSIONS + UFUNCS_COMPARISONS:
1198 # Ok if dimension of arguments match (for reductions, they always do)
1199 if method == "__call__":
1200 fail_for_dimension_mismatch(
1201 inputs[0],
1202 inputs[1],
1203 error_message=(
1204 "Cannot calculate {val1} %s {val2}, the units do not match"
1205 )
1206 % uf.__name__,
1207 val1=inputs[0],
1208 val2=inputs[1],
1209 )
1210 if uf.__name__ in UFUNCS_COMPARISONS:
1211 return uf_method(*[np.asarray(i) for i in inputs], **kwargs)
1212 else:
1213 return Quantity(
1214 uf_method(*[np.asarray(i) for i in inputs], **kwargs),
1215 dim=self.dim,
1216 )
1217 elif uf.__name__ in UFUNCS_DIMENSIONLESS:
1218 # Ok if argument is dimensionless
1219 fail_for_dimension_mismatch(
1220 inputs[0],
1221 error_message="%s expects a dimensionless argument but got {value}"
1222 % uf.__name__,
1223 value=inputs[0],
1224 )
1225 return uf_method(np.asarray(inputs[0]), *inputs[1:], **kwargs)
1226 elif uf.__name__ in UFUNCS_DIMENSIONLESS_TWOARGS:
1227 # Ok if both arguments are dimensionless
1228 fail_for_dimension_mismatch(
1229 inputs[0],
1230 error_message=(
1231 "Both arguments for "
1232 '"%s" should be '
1233 "dimensionless but "
1234 "first argument was "
1235 "{value}"
1236 )
1237 % uf.__name__,
1238 value=inputs[0],
1239 )
1240 fail_for_dimension_mismatch(
1241 inputs[1],
1242 error_message=(
1243 "Both arguments for "
1244 '"%s" should be '
1245 "dimensionless but "
1246 "second argument was "
1247 "{value}"
1248 )
1249 % uf.__name__,
1250 value=inputs[1],
1251 )
1252 return uf_method(
1253 np.asarray(inputs[0]),
1254 np.asarray(inputs[1]),
1255 *inputs[2:],
1256 **kwargs,
1257 )
1258 else:
1259 return NotImplemented
1260
1261 def __deepcopy__(self, memo):
1262 return Quantity(self, copy=True)
1263
1264 # ==============================================================================
1265 # Quantity-specific functions (not existing in ndarray)
1266 # ==============================================================================
1267 @staticmethod
1268 def with_dimensions(value, *args, **keywords):
1269 """
1270 Create a `Quantity` object with dim.
1271
1272 Parameters
1273 ----------
1274 value : {array_like, number}
1275 The value of the dimension
1276 args : {`Dimension`, sequence of float}
1277 Either a single argument (a `Dimension`) or a sequence of 7 values.
1278 kwds
1279 Keywords defining the dim, see `Dimension` for details.
1280
1281 Returns
1282 -------
1283 q : `Quantity`
1284 A `Quantity` object with the given dim
1285
1286 Examples
1287 --------
1288 All of these define an equivalent `Quantity` object:
1289
1290 >>> from brian2 import *
1291 >>> Quantity.with_dimensions(2, get_or_create_dimension(length=1))
1292 2. * metre
1293 >>> Quantity.with_dimensions(2, length=1)
1294 2. * metre
1295 >>> 2 * metre
1296 2. * metre
1297 """
1298 if len(args) and isinstance(args[0], Dimension):
1299 dimensions = args[0]
1300 else:
1301 dimensions = get_or_create_dimension(*args, **keywords)
1302 return Quantity(value, dim=dimensions)
1303
1304 ### ATTRIBUTES ###
1305 is_dimensionless = property(
1306 lambda self: self.dim.is_dimensionless,
1307 doc="Whether this is a dimensionless quantity.",
1308 )
1309
1310 @property
1311 def dimensions(self):
1312 """
1313 The physical dimensions of this quantity.
1314 """
1315 return self.dim
1316
1317 @dimensions.setter
1318 def dimensions(self, dim):
1319 self.dim = dim
1320
1321 #### METHODS ####
1322
1323 def has_same_dimensions(self, other):
1324 """
1325 Return whether this object has the same dimensions as another.
1326
1327 Parameters
1328 ----------
1329 other : {`Quantity`, array-like, number}
1330 The object to compare the dimensions against.
1331
1332 Returns
1333 -------
1334 same : `bool`
1335 ``True`` if `other` has the same dimensions.
1336 """
1337 if not unit_checking:
1338 return True # ignore units if unit checking is disabled
1339
1340 other_dim = get_dimensions(other)
1341 return (self.dim is other_dim) or (self.dim == other_dim)
1342
1343 def in_unit(self, u, precision=None, python_code=False):
1344 """
1345 Represent the quantity in a given unit. If `python_code` is ``True``,
1346 this will return valid python code, i.e. a string like ``5.0 * um ** 2``
1347 instead of ``5.0 um^2``
1348
1349 Parameters
1350 ----------
1351 u : {`Quantity`, `Unit`}
1352 The unit in which to show the quantity.
1353 precision : `int`, optional
1354 The number of digits of precision (in the given unit, see Examples).
1355 If no value is given, numpy's `get_printoptions` value is used.
1356 python_code : `bool`, optional
1357 Whether to return valid python code (``True``) or a human readable
1358 string (``False``, the default).
1359
1360 Returns
1361 -------
1362 s : `str`
1363 String representation of the object in unit `u`.
1364
1365 Examples
1366 --------
1367 >>> from brian2.units import *
1368 >>> from brian2.units.stdunits import *
1369 >>> x = 25.123456 * mV
1370 >>> x.in_unit(volt)
1371 '0.02512346 V'
1372 >>> x.in_unit(volt, 3)
1373 '0.025 V'
1374 >>> x.in_unit(mV, 3)
1375 '25.123 mV'
1376
1377 See Also
1378 --------
1379 in_unit
1380 """
1381
1382 fail_for_dimension_mismatch(self, u, 'Non-matching unit for method "in_unit"')
1383
1384 value = np.asarray(self / u)
1385 # numpy uses the printoptions setting only in arrays, not in array
1386 # scalars, so we use this hackish way of turning the scalar first into
1387 # an array, then removing the square brackets from the output
1388 if value.shape == ():
1389 s = np.array_str(np.array([value]), precision=precision)
1390 s = s.replace("[", "").replace("]", "").strip()
1391 else:
1392 if python_code:
1393 s = np.array_repr(value, precision=precision)
1394 else:
1395 s = np.array_str(value, precision=precision)
1396
1397 if not u.is_dimensionless:
1398 if isinstance(u, Unit):
1399 if python_code:
1400 s += f" * {repr(u)}"
1401 else:
1402 s += f" {str(u)}"
1403 else:
1404 if python_code:
1405 s += f" * {repr(u.dim)}"
1406 else:
1407 s += f" {str(u.dim)}"
1408 elif python_code: # Make a quantity without unit recognisable
1409 return f"{self.__class__.__name__}({s.strip()})"
1410 return s.strip()
1411
1412 def get_best_unit(self, *regs):
1413 """
1414 Return the best unit for this `Quantity`.
1415
1416 Parameters
1417 ----------
1418 regs : any number of `UnitRegistry` objects
1419 The registries that are searched for units. If none are provided, it
1420 will check the standard, user and additional unit registers in turn.
1421
1422 Returns
1423 -------
1424 u : `Quantity` or `Unit`
1425 The best-fitting unit for the quantity `x`.
1426 """
1427 if self.is_dimensionless:
1428 return Unit(1)
1429 if len(regs):
1430 for r in regs:
1431 try:
1432 return r[self]
1433 except KeyError:
1434 pass
1435 return Quantity(1, self.dim)
1436 else:
1437 return self.get_best_unit(
1438 standard_unit_register, user_unit_register, additional_unit_register
1439 )
1440
1441 def _get_best_unit(self, *regs):
1442 warn(
1443 "Quantity._get_best_unit has been renamed to Quantity.get_best_unit.",
1444 VisibleDeprecationWarning,
1445 )
1446 return self.get_best_unit(*regs)
1447
1448 def in_best_unit(self, precision=None, python_code=False, *regs):
1449 """
1450 Represent the quantity in the "best" unit.
1451
1452 Parameters
1453 ----------
1454 python_code : `bool`, optional
1455 If set to ``False`` (the default), will return a string like
1456 ``5.0 um^2`` which is not a valid Python expression. If set to
1457 ``True``, it will return ``5.0 * um ** 2`` instead.
1458 precision : `int`, optional
1459 The number of digits of precision (in the best unit, see
1460 Examples). If no value is given, numpy's
1461 `get_printoptions` value is used.
1462 regs : `UnitRegistry` objects
1463 The registries where to search for units. If none are given, the
1464 standard, user-defined and additional registries are searched in
1465 that order.
1466
1467 Returns
1468 -------
1469 representation : `str`
1470 A string representation of this `Quantity`.
1471
1472 Examples
1473 --------
1474 >>> from brian2.units import *
1475
1476 >>> x = 0.00123456 * volt
1477
1478 >>> x.in_best_unit()
1479 '1.23456 mV'
1480
1481 >>> x.in_best_unit(3)
1482 '1.235 mV'
1483
1484 See Also
1485 --------
1486 in_best_unit
1487 """
1488 u = self.get_best_unit(*regs)
1489 return self.in_unit(u, precision=precision, python_code=python_code)
1490
1491 # ==============================================================================
1492 # Overwritten ndarray methods
1493 # ==============================================================================
1494
1495 #### Setting/getting items ####
1496 def __getitem__(self, key):
1497 """Overwritten to assure that single elements (i.e., indexed with a
1498 single integer or a tuple of integers) retain their unit.
1499 """
1500 return Quantity(np.ndarray.__getitem__(self, key), self.dim)
1501
1502 def item(self, *args):
1503 """Overwritten to assure that the returned element retains its unit."""
1504 return Quantity(np.ndarray.item(self, *args), self.dim)
1505
1506 def __setitem__(self, key, value):
1507 fail_for_dimension_mismatch(self, value, "Inconsistent units in assignment")
1508 return super().__setitem__(key, value)
1509
1510 def tolist(self):
1511 """
1512 Convert the array into a list.
1513
1514 Returns
1515 -------
1516 l : list of `Quantity`
1517 A (possibly nested) list equivalent to the original array.
1518 """
1519
1520 def replace_with_quantity(seq, dim):
1521 """
1522 Replace all the elements in the list with an equivalent `Quantity`
1523 with the given `dim`.
1524 """
1525 # No recursion needed for single values
1526 if not isinstance(seq, list):
1527 return Quantity(seq, dim)
1528
1529 def top_replace(s):
1530 """
1531 Recursivley descend into the list.
1532 """
1533 for i in s:
1534 if not isinstance(i, list):
1535 yield Quantity(i, dim)
1536 else:
1537 yield type(i)(top_replace(i))
1538
1539 return type(seq)(top_replace(seq))
1540
1541 return replace_with_quantity(np.asarray(self).tolist(), self.dim)
1542
1543 #### COMPARISONS ####
1544 def _comparison(self, other, operator_str, operation):
1545 is_scalar = is_scalar_type(other)
1546 if not is_scalar and not isinstance(other, np.ndarray):
1547 return NotImplemented
1548 if not is_scalar or not np.isinf(other):
1549 message = (
1550 "Cannot perform comparison {value1} %s {value2}, units do not match"
1551 % operator_str
1552 )
1553 fail_for_dimension_mismatch(self, other, message, value1=self, value2=other)
1554 return operation(np.asarray(self), np.asarray(other))
1555
1556 def __lt__(self, other):
1557 return self._comparison(other, "<", operator.lt)
1558
1559 def __le__(self, other):
1560 return self._comparison(other, "<=", operator.le)
1561
1562 def __gt__(self, other):
1563 return self._comparison(other, ">", operator.gt)
1564
1565 def __ge__(self, other):
1566 return self._comparison(other, ">=", operator.ge)
1567
1568 def __eq__(self, other):
1569 return self._comparison(other, "==", operator.eq)
1570
1571 def __ne__(self, other):
1572 return self._comparison(other, "!=", operator.ne)
1573
1574 #### MAKE QUANTITY PICKABLE ####
1575 def __reduce__(self):
1576 return quantity_with_dimensions, (np.asarray(self), self.dim)
1577
1578 #### REPRESENTATION ####
1579 def __repr__(self):
1580 return self.in_best_unit(python_code=True)
1581
1582 def _latex(self, expr):
1583 """
1584 Translates a scalar, 1-d or 2-d array into a LaTeX representation. Will be called
1585 by ``sympy``'s `~sympy.latex` function and used as a "rich representation" in e.g.
1586 jupyter notebooks.
1587 The values in the array will be formatted with `numpy.array2string` and will
1588 therefore observe ``numpy``'s "print options" such as ``precision``. Including
1589 all numbers in the LaTeX output will rarely be useful for large arrays; this
1590 function will therefore apply a ``threshold`` value divided by 100 (the default
1591 ``threshold`` value is 1000, this function hence applies 10). Note that the
1592 ``max_line_width`` print option is ignored.
1593 """
1594 best_unit = self.get_best_unit()
1595 if isinstance(best_unit, Unit):
1596 best_unit_latex = latex(best_unit)
1597 else: # A quantity
1598 best_unit_latex = latex(best_unit.dimensions)
1599 unitless = np.asarray(self / best_unit)
1600 threshold = np.get_printoptions()["threshold"] // 100
1601 if unitless.ndim == 0:
1602 sympy_quantity = float(unitless)
1603 elif unitless.ndim == 1:
1604 array_str = np.array2string(
1605 unitless,
1606 separator=" & ",
1607 threshold=threshold,
1608 max_line_width=sys.maxsize,
1609 )
1610 # Replace [ and ]
1611 sympy_quantity = (
1612 r"\left[\begin{matrix}"
1613 + array_str[1:-1].replace("...", r"\dots")
1614 + r"\end{matrix}\right]"
1615 )
1616 elif unitless.ndim == 2:
1617 array_str = np.array2string(
1618 unitless,
1619 separator=" & ",
1620 threshold=threshold,
1621 max_line_width=sys.maxsize,
1622 )
1623 array_str = array_str[1:-1].replace("...", r"\dots")
1624 array_str = (
1625 array_str.replace("[", "").replace("] &", r"\\").replace("]", "\n")
1626 )
1627 lines = array_str.split("\n")
1628 n_cols = lines[0].count("&") + 1
1629 new_lines = []
1630 for line in lines:
1631 if line.strip() == r"\dots &":
1632 new_lines.append(" & ".join([r"\vdots"] * n_cols) + r"\\")
1633 else:
1634 new_lines.append(line)
1635 sympy_quantity = (
1636 r"\left[\begin{matrix}"
1637 + "\n"
1638 + "\n".join(new_lines)
1639 + r"\end{matrix}\right]"
1640 )
1641 else:
1642 raise NotImplementedError(
1643 f"Cannot create a LaTeX representation for a {unitless.ndim}-d matrix."
1644 )
1645 return f"{sympy_quantity}\\,{best_unit_latex}"
1646
1647 def _repr_latex_(self):
1648 return f"${latex(self)}$"
1649
1650 def __str__(self):
1651 return self.in_best_unit()
1652
1653 def __format__(self, format_spec):
1654 # Avoid that formatted strings like f"{q}" use floating point formatting for the
1655 # quantity, i.e. discard the unit
1656 if format_spec == "":
1657 return str(self)
1658 else:
1659 return super().__format__(format_spec)
1660
1661 #### Mathematic methods ####
1662
1663 cumsum = wrap_function_keep_dimensions(np.ndarray.cumsum)
1664 diagonal = wrap_function_keep_dimensions(np.ndarray.diagonal)
1665 max = wrap_function_keep_dimensions(np.ndarray.max)
1666 mean = wrap_function_keep_dimensions(np.ndarray.mean)
1667 min = wrap_function_keep_dimensions(np.ndarray.min)
1668 if hasattr(np.ndarray, "ptp"):
1669 ptp = wrap_function_keep_dimensions(np.ndarray.ptp)
1670
1671 # To work around an issue in matplotlib 1.3.1 (see
1672 # https://github.com/matplotlib/matplotlib/pull/2591), we make `ravel`
1673 # return a unitless array and emit a warning explaining the issue.
1674 use_matplotlib_units_fix = False
1675 try:
1676 import matplotlib
1677
1678 if matplotlib.__version__ == "1.3.1":
1679 use_matplotlib_units_fix = True
1680 except ImportError:
1681 pass
1682
1683 if use_matplotlib_units_fix:
1684
1685 def ravel(self, *args, **kwds):
1686 # Note that we don't use Brian's logging system here as we don't want
1687 # the unit system to depend on other parts of Brian
1688 warn(
1689 "As a workaround for a bug in matplotlib 1.3.1, calling "
1690 '"ravel()" on a quantity will return unit-less values. If you '
1691 "get this warning during plotting, consider removing the units "
1692 "before plotting, e.g. by dividing by the unit. If you are "
1693 'explicitly calling "ravel()", consider using "flatten()" '
1694 "instead."
1695 )
1696 return np.asarray(self).ravel(*args, **kwds)
1697
1698 ravel._arg_units = [None]
1699 ravel._return_unit = 1
1700 ravel.__name__ = np.ndarray.ravel.__name__
1701 ravel.__doc__ = np.ndarray.ravel.__doc__
1702 else:
1703 ravel = wrap_function_keep_dimensions(np.ndarray.ravel)
1704
1705 round = wrap_function_keep_dimensions(np.ndarray.round)
1706 std = wrap_function_keep_dimensions(np.ndarray.std)
1707 sum = wrap_function_keep_dimensions(np.ndarray.sum)
1708 trace = wrap_function_keep_dimensions(np.ndarray.trace)
1709 var = wrap_function_change_dimensions(np.ndarray.var, lambda ar, d: d**2)
1710 all = wrap_function_remove_dimensions(np.ndarray.all)
1711 any = wrap_function_remove_dimensions(np.ndarray.any)
1712 nonzero = wrap_function_remove_dimensions(np.ndarray.nonzero)
1713 argmax = wrap_function_remove_dimensions(np.ndarray.argmax)
1714 argmin = wrap_function_remove_dimensions(np.ndarray.argmin)
1715 argsort = wrap_function_remove_dimensions(np.ndarray.argsort)
1716
1717 def fill(self, values): # pylint: disable=C0111
1718 fail_for_dimension_mismatch(self, values, "fill")
1719 super().fill(values)
1720
1721 fill.__doc__ = np.ndarray.fill.__doc__
1722 fill._do_not_run_doctests = True
1723
1724 def put(self, indices, values, *args, **kwds): # pylint: disable=C0111
1725 fail_for_dimension_mismatch(self, values, "fill")
1726 super().put(indices, values, *args, **kwds)
1727
1728 put.__doc__ = np.ndarray.put.__doc__
1729 put._do_not_run_doctests = True
1730
1731 def clip(self, a_min, a_max, *args, **kwds): # pylint: disable=C0111
1732 fail_for_dimension_mismatch(self, a_min, "clip")
1733 fail_for_dimension_mismatch(self, a_max, "clip")
1734 return Quantity(
1735 np.clip(
1736 np.asarray(self),
1737 np.asarray(a_min),
1738 np.asarray(a_max),
1739 *args,
1740 **kwds,
1741 ),
1742 self.dim,
1743 )
1744
1745 clip.__doc__ = np.ndarray.clip.__doc__
1746 clip._do_not_run_doctests = True
1747
1748 def dot(self, other, **kwds): # pylint: disable=C0111
1749 return Quantity(
1750 np.array(self).dot(np.array(other), **kwds),
1751 self.dim * get_dimensions(other),
1752 )
1753
1754 dot.__doc__ = np.ndarray.dot.__doc__
1755 dot._do_not_run_doctests = True
1756
1757 def searchsorted(self, v, **kwds): # pylint: disable=C0111
1758 fail_for_dimension_mismatch(self, v, "searchsorted")
1759 return super().searchsorted(np.asarray(v), **kwds)
1760
1761 searchsorted.__doc__ = np.ndarray.searchsorted.__doc__
1762 searchsorted._do_not_run_doctests = True
1763
1764 def prod(self, *args, **kwds): # pylint: disable=C0111
1765 prod_result = super().prod(*args, **kwds)
1766 # Calculating the correct dimensions is not completly trivial (e.g.
1767 # like doing self.dim**self.size) because prod can be called on
1768 # multidimensional arrays along a certain axis.
1769 # Our solution: Use a "dummy matrix" containing a 1 (without units) at
1770 # each entry and sum it, using the same keyword arguments as provided.
1771 # The result gives the exponent for the dimensions.
1772 # This relies on sum and prod having the same arguments, which is true
1773 # now and probably remains like this in the future
1774 dim_exponent = np.ones_like(self).sum(*args, **kwds)
1775 # The result is possibly multidimensional but all entries should be
1776 # identical
1777 if dim_exponent.size > 1:
1778 dim_exponent = dim_exponent[0]
1779 return Quantity(np.asarray(prod_result), self.dim**dim_exponent)
1780
1781 prod.__doc__ = np.ndarray.prod.__doc__
1782 prod._do_not_run_doctests = True
1783
1784 def cumprod(self, *args, **kwds): # pylint: disable=C0111
1785 if not self.is_dimensionless:
1786 raise TypeError(
1787 "cumprod over array elements on quantities "
1788 "with dimensions is not possible."
1789 )
1790 return Quantity(np.asarray(self).cumprod(*args, **kwds))
1791
1792 cumprod.__doc__ = np.ndarray.cumprod.__doc__
1793 cumprod._do_not_run_doctests = True
1794
1795
1796 class Unit(Quantity):
1797 r"""
1798 A physical unit.
1799
1800 Normally, you do not need to worry about the implementation of
1801 units. They are derived from the `Quantity` object with
1802 some additional information (name and string representation).
1803
1804 Basically, a unit is just a number with given dimensions, e.g.
1805 mvolt = 0.001 with the dimensions of voltage. The units module
1806 defines a large number of standard units, and you can also define
1807 your own (see below).
1808
1809 The unit class also keeps track of various things that were used
1810 to define it so as to generate a nice string representation of it.
1811 See below.
1812
1813 When creating scaled units, you can use the following prefixes:
1814
1815 ====== ====== ==============
1816 Factor Name Prefix
1817 ====== ====== ==============
1818 10^24 yotta Y
1819 10^21 zetta Z
1820 10^18 exa E
1821 10^15 peta P
1822 10^12 tera T
1823 10^9 giga G
1824 10^6 mega M
1825 10^3 kilo k
1826 10^2 hecto h
1827 10^1 deka da
1828 1
1829 10^-1 deci d
1830 10^-2 centi c
1831 10^-3 milli m
1832 10^-6 micro u (\mu in SI)
1833 10^-9 nano n
1834 10^-12 pico p
1835 10^-15 femto f
1836 10^-18 atto a
1837 10^-21 zepto z
1838 10^-24 yocto y
1839 ====== ====== ==============
1840
1841 **Defining your own**
1842
1843 It can be useful to define your own units for printing
1844 purposes. So for example, to define the newton metre, you
1845 write
1846
1847 >>> from brian2 import *
1848 >>> from brian2.units.allunits import newton
1849 >>> Nm = newton * metre
1850
1851 You can then do
1852
1853 >>> (1*Nm).in_unit(Nm)
1854 '1. N m'
1855
1856 New "compound units", i.e. units that are composed of other units will be
1857 automatically registered and from then on used for display. For example,
1858 imagine you define total conductance for a membrane, and the total area of
1859 that membrane:
1860
1861 >>> conductance = 10.*nS
1862 >>> area = 20000*um**2
1863
1864 If you now ask for the conductance density, you will get an "ugly" display
1865 in basic SI dimensions, as Brian does not know of a corresponding unit:
1866
1867 >>> conductance/area
1868 0.5 * metre ** -4 * kilogram ** -1 * second ** 3 * amp ** 2
1869
1870 By using an appropriate unit once, it will be registered and from then on
1871 used for display when appropriate:
1872
1873 >>> usiemens/cm**2
1874 usiemens / (cmetre ** 2)
1875 >>> conductance/area # same as before, but now Brian knows about uS/cm^2
1876 50. * usiemens / (cmetre ** 2)
1877
1878 Note that user-defined units cannot override the standard units (`volt`,
1879 `second`, etc.) that are predefined by Brian. For example, the unit
1880 ``Nm`` has the dimensions "length²·mass/time²", and therefore the same
1881 dimensions as the standard unit `joule`. The latter will be used for display
1882 purposes:
1883
1884 >>> 3*joule
1885 3. * joule
1886 >>> 3*Nm
1887 3. * joule
1888
1889 """
1890
1891 __slots__ = ["dim", "scale", "_dispname", "_name", "_latexname", "iscompound"]
1892
1893 __array_priority__ = 100
1894
1895 automatically_register_units = True
1896
1897 #### CONSTRUCTION ####
1898 def __new__(
1899 cls,
1900 arr,
1901 dim=None,
1902 scale=0,
1903 name=None,
1904 dispname=None,
1905 latexname=None,
1906 iscompound=False,
1907 dtype=None,
1908 copy=False,
1909 ):
1910 if dim is None:
1911 dim = DIMENSIONLESS
1912 obj = super().__new__(
1913 cls, arr, dim=dim, dtype=dtype, copy=copy, force_quantity=True
1914 )
1915 return obj
1916
1917 def __array_finalize__(self, orig):
1918 self.dim = getattr(orig, "dim", DIMENSIONLESS)
1919 self.scale = getattr(orig, "scale", 0)
1920 self._name = getattr(orig, "_name", "")
1921 self._dispname = getattr(orig, "_dispname", "")
1922 self._latexname = getattr(orig, "_latexname", "")
1923 self.iscompound = getattr(orig, "_iscompound", False)
1924 return self
1925
1926 def __init__(
1927 self,
1928 value,
1929 dim=None,
1930 scale=0,
1931 name=None,
1932 dispname=None,
1933 latexname="",
1934 iscompound=False,
1935 ):
1936 if value != 10.0**scale:
1937 raise AssertionError(
1938 f"Unit value has to be 10**scale (scale={scale}, value={value})"
1939 )
1940 if dim is None:
1941 dim = DIMENSIONLESS
1942 self.dim = dim #: The Dimensions of this unit
1943
1944 #: The scale for this unit (as the integer exponent of 10), i.e.
1945 #: a scale of 3 means 10^3, e.g. for a "k" prefix.
1946 self.scale = scale
1947 if name is None:
1948 if dim is DIMENSIONLESS:
1949 name = "Unit(1)"
1950 else:
1951 name = repr(dim)
1952 if dispname is None:
1953 if dim is DIMENSIONLESS:
1954 dispname = "1"
1955 else:
1956 dispname = str(dim)
1957 #: The full name of this unit.
1958 self._name = name
1959 #: The display name of this unit.
1960 self._dispname = dispname
1961 #: A LaTeX expression for the name of this unit.
1962 self._latexname = latexname
1963 #: Whether this unit is a combination of other units.
1964 self.iscompound = iscompound
1965
1966 if Unit.automatically_register_units:
1967 register_new_unit(self)
1968
1969 @staticmethod
1970 def create(dim, name, dispname, latexname=None, scale=0):
1971 """
1972 Create a new named unit.
1973
1974 Parameters
1975 ----------
1976 dim : `Dimension`
1977 The dimensions of the unit.
1978 name : `str`
1979 The full name of the unit, e.g. ``'volt'``
1980 dispname : `str`
1981 The display name, e.g. ``'V'``
1982 latexname : str, optional
1983 The name as a LaTeX expression (math mode is assumed, do not add
1984 $ signs or similar), e.g. ``'\\omega'``. If no `latexname` is
1985 specified, `dispname` will be used.
1986 scale : int, optional
1987 The scale of this unit as an exponent of 10, e.g. -3 for a unit that
1988 is 1/1000 of the base scale. Defaults to 0 (i.e. a base unit).
1989
1990 Returns
1991 -------
1992 u : `Unit`
1993 The new unit.
1994 """
1995 name = str(name)
1996 dispname = str(dispname)
1997 if latexname is None:
1998 latexname = f"\\mathrm{{{dispname}}}"
1999
2000 u = Unit(
2001 10.0**scale,
2002 dim=dim,
2003 scale=scale,
2004 name=name,
2005 dispname=dispname,
2006 latexname=latexname,
2007 )
2008
2009 return u
2010
2011 @staticmethod
2012 def create_scaled_unit(baseunit, scalefactor):
2013 """
2014 Create a scaled unit from a base unit.
2015
2016 Parameters
2017 ----------
2018 baseunit : `Unit`
2019 The unit of which to create a scaled version, e.g. ``volt``,
2020 ``amp``.
2021 scalefactor : `str`
2022 The scaling factor, e.g. ``"m"`` for mvolt, mamp
2023
2024 Returns
2025 -------
2026 u : `Unit`
2027 The new unit.
2028 """
2029 name = scalefactor + baseunit.name
2030 dispname = scalefactor + baseunit.dispname
2031 scale = _siprefixes[scalefactor] + baseunit.scale
2032 if scalefactor == "u":
2033 scalefactor = r"\mu"
2034 latexname = f"\\mathrm{{{scalefactor}}}{baseunit.latexname}"
2035
2036 u = Unit(
2037 10.0**scale,
2038 dim=baseunit.dim,
2039 name=name,
2040 dispname=dispname,
2041 latexname=latexname,
2042 scale=scale,
2043 )
2044
2045 return u
2046
2047 #### METHODS ####
2048 def set_name(self, name):
2049 """Sets the name for the unit.
2050
2051 .. deprecated:: 2.1
2052 Create a new unit with `Unit.create` instead.
2053 """
2054 raise NotImplementedError(
2055 "Setting the name for a unit after"
2056 "its creation is no longer supported, use"
2057 "'Unit.create' to create a new unit."
2058 )
2059
2060 def set_display_name(self, name):
2061 """Sets the display name for the unit.
2062
2063 .. deprecated:: 2.1
2064 Create a new unit with `Unit.create` instead.
2065 """
2066 raise NotImplementedError(
2067 "Setting the display name for a unit after"
2068 "its creation is no longer supported, use"
2069 "'Unit.create' to create a new unit."
2070 )
2071
2072 def set_latex_name(self, name):
2073 """Sets the LaTeX name for the unit.
2074
2075 .. deprecated:: 2.1
2076 Create a new unit with `Unit.create` instead.
2077 """
2078 raise NotImplementedError(
2079 "Setting the LaTeX name for a unit after"
2080 "its creation is no longer supported, use"
2081 "'Unit.create' to create a new unit."
2082 )
2083
2084 name = property(
2085 fget=lambda self: self._name, fset=set_name, doc="The name of the unit"
2086 )
2087
2088 dispname = property(
2089 fget=lambda self: self._dispname,
2090 fset=set_display_name,
2091 doc="The display name of the unit",
2092 )
2093
2094 latexname = property(
2095 fget=lambda self: self._latexname,
2096 fset=set_latex_name,
2097 doc="The LaTeX name of the unit",
2098 )
2099
2100 #### REPRESENTATION ####
2101 def __repr__(self):
2102 return self.name
2103
2104 def __str__(self):
2105 return self.dispname
2106
2107 def _latex(self, *args):
2108 return self.latexname
2109
2110 def _repr_latex_(self):
2111 return f"${latex(self)}$"
2112
2113 def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
2114 if method != "__call__":
2115 return NotImplemented
2116
2117 if ufunc.__name__ == "multiply":
2118 first, second = inputs
2119 if isinstance(first, Unit) and isinstance(second, Unit):
2120 name = f"{first.name} * {second.name}"
2121 dispname = f"{self.dispname} {second.dispname}"
2122 latexname = f"{first.latexname}\\,{second.latexname}"
2123 scale = first.scale + second.scale
2124 u = Unit(
2125 10.0**scale,
2126 dim=first.dim * second.dim,
2127 name=name,
2128 dispname=dispname,
2129 latexname=latexname,
2130 iscompound=True,
2131 scale=scale,
2132 )
2133 return u
2134 else:
2135 return ufunc(
2136 *[
2137 Quantity(i, dim=getattr(i, "dim", DIMENSIONLESS))
2138 for i in inputs
2139 ],
2140 **kwargs,
2141 )
2142 elif ufunc.__name__ == "divide":
2143 first, second = inputs
2144 if isinstance(first, Unit) and isinstance(second, Unit):
2145 if first.iscompound:
2146 dispname = f"({self.dispname})"
2147 name = f"({self.name})"
2148 else:
2149 dispname = self.dispname
2150 name = self.name
2151 dispname += "/"
2152 name += " / "
2153 if second.iscompound:
2154 dispname += f"({second.dispname})"
2155 name += f"({second.name})"
2156 else:
2157 dispname += second.dispname
2158 name += second.name
2159
2160 latexname = rf"\frac{{{first.latexname}}}{{{second.latexname}}}"
2161 scale = first.scale - second.scale
2162 u = Unit(
2163 10.0**scale,
2164 dim=first.dim / second.dim,
2165 name=name,
2166 dispname=dispname,
2167 latexname=latexname,
2168 scale=scale,
2169 iscompound=True,
2170 )
2171 return u
2172 elif is_dimensionless(first) and np.array(first).shape == () and first == 1:
2173 return np.reciprocal(second)
2174 else:
2175 return ufunc(
2176 *[
2177 Quantity(i, dim=getattr(i, "dim", DIMENSIONLESS))
2178 for i in inputs
2179 ],
2180 **kwargs,
2181 )
2182 elif ufunc.__name__ == "power":
2183 first, second = inputs
2184 if is_scalar_type(second):
2185 if first.iscompound:
2186 dispname = f"({first.dispname})"
2187 name = f"({first.name})"
2188 latexname = r"\left(%s\right)" % first.latexname
2189 else:
2190 dispname = first.dispname
2191 name = first.name
2192 latexname = first.latexname
2193 dispname += f"^{str(second)}"
2194 name += f" ** {repr(second)}"
2195 latexname += "^{%s}" % latex(second)
2196 scale = first.scale * second
2197 u = Unit(
2198 10.0**scale,
2199 dim=first.dim**second,
2200 name=name,
2201 dispname=dispname,
2202 latexname=latexname,
2203 scale=scale,
2204 iscompound=True,
2205 ) # To avoid issues with units like (second ** -1) ** -1
2206 return u
2207 else:
2208 return super().__pow__(second)
2209 elif ufunc.__name__ == "square":
2210 if self.iscompound:
2211 dispname = f"({self.dispname})"
2212 name = f"({self.name})"
2213 latexname = r"\left(%s\right)" % self.latexname
2214 else:
2215 dispname = self.dispname
2216 name = self.name
2217 latexname = self.latexname
2218 dispname += "^2"
2219 name += " ** 2"
2220 latexname += "^2"
2221 scale = self.scale * 2
2222 u = Unit(
2223 10.0**scale,
2224 dim=self.dim**2,
2225 name=name,
2226 dispname=dispname,
2227 latexname=latexname,
2228 scale=scale,
2229 iscompound=True,
2230 )
2231 return u
2232 elif ufunc.__name__ == "sqrt":
2233 if self.iscompound:
2234 dispname = f"({self.dispname})"
2235 name = f"({self.name})"
2236 latexname = r"\left(%s\right)" % self.latexname
2237 else:
2238 dispname = self.dispname
2239 name = self.name
2240 latexname = self.latexname
2241 dispname += "^0.5"
2242 name += " ** 0.5"
2243 latexname += "^0.5"
2244 scale = self.scale / 2
2245 u = Unit(
2246 10.0**scale,
2247 dim=self.dim**0.5,
2248 name=name,
2249 dispname=dispname,
2250 latexname=latexname,
2251 scale=scale,
2252 iscompound=True,
2253 )
2254 return u
2255 elif ufunc.__name__ == "reciprocal":
2256 if self.iscompound:
2257 dispname = f"({self.dispname})"
2258 name = f"({self.name})"
2259 latexname = r"\left(%s\right)" % self.latexname
2260 else:
2261 dispname = self.dispname
2262 name = self.name
2263 latexname = self.latexname
2264 dispname += "^-1"
2265 name += " ** -1"
2266 latexname += "^{-1}"
2267 scale = -self.scale
2268 u = Unit(
2269 10.0**scale,
2270 dim=self.dim**-1,
2271 name=name,
2272 dispname=dispname,
2273 latexname=latexname,
2274 scale=scale,
2275 iscompound=True,
2276 )
2277 return u
2278 else:
2279 # Treat the unit as a Quantity (e.g. meter + meter should not fail but give 2*meter)
2280 return super().__array_ufunc__(ufunc, method, *inputs, **kwargs)
2281
2282 def __iadd__(self, other):
2283 raise TypeError("Units cannot be modified in-place")
2284
2285 def __isub__(self, other):
2286 raise TypeError("Units cannot be modified in-place")
2287
2288 def __imul__(self, other):
2289 raise TypeError("Units cannot be modified in-place")
2290
2291 def __idiv__(self, other):
2292 raise TypeError("Units cannot be modified in-place")
2293
2294 def __itruediv__(self, other):
2295 raise TypeError("Units cannot be modified in-place")
2296
2297 def __ifloordiv__(self, other):
2298 raise TypeError("Units cannot be modified in-place")
2299
2300 def __imod__(self, other):
2301 raise TypeError("Units cannot be modified in-place")
2302
2303 def __ipow__(self, other, modulo=None):
2304 raise TypeError("Units cannot be modified in-place")
2305
2306 def __eq__(self, other):
2307 if isinstance(other, Unit):
2308 return other.dim is self.dim and other.scale == self.scale
2309 else:
2310 return Quantity.__eq__(self, other)
2311
2312 def __neq__(self, other):
2313 return not self.__eq__(other)
2314
2315 def __hash__(self):
2316 return hash((self.dim, self.scale))
2317
2318
2319 class UnitRegistry:
2320 """
2321 Stores known units for printing in best units.
2322
2323 All a user needs to do is to use the `register_new_unit`
2324 function.
2325
2326 Default registries:
2327
2328 The units module defines three registries, the standard units,
2329 user units, and additional units. Finding best units is done
2330 by first checking standard, then user, then additional. New
2331 user units are added by using the `register_new_unit` function.
2332
2333 Standard units includes all the basic non-compound unit names
2334 built in to the module, including volt, amp, etc. Additional
2335 units defines some compound units like newton metre (Nm) etc.
2336
2337 Methods
2338 -------
2339 add
2340 __getitem__
2341 """
2342
2343 def __init__(self):
2344 self.units = collections.OrderedDict()
2345 self.units_for_dimensions = collections.defaultdict(dict)
2346
2347 def add(self, u):
2348 """Add a unit to the registry"""
2349 self.units[repr(u)] = u
2350 self.units_for_dimensions[u.dim][float(u)] = u
2351
2352 def __getitem__(self, x):
2353 """Returns the best unit for quantity x
2354
2355 The algorithm is to consider the value:
2356
2357 m=abs(x/u)
2358
2359 for all matching units u. We select the unit where this ratio is the
2360 closest to 10 (if it is an array with several values, we select the
2361 unit where the deviations from that are the smallest. More precisely,
2362 the unit that minimizes the sum of (log10(m)-1)**2 over all entries).
2363 """
2364 matching = self.units_for_dimensions.get(x.dim, {})
2365 if len(matching) == 0:
2366 raise KeyError("Unit not found in registry.")
2367
2368 matching_values = np.asarray(list(matching.keys()))
2369 print_opts = np.get_printoptions()
2370 edgeitems, threshold = print_opts["edgeitems"], print_opts["threshold"]
2371 if x.size > threshold:
2372 # Only care about optimizing the units for the values that will
2373 # actually be shown later
2374 # The code looks a bit complex, but should return the same numbers
2375 # that are shown by numpy's string conversion
2376 slices = []
2377 for shape in x.shape:
2378 if shape > 2 * edgeitems:
2379 slices.append((slice(0, edgeitems), slice(-edgeitems, None)))
2380 else:
2381 slices.append((slice(None),))
2382 x_flat = np.hstack(
2383 [x[use_slices].flatten() for use_slices in itertools.product(*slices)]
2384 )
2385 else:
2386 x_flat = np.asarray(x).flatten()
2387 floatreps = np.tile(np.abs(x_flat), (len(matching), 1)).T / matching_values
2388 # ignore zeros, they are well represented in any unit
2389 floatreps[floatreps == 0] = np.nan
2390 if np.all(np.isnan(floatreps)):
2391 return matching[1.0] # all zeros, use the base unit
2392
2393 deviations = np.nansum((np.log10(floatreps) - 1) ** 2, axis=0)
2394 return list(matching.values())[deviations.argmin()]
2395
2396
2397 def register_new_unit(u):
2398 """Register a new unit for automatic displaying of quantities
2399
2400 Parameters
2401 ----------
2402 u : `Unit`
2403 The unit that should be registered.
2404
2405 Examples
2406 --------
2407 >>> from brian2 import *
2408 >>> 2.0*farad/metre**2
2409 2. * metre ** -4 * kilogram ** -1 * second ** 4 * amp ** 2
2410 >>> register_new_unit(pfarad / mmetre**2)
2411 >>> 2.0*farad/metre**2
2412 2000000. * pfarad / (mmetre ** 2)
2413 """
2414 user_unit_register.add(u)
2415
2416
2417 #: `UnitRegistry` containing all the standard units (metre, kilogram, um2...)
2418 standard_unit_register = UnitRegistry()
2419 #: `UnitRegistry` containing additional units (newton*metre, farad / metre, ...)
2420 additional_unit_register = UnitRegistry()
2421 #: `UnitRegistry` containing all units defined by the user
2422 user_unit_register = UnitRegistry()
2423
2424
2425 def get_unit(d):
2426 """
2427 Find an unscaled unit (e.g. `volt` but not `mvolt`) for a `Dimension`.
2428
2429 Parameters
2430 ----------
2431 d : `Dimension`
2432 The dimension to find a unit for.
2433
2434 Returns
2435 -------
2436 u : `Unit`
2437 A registered unscaled `Unit` for the dimensions ``d``, or a new `Unit`
2438 if no unit was found.
2439 """
2440 for unit_register in [
2441 standard_unit_register,
2442 user_unit_register,
2443 additional_unit_register,
2444 ]:
2445 if 1.0 in unit_register.units_for_dimensions[d]:
2446 return unit_register.units_for_dimensions[d][1.0]
2447 return Unit(1.0, dim=d)
2448
2449
2450 def get_unit_for_display(d):
2451 """
2452 Return a string representation of an appropriate unscaled unit or ``'1'``
2453 for a dimensionless quantity.
2454
2455 Parameters
2456 ----------
2457 d : `Dimension` or int
2458 The dimension to find a unit for.
2459
2460 Returns
2461 -------
2462 s : str
2463 A string representation of the respective unit or the string ``'1'``.
2464 """
2465 if (isinstance(d, int) and d == 1) or d is DIMENSIONLESS:
2466 return "1"
2467 else:
2468 return str(get_unit(d))
2469
2470
2471 #### DECORATORS
2472
2473
2474 def check_units(**au):
2475 """Decorator to check units of arguments passed to a function
2476
2477 Examples
2478 --------
2479 >>> from brian2.units import *
2480 >>> @check_units(I=amp, R=ohm, wibble=metre, result=volt)
2481 ... def getvoltage(I, R, **k):
2482 ... return I*R
2483
2484 You don't have to check the units of every variable in the function, and
2485 you can define what the units should be for variables that aren't
2486 explicitly named in the definition of the function. For example, the code
2487 above checks that the variable wibble should be a length, so writing
2488
2489 >>> getvoltage(1*amp, 1*ohm, wibble=1) # doctest: +IGNORE_EXCEPTION_DETAIL
2490 Traceback (most recent call last):
2491 ...
2492 DimensionMismatchError: Function "getvoltage" variable "wibble" has wrong dimensions, dimensions were (1) (m)
2493
2494 fails, but
2495
2496 >>> getvoltage(1*amp, 1*ohm, wibble=1*metre)
2497 1. * volt
2498
2499 passes. String arguments or ``None`` are not checked
2500
2501 >>> getvoltage(1*amp, 1*ohm, wibble='hello')
2502 1. * volt
2503
2504 By using the special name ``result``, you can check the return value of the
2505 function.
2506
2507 You can also use ``1`` or ``bool`` as a special value to check for a
2508 unitless number or a boolean value, respectively:
2509
2510 >>> @check_units(value=1, absolute=bool, result=bool)
2511 ... def is_high(value, absolute=False):
2512 ... if absolute:
2513 ... return abs(value) >= 5
2514 ... else:
2515 ... return value >= 5
2516
2517 This will then again raise an error if the argument if not of the expected
2518 type:
2519
2520 >>> is_high(7)
2521 True
2522 >>> is_high(-7, True)
2523 True
2524 >>> is_high(3, 4) # doctest: +IGNORE_EXCEPTION_DETAIL
2525 Traceback (most recent call last):
2526 ...
2527 TypeError: Function "is_high" expected a boolean value for argument "absolute" but got 4.
2528
2529 If the return unit depends on the unit of an argument, you can also pass
2530 a function that takes the units of all the arguments as its inputs (in the
2531 order specified in the function header):
2532
2533 >>> @check_units(result=lambda d: d**2)
2534 ... def square(value):
2535 ... return value**2
2536
2537 If several arguments take arbitrary units but they have to be
2538 consistent among each other, you can state the name of another argument as
2539 a string to state that it uses the same unit as that argument.
2540
2541 >>> @check_units(summand_1=None, summand_2='summand_1')
2542 ... def multiply_sum(multiplicand, summand_1, summand_2):
2543 ... "Calculates multiplicand*(summand_1 + summand_2)"
2544 ... return multiplicand*(summand_1 + summand_2)
2545 >>> multiply_sum(3, 4*mV, 5*mV)
2546 27. * mvolt
2547 >>> multiply_sum(3*nA, 4*mV, 5*mV)
2548 27. * pwatt
2549 >>> multiply_sum(3*nA, 4*mV, 5*nA) # doctest: +IGNORE_EXCEPTION_DETAIL
2550 Traceback (most recent call last):
2551 ...
2552 brian2.units.fundamentalunits.DimensionMismatchError: Function 'multiply_sum' expected the same arguments for arguments 'summand_1', 'summand_2', but argument 'summand_1' has unit V, while argument 'summand_2' has unit A.
2553
2554 Raises
2555 ------
2556
2557 DimensionMismatchError
2558 In case the input arguments or the return value do not have the
2559 expected dimensions.
2560 TypeError
2561 If an input argument or return value was expected to be a boolean but
2562 is not.
2563
2564 Notes
2565 -----
2566 This decorator will destroy the signature of the original function, and
2567 replace it with the signature ``(*args, **kwds)``. Other decorators will
2568 do the same thing, and this decorator critically needs to know the signature
2569 of the function it is acting on, so it is important that it is the first
2570 decorator to act on a function. It cannot be used in combination with
2571 another decorator that also needs to know the signature of the function.
2572
2573 Note that the ``bool`` type is "strict", i.e. it expects a proper
2574 boolean value and does not accept 0 or 1. This is not the case the other
2575 way round, declaring an argument or return value as "1" *does* allow for a
2576 ``True`` or ``False`` value.
2577 """
2578
2579 def do_check_units(f):
2580 @functools.wraps(f)
2581 def new_f(*args, **kwds):
2582 newkeyset = kwds.copy()
2583 arg_names = f.__code__.co_varnames[0 : f.__code__.co_argcount]
2584 for n, v in zip(arg_names, args[0 : f.__code__.co_argcount], strict=False):
2585 if (
2586 not isinstance(v, (Quantity, str, bool, np.bool_))
2587 and v is not None
2588 and n in au
2589 ):
2590 try:
2591 # allow e.g. to pass a Python list of values
2592 v = Quantity(v)
2593 except TypeError as ex:
2594 if have_same_dimensions(au[n], 1):
2595 raise TypeError(
2596 f"Argument {n} is not a unitless value/array."
2597 ) from ex
2598 else:
2599 raise TypeError(
2600 f"Argument '{n}' is not a quantity, "
2601 "expected a quantity with dimensions "
2602 f"{au[n]}"
2603 ) from ex
2604 newkeyset[n] = v
2605
2606 for k in newkeyset:
2607 # string variables are allowed to pass, the presumption is they
2608 # name another variable. None is also allowed, useful for
2609 # default parameters
2610 if (
2611 k in au
2612 and not isinstance(newkeyset[k], str)
2613 and newkeyset[k] is not None
2614 and au[k] is not None
2615 ):
2616 if au[k] in (bool, np.bool_):
2617 if not isinstance(newkeyset[k], (bool, np.bool_)):
2618 value = newkeyset[k]
2619 error_message = (
2620 f"Function '{f.__name__}' "
2621 "expected a boolean value "
2622 f"for argument '{k}' but got "
2623 f"'{value}'"
2624 )
2625 raise TypeError(error_message)
2626 elif isinstance(au[k], str):
2627 if au[k] not in newkeyset:
2628 error_message = (
2629 f"Function '{f.__name__}' "
2630 "expected its argument to have the "
2631 f"same units as argument '{k}', but "
2632 "there is no argument of that name"
2633 )
2634 raise TypeError(error_message)
2635 if not have_same_dimensions(newkeyset[k], newkeyset[au[k]]):
2636 d1 = get_dimensions(newkeyset[k])
2637 d2 = get_dimensions(newkeyset[au[k]])
2638 error_message = (
2639 f"Function '{f.__name__}' expected "
2640 f"the argument '{k}' to have the same "
2641 f"units as argument '{au[k]}', but "
2642 f"argument '{k}' has "
2643 f"unit {get_unit_for_display(d1)}, "
2644 f"while argument '{au[k]}' "
2645 f"has unit {get_unit_for_display(d2)}."
2646 )
2647 raise DimensionMismatchError(error_message)
2648 elif not have_same_dimensions(newkeyset[k], au[k]):
2649 unit = repr(au[k])
2650 value = newkeyset[k]
2651 error_message = (
2652 f"Function '{f.__name__}' "
2653 "expected a quantity with unit "
2654 f"{unit} for argument '{k}' but got "
2655 f"'{value}'"
2656 )
2657 raise DimensionMismatchError(
2658 error_message, get_dimensions(newkeyset[k])
2659 )
2660
2661 result = f(*args, **kwds)
2662 if "result" in au:
2663 if isinstance(au["result"], Callable) and au["result"] not in (
2664 bool,
2665 np.bool_,
2666 ):
2667 expected_result = au["result"](*[get_dimensions(a) for a in args])
2668 else:
2669 expected_result = au["result"]
2670 if au["result"] in (bool, np.bool_):
2671 if not isinstance(result, (bool, np.bool_)):
2672 error_message = (
2673 "The return value of function "
2674 f"'{f.__name__}' was expected to be "
2675 "a boolean value, but was of type "
2676 f"{type(result)}"
2677 )
2678 raise TypeError(error_message)
2679 elif not have_same_dimensions(result, expected_result):
2680 unit = get_unit_for_display(expected_result)
2681 error_message = (
2682 "The return value of function "
2683 f"'{f.__name__}' was expected to have "
2684 f"unit {unit} but was "
2685 f"'{result}'"
2686 )
2687 raise DimensionMismatchError(error_message, get_dimensions(result))
2688 return result
2689
2690 new_f._orig_func = f
2691 new_f.__doc__ = f.__doc__
2692 new_f.__name__ = f.__name__
2693 # store the information in the function, necessary when using the
2694 # function in expressions or equations
2695 if hasattr(f, "_orig_arg_names"):
2696 arg_names = f._orig_arg_names
2697 else:
2698 arg_names = f.__code__.co_varnames[: f.__code__.co_argcount]
2699 new_f._arg_names = arg_names
2700 new_f._arg_units = [au.get(name) for name in arg_names]
2701 return_unit = au.get("result")
2702 if return_unit is None:
2703 new_f._return_unit = None
2704 else:
2705 new_f._return_unit = return_unit
2706 if return_unit is bool:
2707 new_f._returns_bool = True
2708 else:
2709 new_f._returns_bool = False
2710 new_f._orig_arg_names = arg_names
2711
2712 # copy any annotation attributes
2713 if hasattr(f, "_annotation_attributes"):
2714 for attrname in f._annotation_attributes:
2715 setattr(new_f, attrname, getattr(f, attrname))
2716 new_f._annotation_attributes = getattr(f, "_annotation_attributes", []) + [
2717 "_arg_units",
2718 "_arg_names",
2719 "_return_unit",
2720 "_orig_func",
2721 "_returns_bool",
2722 ]
2723 return new_f
2724
2725 return do_check_units