1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
|
"""
Classes used to specify the type of a function, variable or common
sub-expression.
"""
import collections
import functools
import numbers
from collections.abc import Mapping
import numpy as np
from brian2.units.fundamentalunits import (
DIMENSIONLESS,
Dimension,
Quantity,
fail_for_dimension_mismatch,
get_unit,
get_unit_for_display,
)
from brian2.utils.caching import CacheKey
from brian2.utils.logger import get_logger
from brian2.utils.stringtools import get_identifiers, word_substitute
from .base import device_override, weakproxy_with_fallback
from .preferences import prefs
__all__ = [
"Variable",
"Constant",
"ArrayVariable",
"DynamicArrayVariable",
"Subexpression",
"AuxiliaryVariable",
"VariableView",
"Variables",
"LinkedVariable",
"linked_var",
]
logger = get_logger(__name__)
def get_dtype(obj):
"""
Helper function to return the `numpy.dtype` of an arbitrary object.
Parameters
----------
obj : object
Any object (but typically some kind of number or array).
Returns
-------
dtype : `numpy.dtype`
The type of the given object.
"""
if hasattr(obj, "dtype"):
return obj.dtype
else:
return np.dtype(type(obj))
def get_dtype_str(val):
"""
Returns canonical string representation of the dtype of a value or dtype
Returns
-------
dtype_str : str
The numpy dtype name
"""
if isinstance(val, np.dtype):
return val.name
if isinstance(val, type):
return get_dtype_str(val())
is_bool = val is True or val is False or val is np.True_ or val is np.False_
if is_bool:
return "bool"
if hasattr(val, "dtype"):
return get_dtype_str(val.dtype)
if isinstance(val, numbers.Number):
return get_dtype_str(np.array(val).dtype)
return f"unknown[{str(val)}, {val.__class__.__name__}]"
def variables_by_owner(variables, owner):
owner_name = getattr(owner, "name", None)
return {
varname: var
for varname, var in variables.items()
if getattr(var.owner, "name", None) is owner_name
}
class Variable(CacheKey):
r"""
An object providing information about model variables (including implicit
variables such as ``t`` or ``xi``). This class should never be
instantiated outside of testing code, use one of its subclasses instead.
Parameters
----------
name : 'str'
The name of the variable. Note that this refers to the *original*
name in the owning group. The same variable may be known under other
names in other groups (e.g. the variable ``v`` of a `NeuronGroup` is
known as ``v_post`` in a `Synapse` connecting to the group).
dimensions : `Dimension`, optional
The physical dimensions of the variable.
owner : `Nameable`, optional
The object that "owns" this variable, e.g. the `NeuronGroup` or
`Synapses` object that declares the variable in its model equations.
Defaults to ``None`` (the value used for `Variable` objects without an
owner, e.g. external `Constant`\ s).
dtype : `dtype`, optional
The dtype used for storing the variable. Defaults to the preference
`core.default_scalar.dtype`.
scalar : bool, optional
Whether the variable is a scalar value (``True``) or vector-valued, e.g.
defined for every neuron (``False``). Defaults to ``False``.
constant: bool, optional
Whether the value of this variable can change during a run. Defaults
to ``False``.
read_only : bool, optional
Whether this is a read-only variable, i.e. a variable that is set
internally and cannot be changed by the user (this is used for example
for the variable ``N``, the number of neurons in a group). Defaults
to ``False``.
array : bool, optional
Whether this variable is an array. Allows for simpler check than testing
``isinstance(var, ArrayVariable)``. Defaults to ``False``.
"""
_cache_irrelevant_attributes = {"owner"}
def __init__(
self,
name,
dimensions=DIMENSIONLESS,
owner=None,
dtype=None,
scalar=False,
constant=False,
read_only=False,
dynamic=False,
array=False,
):
assert isinstance(dimensions, Dimension)
#: The variable's dimensions.
self.dim = dimensions
#: The variable's name.
self.name = name
#: The `Group` to which this variable belongs.
self.owner = weakproxy_with_fallback(owner) if owner is not None else None
#: The dtype used for storing the variable.
self.dtype = dtype
if dtype is None:
self.dtype = prefs.core.default_float_dtype
if self.is_boolean:
if dimensions is not DIMENSIONLESS:
raise ValueError("Boolean variables can only be dimensionless")
#: Whether the variable is a scalar
self.scalar = scalar
#: Whether the variable is constant during a run
self.constant = constant
#: Whether the variable is read-only
self.read_only = read_only
#: Whether the variable is dynamically sized (only for non-scalars)
self.dynamic = dynamic
#: Whether the variable is an array
self.array = array
def __getstate__(self):
state = self.__dict__.copy()
state["owner"] = state["owner"].__repr__.__self__ # replace proxy
return state
def __setstate__(self, state):
state["owner"] = weakproxy_with_fallback(state["owner"])
self.__dict__ = state
@property
def is_boolean(self):
return np.issubdtype(self.dtype, np.bool_)
@property
def is_integer(self):
return np.issubdtype(self.dtype, np.signedinteger)
@property
def dtype_str(self):
"""
String representation of the numpy dtype
"""
return get_dtype_str(self)
@property
def unit(self):
"""
The `Unit` of this variable
"""
return get_unit(self.dim)
def get_value(self):
"""
Return the value associated with the variable (without units). This
is the way variables are accessed in generated code.
"""
raise TypeError(f"Cannot get value for variable {self}")
def set_value(self, value):
"""
Set the value associated with the variable.
"""
raise TypeError(f"Cannot set value for variable {self}")
def get_value_with_unit(self):
"""
Return the value associated with the variable (with units).
"""
return Quantity(self.get_value(), self.dim)
def get_addressable_value(self, name, group):
"""
Get the value (without units) of this variable in a form that can be
indexed in the context of a group. For example, if a
postsynaptic variable ``x`` is accessed in a synapse ``S`` as
``S.x_post``, the synaptic indexing scheme can be used.
Parameters
----------
name : str
The name of the variable
group : `Group`
The group providing the context for the indexing. Note that this
`group` is not necessarily the same as `Variable.owner`: a variable
owned by a `NeuronGroup` can be indexed in a different way if
accessed via a `Synapses` object.
Returns
-------
variable : object
The variable in an indexable form (without units).
"""
return self.get_value()
def get_addressable_value_with_unit(self, name, group):
"""
Get the value (with units) of this variable in a form that can be
indexed in the context of a group. For example, if a postsynaptic
variable ``x`` is accessed in a synapse ``S`` as ``S.x_post``, the
synaptic indexing scheme can be used.
Parameters
----------
name : str
The name of the variable
group : `Group`
The group providing the context for the indexing. Note that this
`group` is not necessarily the same as `Variable.owner`: a variable
owned by a `NeuronGroup` can be indexed in a different way if
accessed via a `Synapses` object.
Returns
-------
variable : object
The variable in an indexable form (with units).
"""
return self.get_value_with_unit()
def get_len(self):
"""
Get the length of the value associated with the variable or ``0`` for
a scalar variable.
"""
if self.scalar:
return 0
else:
return len(self.get_value())
def __len__(self):
return self.get_len()
def __repr__(self):
description = (
"<{classname}(dimensions={dimensions}, "
" dtype={dtype}, scalar={scalar}, constant={constant},"
" read_only={read_only})>"
)
return description.format(
classname=self.__class__.__name__,
dimensions=repr(self.dim),
dtype=getattr(self.dtype, "__name__", repr(self.dtype)),
scalar=repr(self.scalar),
constant=repr(self.constant),
read_only=repr(self.read_only),
)
# ------------------------------------------------------------------------------
# Concrete classes derived from `Variable` -- these are the only ones ever
# instantiated.
# ------------------------------------------------------------------------------
class Constant(Variable):
"""
A scalar constant (e.g. the number of neurons ``N``). Information such as
the dtype or whether this variable is a boolean are directly derived from
the `value`. Most of the time `Variables.add_constant` should be used
instead of instantiating this class directly.
Parameters
----------
name : str
The name of the variable
dimensions : `Dimension`, optional
The physical dimensions of the variable. Note that the variable itself
(as referenced by value) should never have units attached.
value: reference to the variable value
The value of the constant.
owner : `Nameable`, optional
The object that "owns" this variable, for constants that belong to a
specific group, e.g. the ``N`` constant for a `NeuronGroup`. External
constants will have ``None`` (the default value).
"""
def __init__(self, name, value, dimensions=DIMENSIONLESS, owner=None):
# Determine the type of the value
is_bool = (
value is True or value is False or value is np.True_ or value is np.False_
)
if is_bool:
dtype = bool
else:
dtype = get_dtype(value)
# Use standard Python types if possible for numpy scalars
if getattr(value, "shape", None) == () and hasattr(value, "dtype"):
numpy_type = value.dtype
if np.can_cast(numpy_type, int):
value = int(value)
elif np.can_cast(numpy_type, float):
value = float(value)
elif np.can_cast(numpy_type, complex):
value = complex(value)
elif value is np.True_:
value = True
elif value is np.False_:
value = False
#: The constant's value
self.value = value
super().__init__(
dimensions=dimensions,
name=name,
owner=owner,
dtype=dtype,
scalar=True,
constant=True,
read_only=True,
)
def get_value(self):
return self.value
def item(self):
return self.value
class AuxiliaryVariable(Variable):
"""
Variable description for an auxiliary variable (most likely one that is
added automatically to abstract code, e.g. ``_cond`` for a threshold
condition), specifying its type and unit for code generation. Most of the
time `Variables.add_auxiliary_variable` should be used instead of
instantiating this class directly.
Parameters
----------
name : str
The name of the variable
dimensions : `Dimension`, optional
The physical dimensions of the variable.
dtype : `dtype`, optional
The dtype used for storing the variable. If none is given, defaults
to `core.default_float_dtype`.
scalar : bool, optional
Whether the variable is a scalar value (``True``) or vector-valued, e.g.
defined for every neuron (``False``). Defaults to ``False``.
"""
def __init__(self, name, dimensions=DIMENSIONLESS, dtype=None, scalar=False):
super().__init__(dimensions=dimensions, name=name, dtype=dtype, scalar=scalar)
def get_value(self):
raise TypeError(
f"Cannot get the value for an auxiliary variable ({self.name})."
)
class ArrayVariable(Variable):
"""
An object providing information about a model variable stored in an array
(for example, all state variables). Most of the time `Variables.add_array`
should be used instead of instantiating this class directly.
Parameters
----------
name : 'str'
The name of the variable. Note that this refers to the *original*
name in the owning group. The same variable may be known under other
names in other groups (e.g. the variable ``v`` of a `NeuronGroup` is
known as ``v_post`` in a `Synapse` connecting to the group).
dimensions : `Dimension`, optional
The physical dimensions of the variable
owner : `Nameable`
The object that "owns" this variable, e.g. the `NeuronGroup` or
`Synapses` object that declares the variable in its model equations.
size : int
The size of the array
device : `Device`
The device responsible for the memory access.
dtype : `dtype`, optional
The dtype used for storing the variable. If none is given, defaults
to `core.default_float_dtype`.
constant : bool, optional
Whether the variable's value is constant during a run.
Defaults to ``False``.
scalar : bool, optional
Whether this array is a 1-element array that should be treated like a
scalar (e.g. for a single delay value across synapses). Defaults to
``False``.
read_only : bool, optional
Whether this is a read-only variable, i.e. a variable that is set
internally and cannot be changed by the user. Defaults
to ``False``.
unique : bool, optional
Whether the values in this array are all unique. This information is
only important for variables used as indices and does not have to
reflect the actual contents of the array but only the possibility of
non-uniqueness (e.g. synaptic indices are always unique but the
corresponding pre- and post-synaptic indices are not). Defaults to
``False``.
"""
def __init__(
self,
name,
owner,
size,
device,
dimensions=DIMENSIONLESS,
dtype=None,
constant=False,
scalar=False,
read_only=False,
dynamic=False,
unique=False,
):
super().__init__(
dimensions=dimensions,
name=name,
owner=owner,
dtype=dtype,
scalar=scalar,
constant=constant,
read_only=read_only,
dynamic=dynamic,
array=True,
)
#: Wether all values in this arrays are necessarily unique (only
#: relevant for index variables).
self.unique = unique
#: The `Device` responsible for memory access.
self.device = device
#: The size of this variable.
self.size = size
if scalar and size != 1:
raise ValueError(f"Scalar variables need to have size 1, not size {size}.")
#: Another variable, on which the write is conditioned (e.g. a variable
#: denoting the absence of refractoriness)
self.conditional_write = None
def set_conditional_write(self, var):
if not var.is_boolean:
raise TypeError(
"A variable can only be conditionally writeable "
f"depending on a boolean variable, '{var.name}' is not "
"boolean."
)
self.conditional_write = var
def get_value(self):
return self.device.get_value(self)
def item(self):
if self.size == 1:
return self.get_value().item()
else:
raise ValueError("can only convert an array of size 1 to a Python scalar")
def set_value(self, value):
self.device.fill_with_array(self, value)
def get_len(self):
return self.size
def get_addressable_value(self, name, group):
return VariableView(name=name, variable=self, group=group, dimensions=None)
def get_addressable_value_with_unit(self, name, group):
return VariableView(name=name, variable=self, group=group, dimensions=self.dim)
class DynamicArrayVariable(ArrayVariable):
"""
An object providing information about a model variable stored in a dynamic
array (used in `Synapses`). Most of the time `Variables.add_dynamic_array`
should be used instead of instantiating this class directly.
Parameters
----------
name : 'str'
The name of the variable. Note that this refers to the *original*
name in the owning group. The same variable may be known under other
names in other groups (e.g. the variable ``v`` of a `NeuronGroup` is
known as ``v_post`` in a `Synapse` connecting to the group).
dimensions : `Dimension`, optional
The physical dimensions of the variable.
owner : `Nameable`
The object that "owns" this variable, e.g. the `NeuronGroup` or
`Synapses` object that declares the variable in its model equations.
size : int or tuple of int
The (initial) size of the variable.
device : `Device`
The device responsible for the memory access.
dtype : `dtype`, optional
The dtype used for storing the variable. If none is given, defaults
to `core.default_float_dtype`.
constant : bool, optional
Whether the variable's value is constant during a run.
Defaults to ``False``.
needs_reference_update : bool, optional
Whether the code objects need a new reference to the underlying data at
every time step. This should be set if the size of the array can be
changed by other code objects. Defaults to ``False``.
scalar : bool, optional
Whether this array is a 1-element array that should be treated like a
scalar (e.g. for a single delay value across synapses). Defaults to
``False``.
read_only : bool, optional
Whether this is a read-only variable, i.e. a variable that is set
internally and cannot be changed by the user. Defaults
to ``False``.
unique : bool, optional
Whether the values in this array are all unique. This information is
only important for variables used as indices and does not have to
reflect the actual contents of the array but only the possibility of
non-uniqueness (e.g. synaptic indices are always unique but the
corresponding pre- and post-synaptic indices are not). Defaults to
``False``.
"""
# The size of a dynamic variable can of course change and changes in
# size should not invalidate the cache
_cache_irrelevant_attributes = ArrayVariable._cache_irrelevant_attributes | {"size"}
def __init__(
self,
name,
owner,
size,
device,
dimensions=DIMENSIONLESS,
dtype=None,
constant=False,
needs_reference_update=False,
resize_along_first=False,
scalar=False,
read_only=False,
unique=False,
):
if isinstance(size, int):
ndim = 1
else:
ndim = len(size)
#: The number of dimensions
self.ndim = ndim
if constant and needs_reference_update:
raise ValueError("A variable cannot be constant and need reference updates")
#: Whether this variable needs an update of the reference to the
#: underlying data whenever it is passed to a code object
self.needs_reference_update = needs_reference_update
#: Whether this array will be only resized along the first dimension
self.resize_along_first = resize_along_first
super().__init__(
dimensions=dimensions,
owner=owner,
name=name,
size=size,
device=device,
constant=constant,
dtype=dtype,
scalar=scalar,
dynamic=True,
read_only=read_only,
unique=unique,
)
@property
def dimensions(self):
logger.warn(
"The DynamicArrayVariable.dimensions attribute is "
"deprecated, use .ndim instead",
"deprecated_dimensions",
once=True,
)
return self.ndim
def resize(self, new_size):
"""
Resize the dynamic array. Calls `self.device.resize` to do the
actual resizing.
Parameters
----------
new_size : int or tuple of int
The new size.
"""
if self.resize_along_first:
self.device.resize_along_first(self, new_size)
else:
self.device.resize(self, new_size)
self.size = new_size
class Subexpression(Variable):
"""
An object providing information about a named subexpression in a model.
Most of the time `Variables.add_subexpression` should be used instead of
instantiating this class directly.
Parameters
----------
name : str
The name of the subexpression.
dimensions : `Dimension`, optional
The physical dimensions of the subexpression.
owner : `Group`
The group to which the expression refers.
expr : str
The subexpression itself.
device : `Device`
The device responsible for the memory access.
dtype : `dtype`, optional
The dtype used for the expression. Defaults to
`core.default_float_dtype`.
scalar: bool, optional
Whether this is an expression only referring to scalar variables.
Defaults to ``False``
"""
def __init__(
self,
name,
owner,
expr,
device,
dimensions=DIMENSIONLESS,
dtype=None,
scalar=False,
):
super().__init__(
dimensions=dimensions,
owner=owner,
name=name,
dtype=dtype,
scalar=scalar,
constant=False,
read_only=True,
)
#: The `Device` responsible for memory access
self.device = device
#: The expression defining the subexpression
self.expr = expr.strip()
#: The identifiers used in the expression
self.identifiers = get_identifiers(expr)
def get_addressable_value(self, name, group):
return VariableView(
name=name, variable=self, group=group, dimensions=DIMENSIONLESS
)
def get_addressable_value_with_unit(self, name, group):
return VariableView(name=name, variable=self, group=group, dimensions=self.dim)
def __contains__(self, var):
return var in self.identifiers
def __repr__(self):
description = (
"<{classname}(name={name}, dimensions={dimensions}, dtype={dtype}, "
"expr={expr}, owner=<{owner}>)>"
)
return description.format(
classname=self.__class__.__name__,
name=repr(self.name),
dimensions=repr(self.dim),
dtype=repr(self.dtype),
expr=repr(self.expr),
owner=self.owner.name,
)
# ------------------------------------------------------------------------------
# Classes providing views on variables and storing variables information
# ------------------------------------------------------------------------------
class LinkedVariable:
"""
A simple helper class to make linking variables explicit. Users should use
`linked_var` instead.
Parameters
----------
group : `Group`
The group through which the `variable` is accessed (not necessarily the
same as ``variable.owner``.
name : str
The name of `variable` in `group` (not necessarily the same as
``variable.name``).
variable : `Variable`
The variable that should be linked.
index : str or `ndarray`, optional
An indexing array (or the name of a state variable), providing a mapping
from the entries in the link source to the link target.
"""
def __init__(self, group, name, variable, index=None):
if isinstance(variable, DynamicArrayVariable):
raise NotImplementedError(
f"Linking to variable {variable.name} is "
"not supported, can only link to "
"state variables of fixed size."
)
self.group = group
self.name = name
self.variable = variable
self.index = index
def linked_var(group_or_variable, name=None, index=None):
"""
Represents a link target for setting a linked variable.
Parameters
----------
group_or_variable : `NeuronGroup` or `VariableView`
Either a reference to the target `NeuronGroup` (e.g. ``G``) or a direct
reference to a `VariableView` object (e.g. ``G.v``). In case only the
group is specified, `name` has to be specified as well.
name : str, optional
The name of the target variable, necessary if `group_or_variable` is a
`NeuronGroup`.
index : str or `ndarray`, optional
An indexing array (or the name of a state variable), providing a mapping
from the entries in the link source to the link target.
Examples
--------
>>> from brian2 import *
>>> G1 = NeuronGroup(10, 'dv/dt = -v / (10*ms) : volt')
>>> G2 = NeuronGroup(10, 'v : volt (linked)')
>>> G2.v = linked_var(G1, 'v')
>>> G2.v = linked_var(G1.v) # equivalent
"""
if isinstance(group_or_variable, VariableView):
if name is not None:
raise ValueError(
"Cannot give a variable and a variable name at the same time."
)
return LinkedVariable(
group_or_variable.group,
group_or_variable.name,
group_or_variable.variable,
index=index,
)
elif name is None:
raise ValueError("Need to provide a variable name")
else:
return LinkedVariable(
group_or_variable, name, group_or_variable.variables[name], index=index
)
class VariableView:
"""
A view on a variable that allows to treat it as an numpy array while
allowing special indexing (e.g. with strings) in the context of a `Group`.
Parameters
----------
name : str
The name of the variable (not necessarily the same as ``variable.name``).
variable : `Variable`
The variable description.
group : `Group`
The group through which the variable is accessed (not necessarily the
same as `variable.owner`).
dimensions : `Dimension`, optional
The physical dimensions to be used for the variable, should be `None`
when a variable is accessed without units (e.g. when accessing
``G.var_``).
"""
__array_priority__ = 10
def __init__(self, name, variable, group, dimensions=None):
self.name = name
self.variable = variable
self.index_var_name = group.variables.indices[name]
if self.index_var_name in ("_idx", "0"):
self.index_var = self.index_var_name
else:
self.index_var = group.variables[self.index_var_name]
if isinstance(variable, Subexpression):
# For subexpressions, we *always* have to go via codegen to get
# their value -- since we cannot do this without the group, we
# hold a strong reference
self.group = group
else:
# For state variable arrays, we can do most access without the full
# group, using the indexing reference below. We therefore only keep
# a weak reference to the group.
self.group = weakproxy_with_fallback(group)
self.group_name = group.name
# We keep a strong reference to the `Indexing` object so that basic
# indexing is still possible, even if the group no longer exists
self.indexing = self.group._indices
self.dim = dimensions
@property
def unit(self):
"""
The `Unit` of this variable
"""
return get_unit(self.dim)
def get_item(self, item, level=0, namespace=None):
"""
Get the value of this variable. Called by `__getitem__`.
Parameters
----------
item : slice, `ndarray` or string
The index for the setting operation
level : int, optional
How much farther to go up in the stack to find the implicit
namespace (if used, see `run_namespace`).
namespace : dict-like, optional
An additional namespace that is used for variable lookup (if not
defined, the implicit namespace of local variables is used).
"""
from brian2.core.namespace import get_local_namespace # avoids circular import
if isinstance(item, str):
# Check whether the group still exists to give a more meaningful
# error message if it does not
try:
self.group.name
except ReferenceError:
raise ReferenceError(
"Cannot use string expressions, the "
f"group '{self.group_name}', providing the "
"context for the expression, no longer exists. "
"Consider holding an explicit reference "
"to it to keep it alive."
)
if namespace is None:
namespace = get_local_namespace(level=level + 1)
values = self.get_with_expression(item, run_namespace=namespace)
else:
if isinstance(self.variable, Subexpression):
if namespace is None:
namespace = get_local_namespace(level=level + 1)
values = self.get_subexpression_with_index_array(
item, run_namespace=namespace
)
else:
values = self.get_with_index_array(item)
if self.dim is DIMENSIONLESS or self.dim is None:
return values
else:
return Quantity(values, self.dim)
def __getitem__(self, item):
return self.get_item(item, level=1)
def set_item(self, item, value, level=0, namespace=None):
"""
Set this variable. This function is called by `__setitem__` but there
is also a situation where it should be called directly: if the context
for string-based expressions is higher up in the stack, this function
allows to set the `level` argument accordingly.
Parameters
----------
item : slice, `ndarray` or string
The index for the setting operation
value : `Quantity`, `ndarray` or number
The value for the setting operation
level : int, optional
How much farther to go up in the stack to find the implicit
namespace (if used, see `run_namespace`).
namespace : dict-like, optional
An additional namespace that is used for variable lookup (if not
defined, the implicit namespace of local variables is used).
"""
from brian2.core.namespace import get_local_namespace # avoids circular import
variable = self.variable
if variable.read_only:
raise TypeError(f"Variable {self.name} is read-only.")
# Check whether the group allows writing to the variable (e.g. for
# synaptic variables, writing is only allowed after a connect)
try:
self.group.check_variable_write(variable)
except ReferenceError:
# Ignore problems with weakly referenced groups that don't exist
# anymore at this time (e.g. when doing neuron.axon.var = ...)
pass
# The second part is equivalent to item == slice(None) but formulating
# it this way prevents a FutureWarning if one of the elements is a
# numpy array
if isinstance(item, slice) and (
item.start is None and item.stop is None and item.step is None
):
item = "True"
check_units = self.dim is not None
if namespace is None:
namespace = get_local_namespace(level=level + 1)
# Both index and values are strings, use a single code object do deal
# with this situation
if isinstance(value, str) and isinstance(item, str):
self.set_with_expression_conditional(
item, value, check_units=check_units, run_namespace=namespace
)
elif isinstance(item, str):
try:
if isinstance(value, str):
raise TypeError # Will be dealt with below
value = np.asanyarray(value).item()
except (TypeError, ValueError):
if item != "True":
raise TypeError(
"When setting a variable based on a string "
"index, the value has to be a string or a "
"scalar."
)
if item == "True":
# We do not want to go through code generation for runtime
self.set_with_index_array(slice(None), value, check_units=check_units)
else:
self.set_with_expression_conditional(
item, repr(value), check_units=check_units, run_namespace=namespace
)
elif isinstance(value, str):
self.set_with_expression(
item, value, check_units=check_units, run_namespace=namespace
)
else: # No string expressions involved
self.set_with_index_array(item, value, check_units=check_units)
def __setitem__(self, item, value):
self.set_item(item, value, level=1)
@device_override("variableview_set_with_expression")
def set_with_expression(self, item, code, run_namespace, check_units=True):
"""
Sets a variable using a string expression. Is called by
`VariableView.set_item` for statements such as
``S.var[:, :] = 'exp(-abs(i-j)/space_constant)*nS'``
Parameters
----------
item : `ndarray`
The indices for the variable (in the context of this `group`).
code : str
The code that should be executed to set the variable values.
Can contain references to indices, such as `i` or `j`
run_namespace : dict-like, optional
An additional namespace that is used for variable lookup (if not
defined, the implicit namespace of local variables is used).
check_units : bool, optional
Whether to check the units of the expression.
run_namespace : dict-like, optional
An additional namespace that is used for variable lookup (if not
defined, the implicit namespace of local variables is used).
"""
# Some fairly complicated code to raise a warning in ambiguous
# situations, when indexing with a group. For example, in:
# group.v[subgroup] = 'i'
# the index 'i' is the index of 'group' ("absolute index") and not of
# subgroup ("relative index")
if hasattr(item, "variables") or (
isinstance(item, tuple)
and any(hasattr(one_item, "variables") for one_item in item)
):
# Determine the variables that are used in the expression
from brian2.codegen.translation import get_identifiers_recursively
identifiers = get_identifiers_recursively([code], self.group.variables)
variables = self.group.resolve_all(
identifiers, run_namespace, user_identifiers=set()
)
if not isinstance(item, tuple):
index_groups = [item]
else:
index_groups = item
for varname, var in variables.items():
for index_group in index_groups:
if not hasattr(index_group, "variables"):
continue
if (
varname in index_group.variables
or var.name in index_group.variables
):
indexed_var = index_group.variables.get(
varname, index_group.variables.get(var.name)
)
if indexed_var is not var:
logger.warn(
"The string expression used for setting "
f"'{self.name}' refers to '{varname}' which "
"might be ambiguous. It will be "
"interpreted as referring to "
f"'{varname}' in '{self.group.name}', not as "
"a variable of a group used for "
"indexing.",
"ambiguous_string_expression",
)
break # no need to warn more than once for a variable
indices = np.atleast_1d(self.indexing(item))
abstract_code = f"{self.name} = {code}"
variables = Variables(self.group)
variables.add_array(
"_group_idx", size=len(indices), dtype=np.int32, values=indices
)
# TODO: Have an additional argument to avoid going through the index
# array for situations where iterate_all could be used
from brian2.codegen.codeobject import create_runner_codeobj
from brian2.devices.device import get_device
device = get_device()
codeobj = create_runner_codeobj(
self.group,
abstract_code,
"group_variable_set",
additional_variables=variables,
check_units=check_units,
run_namespace=run_namespace,
codeobj_class=device.code_object_class(
fallback_pref="codegen.string_expression_target"
),
)
codeobj()
@device_override("variableview_set_with_expression_conditional")
def set_with_expression_conditional(
self, cond, code, run_namespace, check_units=True
):
"""
Sets a variable using a string expression and string condition. Is
called by `VariableView.set_item` for statements such as
``S.var['i!=j'] = 'exp(-abs(i-j)/space_constant)*nS'``
Parameters
----------
cond : str
The string condition for which the variables should be set.
code : str
The code that should be executed to set the variable values.
run_namespace : dict-like, optional
An additional namespace that is used for variable lookup (if not
defined, the implicit namespace of local variables is used).
check_units : bool, optional
Whether to check the units of the expression.
"""
variable = self.variable
if variable.scalar and cond != "True":
raise IndexError(
f"Cannot conditionally set the scalar variable '{self.name}'."
)
abstract_code_cond = f"_cond = {cond}"
abstract_code = f"{self.name} = {code}"
variables = Variables(None)
variables.add_auxiliary_variable("_cond", dtype=bool)
from brian2.codegen.codeobject import create_runner_codeobj
# TODO: Have an additional argument to avoid going through the index
# array for situations where iterate_all could be used
from brian2.devices.device import get_device
device = get_device()
codeobj = create_runner_codeobj(
self.group,
{"condition": abstract_code_cond, "statement": abstract_code},
"group_variable_set_conditional",
additional_variables=variables,
check_units=check_units,
run_namespace=run_namespace,
codeobj_class=device.code_object_class(
fallback_pref="codegen.string_expression_target"
),
)
codeobj()
@device_override("variableview_get_with_expression")
def get_with_expression(self, code, run_namespace):
"""
Gets a variable using a string expression. Is called by
`VariableView.get_item` for statements such as
``print(G.v['g_syn > 0'])``.
Parameters
----------
code : str
An expression that states a condition for elements that should be
selected. Can contain references to indices, such as ``i`` or ``j``
and to state variables. For example: ``'i>3 and v>0*mV'``.
run_namespace : dict-like
An additional namespace that is used for variable lookup (either
an explicitly defined namespace or one taken from the local
context).
"""
variable = self.variable
if variable.scalar:
raise IndexError(
f"Cannot access the variable '{self.name}' with a "
"string expression, it is a scalar variable."
)
# Add the recorded variable under a known name to the variables
# dictionary. Important to deal correctly with
# the type of the variable in C++
variables = Variables(None)
variables.add_auxiliary_variable(
"_variable",
dimensions=variable.dim,
dtype=variable.dtype,
scalar=variable.scalar,
)
variables.add_auxiliary_variable("_cond", dtype=bool)
abstract_code = f"_variable = {self.name}\n"
abstract_code += f"_cond = {code}"
from brian2.codegen.codeobject import create_runner_codeobj
from brian2.devices.device import get_device
device = get_device()
codeobj = create_runner_codeobj(
self.group,
abstract_code,
"group_variable_get_conditional",
additional_variables=variables,
run_namespace=run_namespace,
codeobj_class=device.code_object_class(
fallback_pref="codegen.string_expression_target"
),
)
return codeobj()
@device_override("variableview_get_with_index_array")
def get_with_index_array(self, item):
variable = self.variable
if variable.scalar:
if not (isinstance(item, slice) and item == slice(None)):
raise IndexError(
f"Illegal index for variable '{self.name}', it is a "
"scalar variable."
)
indices = 0
elif (
isinstance(item, slice) and item == slice(None) and self.index_var == "_idx"
):
indices = slice(None)
# Quick fix for matplotlib calling 1-d variables as var[:, np.newaxis]
# The test is a bit verbose, but we need to avoid comparisons that raise errors
# (e.g. comparing an array to slice(None))
elif (
isinstance(item, tuple)
and len(item) == 2
and isinstance(item[0], slice)
and item[0] == slice(None)
and item[1] is None
):
if self.index_var == "_idx":
return variable.get_value()[item]
else:
return variable.get_value()[self.index_var.get_value()][item]
else:
indices = self.indexing(item, self.index_var)
return variable.get_value()[indices]
@device_override("variableview_get_subexpression_with_index_array")
def get_subexpression_with_index_array(self, item, run_namespace):
variable = self.variable
if variable.scalar:
if not (isinstance(item, slice) and item == slice(None)):
raise IndexError(
f"Illegal index for variable '{self.name}', it is a "
"scalar variable."
)
indices = np.array(0)
else:
indices = self.indexing(item, self.index_var)
# For "normal" variables, we can directly access the underlying data
# and use the usual slicing syntax. For subexpressions, however, we
# have to evaluate code for the given indices
variables = Variables(None, default_index="_group_index")
variables.add_auxiliary_variable(
"_variable",
dimensions=variable.dim,
dtype=variable.dtype,
scalar=variable.scalar,
)
if indices.shape == ():
single_index = True
indices = np.array([indices])
else:
single_index = False
variables.add_array("_group_idx", size=len(indices), dtype=np.int32)
variables["_group_idx"].set_value(indices)
# Force the use of this variable as a replacement for the original
# index variable
using_orig_index = [
varname
for varname, index in self.group.variables.indices.items()
if index == self.index_var_name and index != "0"
]
for varname in using_orig_index:
variables.indices[varname] = "_idx"
abstract_code = f"_variable = {self.name}\n"
from brian2.codegen.codeobject import create_runner_codeobj
from brian2.devices.device import get_device
device = get_device()
codeobj = create_runner_codeobj(
self.group,
abstract_code,
"group_variable_get",
# Setting the user code to an empty
# string suppresses warnings if the
# subexpression refers to variable
# names that are also present in the
# local namespace
user_code="",
needed_variables=["_group_idx"],
additional_variables=variables,
run_namespace=run_namespace,
codeobj_class=device.code_object_class(
fallback_pref="codegen.string_expression_target"
),
)
result = codeobj()
if single_index and not variable.scalar:
return result[0]
else:
return result
@device_override("variableview_set_with_index_array")
def set_with_index_array(self, item, value, check_units):
variable = self.variable
if check_units:
fail_for_dimension_mismatch(
variable.dim, value, f"Incorrect unit for setting variable {self.name}"
)
if variable.scalar:
if not (isinstance(item, slice) and item == slice(None)):
raise IndexError(
"Illegal index for variable '{self.name}', it is a scalar variable."
)
indices = 0
elif (
isinstance(item, slice) and item == slice(None) and self.index_var == "_idx"
):
indices = slice(None)
else:
indices = self.indexing(item, self.index_var)
q = Quantity(value)
if len(q.shape):
if not len(q.shape) == 1 or len(q) != 1 and len(q) != len(indices):
raise ValueError(
"Provided values do not match the size "
"of the indices, "
f"{len(q)} != {len(indices)}."
)
variable.get_value()[indices] = value
# Allow some basic calculations directly on the ArrayView object
def __array__(self, dtype=None, copy=None):
try:
# This will fail for subexpressions that refer to external
# parameters
values = self[:]
# Never hand over copy = None
return np.array(values, dtype=dtype, copy=copy is not False, subok=True)
except ValueError:
var = self.variable.name
raise ValueError(
f"Cannot get the values for variable {var}. If it "
"is a subexpression referring to external "
f"variables, use 'group.{var}[:]' instead of "
f"'group.{var}'"
)
def __array__ufunc__(self, ufunc, method, *inputs, **kwargs):
if method == "__call__":
return ufunc(self[:], *inputs, **kwargs)
else:
return NotImplemented
def __len__(self):
return len(self.get_item(slice(None), level=1))
def __neg__(self):
return -self.get_item(slice(None), level=1)
def __pos__(self):
return self.get_item(slice(None), level=1)
def __add__(self, other):
return self.get_item(slice(None), level=1) + np.asanyarray(other)
def __radd__(self, other):
return np.asanyarray(other) + self.get_item(slice(None), level=1)
def __sub__(self, other):
return self.get_item(slice(None), level=1) - np.asanyarray(other)
def __rsub__(self, other):
return np.asanyarray(other) - self.get_item(slice(None), level=1)
def __mul__(self, other):
return self.get_item(slice(None), level=1) * np.asanyarray(other)
def __rmul__(self, other):
return np.asanyarray(other) * self.get_item(slice(None), level=1)
def __div__(self, other):
return self.get_item(slice(None), level=1) / np.asanyarray(other)
def __truediv__(self, other):
return self.get_item(slice(None), level=1) / np.asanyarray(other)
def __floordiv__(self, other):
return self.get_item(slice(None), level=1) // np.asanyarray(other)
def __rdiv__(self, other):
return np.asanyarray(other) / self.get_item(slice(None), level=1)
def __rtruediv__(self, other):
return np.asanyarray(other) / self.get_item(slice(None), level=1)
def __rfloordiv__(self, other):
return np.asanyarray(other) // self.get_item(slice(None), level=1)
def __mod__(self, other):
return self.get_item(slice(None), level=1) % np.asanyarray(other)
def __pow__(self, power, modulo=None):
if modulo is not None:
return self.get_item(slice(None), level=1) ** power % modulo
else:
return self.get_item(slice(None), level=1) ** power
def __rpow__(self, other):
if self.dim is not DIMENSIONLESS:
raise TypeError(
f"Cannot use '{self.name}' as an exponent, it has "
f"dimensions {get_unit_for_display(self.unit)}."
)
return other ** self.get_item(slice(None), level=1)
def __iadd__(self, other):
if isinstance(other, str):
raise TypeError(
"In-place modification with strings not "
"supported. Use group.var = 'var + expression' "
"instead of group.var += 'expression'."
)
elif isinstance(self.variable, Subexpression):
raise TypeError("Cannot assign to a subexpression.")
else:
rhs = self[:] + np.asanyarray(other)
self[:] = rhs
return self
# Support matrix multiplication with @
def __matmul__(self, other):
return self.get_item(slice(None), level=1) @ np.asanyarray(other)
def __rmatmul__(self, other):
return np.asanyarray(other) @ self.get_item(slice(None), level=1)
def __isub__(self, other):
if isinstance(other, str):
raise TypeError(
"In-place modification with strings not "
"supported. Use group.var = 'var - expression' "
"instead of group.var -= 'expression'."
)
elif isinstance(self.variable, Subexpression):
raise TypeError("Cannot assign to a subexpression.")
else:
rhs = self[:] - np.asanyarray(other)
self[:] = rhs
return self
def __imul__(self, other):
if isinstance(other, str):
raise TypeError(
"In-place modification with strings not "
"supported. Use group.var = 'var * expression' "
"instead of group.var *= 'expression'."
)
elif isinstance(self.variable, Subexpression):
raise TypeError("Cannot assign to a subexpression.")
else:
rhs = self[:] * np.asanyarray(other)
self[:] = rhs
return self
def __idiv__(self, other):
if isinstance(other, str):
raise TypeError(
"In-place modification with strings not "
"supported. Use group.var = 'var / expression' "
"instead of group.var /= 'expression'."
)
elif isinstance(self.variable, Subexpression):
raise TypeError("Cannot assign to a subexpression.")
else:
rhs = self[:] / np.asanyarray(other)
self[:] = rhs
return self
def __ifloordiv__(self, other):
if isinstance(other, str):
raise TypeError(
"In-place modification with strings not "
"supported. Use group.var = 'var // expression' "
"instead of group.var //= 'expression'."
)
elif isinstance(self.variable, Subexpression):
raise TypeError("Cannot assign to a subexpression.")
else:
rhs = self[:] // np.asanyarray(other)
self[:] = rhs
return self
def __imod__(self, other):
if isinstance(other, str):
raise TypeError(
"In-place modification with strings not "
"supported. Use group.var = 'var // expression' "
"instead of group.var //= 'expression'."
)
elif isinstance(self.variable, Subexpression):
raise TypeError("Cannot assign to a subexpression.")
else:
rhs = self[:] % np.asanyarray(other)
self[:] = rhs
return self
def __ipow__(self, other):
if isinstance(other, str):
raise TypeError(
"In-place modification with strings not "
"supported. Use group.var = 'var ** expression' "
"instead of group.var **= 'expression'."
)
elif isinstance(self.variable, Subexpression):
raise TypeError("Cannot assign to a subexpression.")
else:
rhs = self[:] ** np.asanyarray(other)
self[:] = rhs
return self
# Also allow logical comparisons
def __eq__(self, other):
return self.get_item(slice(None), level=1) == np.asanyarray(other)
def __ne__(self, other):
return self.get_item(slice(None), level=1) != np.asanyarray(other)
def __lt__(self, other):
return self.get_item(slice(None), level=1) < np.asanyarray(other)
def __le__(self, other):
return self.get_item(slice(None), level=1) <= np.asanyarray(other)
def __gt__(self, other):
return self.get_item(slice(None), level=1) > np.asanyarray(other)
def __ge__(self, other):
return self.get_item(slice(None), level=1) >= np.asanyarray(other)
def __repr__(self):
varname = self.name
if self.dim is None:
varname += "_"
if self.variable.scalar:
dim = self.dim if self.dim is not None else DIMENSIONLESS
values = repr(Quantity(self.variable.get_value().item(), dim=dim))
else:
try:
# This will fail for subexpressions that refer to external
# parameters
values = repr(self[:])
except KeyError:
values = (
"[Subexpression refers to external parameters. Use "
f"'group.{self.variable.name}[:]']"
)
return f"<{self.group_name}.{varname}: {values}>"
def __hash__(self):
return hash((self.group_name, self.name))
# Get access to some basic properties of the underlying array
@property
def shape(self):
if self.ndim == 1:
if not self.variable.scalar:
# This is safer than using the variable size, since it also works for subgroups
# see GitHub issue #1555
size = self.group.stop - self.group.start
assert size <= self.variable.size
else:
size = self.variable.size
return (size,)
else:
return self.variable.size
@property
def ndim(self):
return getattr(self.variable, "ndim", 1)
@property
def dtype(self):
return self.variable.dtype
class Variables(Mapping):
"""
A container class for storing `Variable` objects. Instances of this class
are used as the `Group.variables` attribute and can be accessed as
(read-only) dictionaries.
Parameters
----------
owner : `Nameable`
The object (typically a `Group`) "owning" the variables.
default_index : str, optional
The index to use for the variables (only relevant for `ArrayVariable`
and `DynamicArrayVariable`). Defaults to ``'_idx'``.
"""
def __init__(self, owner, default_index="_idx"):
#: A reference to the `Group` owning these variables
self.owner = weakproxy_with_fallback(owner)
# The index that is used for arrays if no index is given explicitly
self.default_index = default_index
# We do the import here to avoid a circular dependency.
from brian2.devices.device import get_device
self.device = get_device()
self._variables = {}
#: A dictionary given the index name for every array name
self.indices = collections.defaultdict(functools.partial(str, default_index))
# Note that by using functools.partial (instead of e.g. a lambda
# function) above, this object remains pickable.
def __getstate__(self):
state = self.__dict__.copy()
state["owner"] = state["owner"].__repr__.__self__
return state
def __setstate__(self, state):
state["owner"] = weakproxy_with_fallback(state["owner"])
self.__dict__ = state
def __getitem__(self, item):
return self._variables[item]
def __len__(self):
return len(self._variables)
def __iter__(self):
return iter(self._variables)
def _add_variable(self, name, var, index=None):
if name in self._variables:
raise KeyError(
f"The name '{name}' is already present in the variables dictionary."
)
# TODO: do some check for the name, part of it has to be device-specific
self._variables[name] = var
if isinstance(var, ArrayVariable):
# Tell the device to actually create the array (or note it down for
# later code generation in standalone).
self.device.add_array(var)
if getattr(var, "scalar", False):
if index not in (None, "0"):
raise ValueError("Cannot set an index for a scalar variable")
self.indices[name] = "0"
if index is not None:
self.indices[name] = index
def add_array(
self,
name,
size,
dimensions=DIMENSIONLESS,
values=None,
dtype=None,
constant=False,
read_only=False,
scalar=False,
unique=False,
index=None,
):
"""
Add an array (initialized with zeros).
Parameters
----------
name : str
The name of the variable.
dimensions : `Dimension`, optional
The physical dimensions of the variable.
size : int
The size of the array.
values : `ndarray`, optional
The values to initalize the array with. If not specified, the array
is initialized to zero.
dtype : `dtype`, optional
The dtype used for storing the variable. If none is given, defaults
to `core.default_float_dtype`.
constant : bool, optional
Whether the variable's value is constant during a run.
Defaults to ``False``.
scalar : bool, optional
Whether this is a scalar variable. Defaults to ``False``, if set to
``True``, also implies that `size` equals 1.
read_only : bool, optional
Whether this is a read-only variable, i.e. a variable that is set
internally and cannot be changed by the user. Defaults
to ``False``.
index : str, optional
The index to use for this variable. Defaults to
`Variables.default_index`.
unique : bool, optional
See `ArrayVariable`. Defaults to ``False``.
"""
if np.asanyarray(size).shape == ():
# We want a basic Python type for the size instead of something
# like numpy.int64
size = int(size)
var = ArrayVariable(
name=name,
dimensions=dimensions,
owner=self.owner,
device=self.device,
size=size,
dtype=dtype,
constant=constant,
scalar=scalar,
read_only=read_only,
unique=unique,
)
self._add_variable(name, var, index)
# This could be avoided, but we currently need it so that standalone
# allocates the memory
self.device.init_with_zeros(var, dtype)
if values is not None:
if scalar:
if np.asanyarray(values).shape != ():
raise ValueError("Need a scalar value.")
self.device.fill_with_array(var, values)
else:
if len(values) != size:
raise ValueError(
"Size of the provided values does not match "
f"size: {len(values)} != {size}"
)
self.device.fill_with_array(var, values)
def add_arrays(
self,
names,
size,
dimensions=DIMENSIONLESS,
dtype=None,
constant=False,
read_only=False,
scalar=False,
unique=False,
index=None,
):
"""
Adds several arrays (initialized with zeros) with the same attributes
(size, units, etc.).
Parameters
----------
names : list of str
The names of the variable.
dimensions : `Dimension`, optional
The physical dimensions of the variable.
size : int
The sizes of the arrays.
dtype : `dtype`, optional
The dtype used for storing the variables. If none is given, defaults
to `core.default_float_dtype`.
constant : bool, optional
Whether the variables' values are constant during a run.
Defaults to ``False``.
scalar : bool, optional
Whether these are scalar variables. Defaults to ``False``, if set to
``True``, also implies that `size` equals 1.
read_only : bool, optional
Whether these are read-only variables, i.e. variables that are set
internally and cannot be changed by the user. Defaults
to ``False``.
index : str, optional
The index to use for these variables. Defaults to
`Variables.default_index`.
unique : bool, optional
See `ArrayVariable`. Defaults to ``False``.
"""
for name in names:
self.add_array(
name,
dimensions=dimensions,
size=size,
dtype=dtype,
constant=constant,
read_only=read_only,
scalar=scalar,
unique=unique,
index=index,
)
def add_dynamic_array(
self,
name,
size,
dimensions=DIMENSIONLESS,
values=None,
dtype=None,
constant=False,
needs_reference_update=False,
resize_along_first=False,
read_only=False,
unique=False,
scalar=False,
index=None,
):
"""
Add a dynamic array.
Parameters
----------
name : str
The name of the variable.
dimensions : `Dimension`, optional
The physical dimensions of the variable.
size : int or tuple of int
The (initital) size of the array.
values : `ndarray`, optional
The values to initalize the array with. If not specified, the array
is initialized to zero.
dtype : `dtype`, optional
The dtype used for storing the variable. If none is given, defaults
to `core.default_float_dtype`.
constant : bool, optional
Whether the variable's value is constant during a run.
Defaults to ``False``.
needs_reference_update : bool, optional
Whether the code objects need a new reference to the underlying data at
every time step. This should be set if the size of the array can be
changed by other code objects. Defaults to ``False``.
scalar : bool, optional
Whether this is a scalar variable. Defaults to ``False``, if set to
``True``, also implies that `size` equals 1.
read_only : bool, optional
Whether this is a read-only variable, i.e. a variable that is set
internally and cannot be changed by the user. Defaults
to ``False``.
index : str, optional
The index to use for this variable. Defaults to
`Variables.default_index`.
unique : bool, optional
See `DynamicArrayVariable`. Defaults to ``False``.
"""
var = DynamicArrayVariable(
name=name,
dimensions=dimensions,
owner=self.owner,
device=self.device,
size=size,
dtype=dtype,
constant=constant,
needs_reference_update=needs_reference_update,
resize_along_first=resize_along_first,
scalar=scalar,
read_only=read_only,
unique=unique,
)
self._add_variable(name, var, index)
if np.prod(size) > 0:
self.device.resize(var, size)
if values is None and np.prod(size) > 0:
self.device.init_with_zeros(var, dtype)
elif values is not None:
if len(values) != size:
raise ValueError(
"Size of the provided values does not match "
f"size: {len(values)} != {size}"
)
if np.prod(size) > 0:
self.device.fill_with_array(var, values)
def add_arange(
self,
name,
size,
start=0,
dtype=np.int32,
constant=True,
read_only=True,
unique=True,
index=None,
):
"""
Add an array, initialized with a range of integers.
Parameters
----------
name : str
The name of the variable.
size : int
The size of the array.
start : int
The start value of the range.
dtype : `dtype`, optional
The dtype used for storing the variable. If none is given, defaults
to `np.int32`.
constant : bool, optional
Whether the variable's value is constant during a run.
Defaults to ``True``.
read_only : bool, optional
Whether this is a read-only variable, i.e. a variable that is set
internally and cannot be changed by the user. Defaults
to ``True``.
index : str, optional
The index to use for this variable. Defaults to
`Variables.default_index`.
unique : bool, optional
See `ArrayVariable`. Defaults to ``True`` here.
"""
self.add_array(
name=name,
dimensions=DIMENSIONLESS,
size=size,
dtype=dtype,
constant=constant,
read_only=read_only,
unique=unique,
index=index,
)
self.device.init_with_arange(self._variables[name], start, dtype=dtype)
def add_constant(self, name, value, dimensions=DIMENSIONLESS):
"""
Add a scalar constant (e.g. the number of neurons `N`).
Parameters
----------
name : str
The name of the variable
value: reference to the variable value
The value of the constant.
dimensions : `Dimension`, optional
The physical dimensions of the variable. Note that the variable
itself (as referenced by value) should never have units attached.
"""
var = Constant(name=name, dimensions=dimensions, owner=self.owner, value=value)
self._add_variable(name, var)
def add_subexpression(
self, name, expr, dimensions=DIMENSIONLESS, dtype=None, scalar=False, index=None
):
"""
Add a named subexpression.
Parameters
----------
name : str
The name of the subexpression.
dimensions : `Dimension`
The physical dimensions of the subexpression.
expr : str
The subexpression itself.
dtype : `dtype`, optional
The dtype used for the expression. Defaults to
`core.default_float_dtype`.
scalar : bool, optional
Whether this is an expression only referring to scalar variables.
Defaults to ``False``
index : str, optional
The index to use for this variable. Defaults to
`Variables.default_index`.
"""
var = Subexpression(
name=name,
dimensions=dimensions,
expr=expr,
owner=self.owner,
dtype=dtype,
device=self.device,
scalar=scalar,
)
self._add_variable(name, var, index=index)
def add_auxiliary_variable(
self, name, dimensions=DIMENSIONLESS, dtype=None, scalar=False
):
"""
Add an auxiliary variable (most likely one that is added automatically
to abstract code, e.g. ``_cond`` for a threshold condition),
specifying its type and unit for code generation.
Parameters
----------
name : str
The name of the variable
dimensions : `Dimension`
The physical dimensions of the variable.
dtype : `dtype`, optional
The dtype used for storing the variable. If none is given, defaults
to `core.default_float_dtype`.
scalar : bool, optional
Whether the variable is a scalar value (``True``) or vector-valued,
e.g. defined for every neuron (``False``). Defaults to ``False``.
"""
var = AuxiliaryVariable(
name=name, dimensions=dimensions, dtype=dtype, scalar=scalar
)
self._add_variable(name, var)
def add_referred_subexpression(self, name, group, subexpr, index):
identifiers = subexpr.identifiers
substitutions = {}
for identifier in identifiers:
if identifier not in subexpr.owner.variables:
# external variable --> nothing to do
continue
subexpr_var = subexpr.owner.variables[identifier]
if hasattr(subexpr_var, "owner"):
new_name = f"_{name}_{subexpr.owner.name}_{identifier}"
else:
new_name = f"_{name}_{identifier}"
substitutions[identifier] = new_name
subexpr_var_index = group.variables.indices[identifier]
if subexpr_var_index == group.variables.default_index:
subexpr_var_index = index
elif subexpr_var_index == "0":
pass # nothing to do for a shared variable
elif subexpr_var_index == index:
pass # The same index as the main subexpression
elif index != self.default_index:
index_var = self._variables.get(index, None)
if isinstance(index_var, DynamicArrayVariable):
raise TypeError(
f"Cannot link to subexpression '{name}': it refers "
f"to the variable '{identifier}' which is indexed "
f"with the dynamic index '{subexpr_var_index}'."
)
else:
self.add_reference(subexpr_var_index, group)
self.indices[new_name] = subexpr_var_index
if isinstance(subexpr_var, Subexpression):
self.add_referred_subexpression(
new_name, group, subexpr_var, subexpr_var_index
)
else:
self.add_reference(new_name, group, identifier, subexpr_var_index)
new_expr = word_substitute(subexpr.expr, substitutions)
new_subexpr = Subexpression(
name,
self.owner,
new_expr,
dimensions=subexpr.dim,
device=subexpr.device,
dtype=subexpr.dtype,
scalar=subexpr.scalar,
)
self._variables[name] = new_subexpr
def add_reference(self, name, group, varname=None, index=None):
"""
Add a reference to a variable defined somewhere else (possibly under
a different name). This is for example used in `Subgroup` and
`Synapses` to refer to variables in the respective `NeuronGroup`.
Parameters
----------
name : str
The name of the variable (in this group, possibly a different name
from `var.name`).
group : `Group`
The group from which `var` is referenced
varname : str, optional
The variable to refer to. If not given, defaults to `name`.
index : str, optional
The index that should be used for this variable (defaults to
`Variables.default_index`).
"""
if varname is None:
varname = name
if varname not in group.variables:
raise KeyError(f"Group {group.name} does not have a variable {varname}.")
if index is None:
if group.variables[varname].scalar:
index = "0"
else:
index = self.default_index
if (
self.owner is not None
and self.owner.name != group.name
and index in self.owner.variables
):
if (
not self.owner.variables[index].read_only
or isinstance(self.owner.variables[index], DynamicArrayVariable)
) and group.variables.indices[varname] != group.variables.default_index:
raise TypeError(
f"Cannot link variable '{name}' to '{varname}' in "
f"group '{group.name}' -- need to precalculate "
f"direct indices but index {index} can change"
)
# We don't overwrite existing names with references
if name not in self._variables:
var = group.variables[varname]
if isinstance(var, Subexpression):
self.add_referred_subexpression(name, group, var, index)
else:
self._variables[name] = var
self.indices[name] = index
def add_references(self, group, varnames, index=None):
"""
Add all `Variable` objects from a name to `Variable` mapping with the
same name as in the original mapping.
Parameters
----------
group : `Group`
The group from which the `variables` are referenced
varnames : iterable of str
The variables that should be referred to in the current group
index : str, optional
The index to use for all the variables (defaults to
`Variables.default_index`)
"""
for name in varnames:
self.add_reference(name, group, name, index)
def add_object(self, name, obj):
"""
Add an arbitrary Python object. This is only meant for internal use
and therefore only names starting with an underscore are allowed.
Parameters
----------
name : str
The name used for this object (has to start with an underscore).
obj : object
An arbitrary Python object that needs to be accessed directly from
a `CodeObject`.
"""
if not name.startswith("_"):
raise ValueError(
"This method is only meant for internally used "
"objects, the name therefore has to start with "
"an underscore"
)
self._variables[name] = obj
def create_clock_variables(self, clock, prefix=""):
"""
Convenience function to add the ``t`` and ``dt`` attributes of a
`clock`.
Parameters
----------
clock : `Clock`
The clock that should be used for ``t`` and ``dt``.
prefix : str, optional
A prefix for the variable names. Used for example in monitors to
not confuse the dynamic array of recorded times with the current
time in the recorded group.
"""
self.add_reference(f"{prefix}t", clock, "t")
self.add_reference(f"{prefix}dt", clock, "dt")
self.add_reference(f"{prefix}t_in_timesteps", clock, "timestep")
|