Debian Codegraph @

docs_sphinx/developer/units.rst

raw
1 Units
2 =====
3
4 Casting rules
5 -------------
6 In Brian 1, a distinction is made between scalars and numpy arrays (including
7 scalar arrays): Scalars could be multiplied with a unit, resulting in a Quantity
8 object whereas the multiplication of an array with a unit resulted in a
9 (unitless) array. Accordingly, scalars were considered as dimensionless
10 quantities for the purpose of unit checking (e.g.. 1 + 1 * mV raised an error)
11 whereas arrays were not (e.g. array(1) + 1 * mV resulted in 1.001 without any
12 errors). Brian 2 no longer makes this distinction and treats both scalars and
13 arrays as dimensionless for unit checking and make all operations involving
14 quantities return a quantity.::
15
16 >>> 1 + 1*second # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
17 Traceback (most recent call last):
18 ...
19 DimensionMismatchError: Cannot calculate 1. s + 1, units do not match (units are second and 1).
20
21 >>> np.array([1]) + 1*second # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
22 Traceback (most recent call last):
23 ...
24 DimensionMismatchError: Cannot calculate 1. s + [1], units do not match (units are second and 1).
25
26 >>> 1*second + 1*second
27 2. * second
28 >>> np.array([1])*second + 1*second
29 array([ 2.]) * second
30
31 As one exception from this rule, a scalar or array ``0`` is considered as having
32 "any unit", i.e. ``0 + 1 * second`` will result in ``1 * second`` without a
33 dimension mismatch error and ``0 == 0 * mV`` will evaluate to ``True``. This
34 seems reasonable from a mathematical viewpoint and makes some sources of error
35 disappear. For example, the Python builtin ``sum`` (not numpy's version) adds
36 the value of the optional argument ``start``, which defaults to 0, to its
37 main argument. Without this exception, ``sum([1 * mV, 2 * mV])`` would therefore
38 raise an error.
39
40 The above rules also apply to all comparisons (e.g. ``==`` or ``<``) with one
41 further exception: ``inf`` and ``-inf`` also have "any unit", therefore an
42 expression like ``v <= inf`` will never raise an exception (and always return
43 ``True``).
44
45 Functions and units
46 -------------------
47
48 ndarray methods
49 ~~~~~~~~~~~~~~~
50 All methods that make sense on quantities should work, i.e. they check for the
51 correct units of their arguments and return quantities with units were
52 appropriate. Most of the methods are overwritten using thin function wrappers:
53
54 ``wrap_function_keep_dimension``:
55 Strips away the units before giving the array to the method of ``ndarray``,
56 then reattaches the unit to the result (examples: sum, mean, max)
57
58 ``wrap_function_change_dimension``:
59 Changes the dimensions in a simple way that is independent of function
60 arguments, the shape of the array, etc. (examples: sqrt, var, power)
61
62 ``wrap_function_dimensionless``:
63 Raises an error if the method is called on a quantity with dimensions (i.e.
64 it works on dimensionless quantities).
65
66 **List of methods**
67
68 ``all``, ``any``, ``argmax``, ``argsort``, ``clip``, ``compress``, ``conj``, ``conjugate``,
69 ``copy``, ``cumsum``, ``diagonal``, ``dot``, ``dump``, ``dumps``, ``fill``, ``flatten``, ``getfield``,
70 ``item``, ``itemset``, ``max``, ``mean``, ``min``, ``newbyteorder``, ``nonzero``, ``prod``, ``ptp``,
71 ``put``, ``ravel``, ``repeat``, ``reshape``, ``round``, ``searchsorted``, ``setasflat``, ``setfield``,
72 ``setflags``, ``sort``, ``squeeze``, ``std``, ``sum``, ``take``, ``tolist``, ``trace``, ``transpose``,
73 ``var``, ``view``
74
75 **Notes**
76
77 * Methods directly working on the internal data buffer (``setfield``,
78 ``getfield``, ``newbyteorder``) ignore the dimensions of the quantity.
79 * The type of a quantity cannot be int, therefore ``astype`` does not quite
80 work when trying to convert the array into integers.
81 * ``choose`` is only defined for integer arrays and therefore does not work
82 * ``tostring`` and ``tofile`` only return/save the pure array data without the
83 unit (but you can use ``dump`` or ``dumps`` to pickle a quantity array)
84 * ``resize`` does not work: ``ValueError: cannot resize this array: it does not
85 own its data``
86 * ``cumprod`` would result in different dimensions for different elements and is
87 therefore forbidden
88 * ``item`` returns a pure Python float by definition
89 * ``itemset`` does not check for units
90
91 Numpy ufuncs
92 ~~~~~~~~~~~~
93
94 All of the standard `numpy ufuncs`_ (functions that operate element-wise on numpy
95 arrays) are supported, meaning that they check for correct units and return
96 appropriate arrays. These functions are often called implicitly, for example
97 when using operators like ``<`` or ``**``.
98
99 *Math operations:*
100 ``add``, ``subtract``, ``multiply``, ``divide``, ``logaddexp``, ``logaddexp2``,
101 ``true_divide``, ``floor_divide``, ``negative``, ``power``, ``remainder``, ``mod``,
102 ``fmod``, ``absolute``, ``rint``, ``sign``, ``conj``, ``conjugate``, ``exp``, ``exp2``,
103 ``log``, ``log2``, ``log10``, ``expm1``, ``log1p``, ``sqrt``, ``square``, ``reciprocal``,
104 ``ones_like``
105
106 *Trigonometric functions:*
107 ``sin``, ``cos``, ``tan``, ``arcsin``, ``arccos``, ``arctan``, ``arctan2``, ``hypot``,
108 ``sinh``, ``cosh``, ``tanh``, ``arcsinh``, ``arccosh``, ``arctanh``, ``deg2rad``, ``rad2deg``
109
110 *Bitwise functions:*
111 ``bitwise_and``, ``bitwise_or``, ``bitwise_xor``, ``invert``, ``left_shift``, ``right_shift``
112
113 *Comparison functions:*
114 ``greater``, ``greater_equal``, ``less``, ``less_equal``, ``not_equal``,
115 ``equal``, ``logical_and``, ``logical_or``, ``logical_xor``, ``logical_not``, ``maximum``,
116 ``minimum``
117
118 *Floating functions:*
119 ``isreal``, ``iscomplex``, ``isfinite``, ``isinf``, ``isnan``, ``floor``, ``ceil``, ``trunc``,
120 ``fmod``
121
122 Not taken care of yet: ``signbit``, ``copysign``, ``nextafter``, ``modf``, ``ldexp``, ``frexp``
123
124 **Notes**
125
126 * Everything involving ``log`` or ``exp``, as well as trigonometric functions
127 only works on dimensionless array (for ``arctan2`` and ``hypot`` this is
128 questionable, though)
129 * Unit arrays can only be raised to a scalar power, not to an array of
130 exponents as this would lead to differing dimensions across entries. For
131 simplicity, this is enforced even for dimensionless quantities.
132 * Bitwise functions never works on quantities (numpy will by itself throw a
133 ``TypeError`` because they are floats not integers).
134 * All comparisons only work for matching dimensions (with the exception of
135 always allowing comparisons to 0) and return a pure boolean array.
136 * All logical functions treat quantities as boolean values in the same
137 way as floats are treated as boolean: Any non-zero value is True.
138
139 .. _numpy ufuncs: http://docs.scipy.org/doc/numpy/reference/ufuncs.html
140
141 Numpy functions
142 ~~~~~~~~~~~~~~~
143 Many numpy functions are functional versions of ndarray methods (e.g. ``mean``,
144 ``sum``, ``clip``). They therefore work automatically when called on quantities,
145 as numpy propagates the call to the respective method.
146
147 There are some functions in numpy that do not propagate their call to the
148 corresponding method (because they use np.asarray instead of np.asanyarray,
149 which might actually be a bug in numpy): ``trace``, ``diagonal``, ``ravel``,
150 ``dot``. For these, wrapped functions in ``unitsafefunctions.py`` are provided.
151
152 **Wrapped numpy functions in unitsafefunctions.py**
153
154 These functions are thin wrappers around the numpy functions to correctly check
155 for units and return quantities when appropriate:
156
157 ``log``, ``exp``, ``sin``, ``cos``, ``tan``, ``arcsin``, ``arccos``, ``arctan``, ``sinh``,
158 ``cosh``, ``tanh``, ``arcsinh``, ``arccosh``, ``arctanh``, ``diagonal``, ``ravel``, ``trace``,
159 ``dot``
160
161 **numpy functions that work unchanged**
162
163 This includes all functional counterparts of the methods mentioned above (with
164 the exceptions mentioned above). Some other functions also work correctly, as
165 they are only using functions/methods that work with quantities:
166
167 * ``linspace``, ``diff``, ``digitize`` [1]_
168 * ``trim_zeros``, ``fliplr``, ``flipud``, ``roll``, ``rot90``, ``shuffle``
169 * ``corrcoeff`` [1]_
170
171 .. [1] But does not care about the units of its input.
172
173 **numpy functions that return a pure numpy array instead of quantities**
174
175 * ``arange``
176 * ``cov``
177 * ``random.permutation``
178 * ``histogram``, ``histogram2d``
179 * ``cross``, ``inner``, ``outer``
180 * ``where``
181
182 **numpy functions that do something wrong**
183
184 * ``insert``, ``delete`` (return a quantity array but without units)
185 * ``correlate`` (returns a quantity with wrong units)
186 * ``histogramdd`` (raises a ``DimensionMismatchError``)
187
188 **other unsupported functions**
189 Functions in ``numpy``'s subpackages such as ``linalg`` are not supported and will
190 either not work with units, or remove units from their inputs.
191
192 User-defined functions and units
193 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
194 For performance and simplicity reasons, code within the Brian core does not use
195 Quantity objects but unitless numpy arrays instead. See :doc:`functions` for
196 details on how to make use user-defined functions with Brian's unit system.