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
|
# mypy: ignore-errors
"""A thin pytorch / numpy compat layer.
Things imported from here have numpy-compatible signatures but operate on
pytorch tensors.
"""
# Contents of this module ends up in the main namespace via _funcs.py
# where type annotations are used in conjunction with the @normalizer decorator.
from __future__ import annotations
import builtins
import itertools
import operator
from typing import Optional, Sequence, TYPE_CHECKING
import torch
from . import _dtypes_impl, _util
if TYPE_CHECKING:
from ._normalizations import (
ArrayLike,
ArrayLikeOrScalar,
CastingModes,
DTypeLike,
NDArray,
NotImplementedType,
OutArray,
)
def copy(
a: ArrayLike, order: NotImplementedType = "K", subok: NotImplementedType = False
):
return a.clone()
def copyto(
dst: NDArray,
src: ArrayLike,
casting: Optional[CastingModes] = "same_kind",
where: NotImplementedType = None,
):
(src,) = _util.typecast_tensors((src,), dst.dtype, casting=casting)
dst.copy_(src)
def atleast_1d(*arys: ArrayLike):
res = torch.atleast_1d(*arys)
if isinstance(res, tuple):
return list(res)
else:
return res
def atleast_2d(*arys: ArrayLike):
res = torch.atleast_2d(*arys)
if isinstance(res, tuple):
return list(res)
else:
return res
def atleast_3d(*arys: ArrayLike):
res = torch.atleast_3d(*arys)
if isinstance(res, tuple):
return list(res)
else:
return res
def _concat_check(tup, dtype, out):
if tup == ():
raise ValueError("need at least one array to concatenate")
"""Check inputs in concatenate et al."""
if out is not None and dtype is not None:
# mimic numpy
raise TypeError(
"concatenate() only takes `out` or `dtype` as an "
"argument, but both were provided."
)
def _concat_cast_helper(tensors, out=None, dtype=None, casting="same_kind"):
"""Figure out dtypes, cast if necessary."""
if out is not None or dtype is not None:
# figure out the type of the inputs and outputs
out_dtype = out.dtype.torch_dtype if dtype is None else dtype
else:
out_dtype = _dtypes_impl.result_type_impl(*tensors)
# cast input arrays if necessary; do not broadcast them agains `out`
tensors = _util.typecast_tensors(tensors, out_dtype, casting)
return tensors
def _concatenate(
tensors, axis=0, out=None, dtype=None, casting: Optional[CastingModes] = "same_kind"
):
# pure torch implementation, used below and in cov/corrcoef below
tensors, axis = _util.axis_none_flatten(*tensors, axis=axis)
tensors = _concat_cast_helper(tensors, out, dtype, casting)
return torch.cat(tensors, axis)
def concatenate(
ar_tuple: Sequence[ArrayLike],
axis=0,
out: Optional[OutArray] = None,
dtype: Optional[DTypeLike] = None,
casting: Optional[CastingModes] = "same_kind",
):
_concat_check(ar_tuple, dtype, out=out)
result = _concatenate(ar_tuple, axis=axis, out=out, dtype=dtype, casting=casting)
return result
def vstack(
tup: Sequence[ArrayLike],
*,
dtype: Optional[DTypeLike] = None,
casting: Optional[CastingModes] = "same_kind",
):
_concat_check(tup, dtype, out=None)
tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting)
return torch.vstack(tensors)
row_stack = vstack
def hstack(
tup: Sequence[ArrayLike],
*,
dtype: Optional[DTypeLike] = None,
casting: Optional[CastingModes] = "same_kind",
):
_concat_check(tup, dtype, out=None)
tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting)
return torch.hstack(tensors)
def dstack(
tup: Sequence[ArrayLike],
*,
dtype: Optional[DTypeLike] = None,
casting: Optional[CastingModes] = "same_kind",
):
# XXX: in numpy 1.24 dstack does not have dtype and casting keywords
# but {h,v}stack do. Hence add them here for consistency.
_concat_check(tup, dtype, out=None)
tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting)
return torch.dstack(tensors)
def column_stack(
tup: Sequence[ArrayLike],
*,
dtype: Optional[DTypeLike] = None,
casting: Optional[CastingModes] = "same_kind",
):
# XXX: in numpy 1.24 column_stack does not have dtype and casting keywords
# but row_stack does. (because row_stack is an alias for vstack, really).
# Hence add these keywords here for consistency.
_concat_check(tup, dtype, out=None)
tensors = _concat_cast_helper(tup, dtype=dtype, casting=casting)
return torch.column_stack(tensors)
def stack(
arrays: Sequence[ArrayLike],
axis=0,
out: Optional[OutArray] = None,
*,
dtype: Optional[DTypeLike] = None,
casting: Optional[CastingModes] = "same_kind",
):
_concat_check(arrays, dtype, out=out)
tensors = _concat_cast_helper(arrays, dtype=dtype, casting=casting)
result_ndim = tensors[0].ndim + 1
axis = _util.normalize_axis_index(axis, result_ndim)
return torch.stack(tensors, axis=axis)
def append(arr: ArrayLike, values: ArrayLike, axis=None):
if axis is None:
if arr.ndim != 1:
arr = arr.flatten()
values = values.flatten()
axis = arr.ndim - 1
return _concatenate((arr, values), axis=axis)
# ### split ###
def _split_helper(tensor, indices_or_sections, axis, strict=False):
if isinstance(indices_or_sections, int):
return _split_helper_int(tensor, indices_or_sections, axis, strict)
elif isinstance(indices_or_sections, (list, tuple)):
# NB: drop split=..., it only applies to split_helper_int
return _split_helper_list(tensor, list(indices_or_sections), axis)
else:
raise TypeError("split_helper: ", type(indices_or_sections))
def _split_helper_int(tensor, indices_or_sections, axis, strict=False):
if not isinstance(indices_or_sections, int):
raise NotImplementedError("split: indices_or_sections")
axis = _util.normalize_axis_index(axis, tensor.ndim)
# numpy: l%n chunks of size (l//n + 1), the rest are sized l//n
l, n = tensor.shape[axis], indices_or_sections
if n <= 0:
raise ValueError
if l % n == 0:
num, sz = n, l // n
lst = [sz] * num
else:
if strict:
raise ValueError("array split does not result in an equal division")
num, sz = l % n, l // n + 1
lst = [sz] * num
lst += [sz - 1] * (n - num)
return torch.split(tensor, lst, axis)
def _split_helper_list(tensor, indices_or_sections, axis):
if not isinstance(indices_or_sections, list):
raise NotImplementedError("split: indices_or_sections: list")
# numpy expects indices, while torch expects lengths of sections
# also, numpy appends zero-size arrays for indices above the shape[axis]
lst = [x for x in indices_or_sections if x <= tensor.shape[axis]]
num_extra = len(indices_or_sections) - len(lst)
lst.append(tensor.shape[axis])
lst = [
lst[0],
] + [a - b for a, b in zip(lst[1:], lst[:-1])]
lst += [0] * num_extra
return torch.split(tensor, lst, axis)
def array_split(ary: ArrayLike, indices_or_sections, axis=0):
return _split_helper(ary, indices_or_sections, axis)
def split(ary: ArrayLike, indices_or_sections, axis=0):
return _split_helper(ary, indices_or_sections, axis, strict=True)
def hsplit(ary: ArrayLike, indices_or_sections):
if ary.ndim == 0:
raise ValueError("hsplit only works on arrays of 1 or more dimensions")
axis = 1 if ary.ndim > 1 else 0
return _split_helper(ary, indices_or_sections, axis, strict=True)
def vsplit(ary: ArrayLike, indices_or_sections):
if ary.ndim < 2:
raise ValueError("vsplit only works on arrays of 2 or more dimensions")
return _split_helper(ary, indices_or_sections, 0, strict=True)
def dsplit(ary: ArrayLike, indices_or_sections):
if ary.ndim < 3:
raise ValueError("dsplit only works on arrays of 3 or more dimensions")
return _split_helper(ary, indices_or_sections, 2, strict=True)
def kron(a: ArrayLike, b: ArrayLike):
return torch.kron(a, b)
def vander(x: ArrayLike, N=None, increasing=False):
return torch.vander(x, N, increasing)
# ### linspace, geomspace, logspace and arange ###
def linspace(
start: ArrayLike,
stop: ArrayLike,
num=50,
endpoint=True,
retstep=False,
dtype: Optional[DTypeLike] = None,
axis=0,
):
if axis != 0 or retstep or not endpoint:
raise NotImplementedError
if dtype is None:
dtype = _dtypes_impl.default_dtypes().float_dtype
# XXX: raises TypeError if start or stop are not scalars
return torch.linspace(start, stop, num, dtype=dtype)
def geomspace(
start: ArrayLike,
stop: ArrayLike,
num=50,
endpoint=True,
dtype: Optional[DTypeLike] = None,
axis=0,
):
if axis != 0 or not endpoint:
raise NotImplementedError
base = torch.pow(stop / start, 1.0 / (num - 1))
logbase = torch.log(base)
return torch.logspace(
torch.log(start) / logbase,
torch.log(stop) / logbase,
num,
base=base,
)
def logspace(
start,
stop,
num=50,
endpoint=True,
base=10.0,
dtype: Optional[DTypeLike] = None,
axis=0,
):
if axis != 0 or not endpoint:
raise NotImplementedError
return torch.logspace(start, stop, num, base=base, dtype=dtype)
def arange(
start: Optional[ArrayLikeOrScalar] = None,
stop: Optional[ArrayLikeOrScalar] = None,
step: Optional[ArrayLikeOrScalar] = 1,
dtype: Optional[DTypeLike] = None,
*,
like: NotImplementedType = None,
):
if step == 0:
raise ZeroDivisionError
if stop is None and start is None:
raise TypeError
if stop is None:
# XXX: this breaks if start is passed as a kwarg:
# arange(start=4) should raise (no stop) but doesn't
start, stop = 0, start
if start is None:
start = 0
# the dtype of the result
if dtype is None:
dtype = (
_dtypes_impl.default_dtypes().float_dtype
if any(_dtypes_impl.is_float_or_fp_tensor(x) for x in (start, stop, step))
else _dtypes_impl.default_dtypes().int_dtype
)
work_dtype = torch.float64 if dtype.is_complex else dtype
# RuntimeError: "lt_cpu" not implemented for 'ComplexFloat'. Fall back to eager.
if any(_dtypes_impl.is_complex_or_complex_tensor(x) for x in (start, stop, step)):
raise NotImplementedError
if (step > 0 and start > stop) or (step < 0 and start < stop):
# empty range
return torch.empty(0, dtype=dtype)
result = torch.arange(start, stop, step, dtype=work_dtype)
result = _util.cast_if_needed(result, dtype)
return result
# ### zeros/ones/empty/full ###
def empty(
shape,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "C",
*,
like: NotImplementedType = None,
):
if dtype is None:
dtype = _dtypes_impl.default_dtypes().float_dtype
return torch.empty(shape, dtype=dtype)
# NB: *_like functions deliberately deviate from numpy: it has subok=True
# as the default; we set subok=False and raise on anything else.
def empty_like(
prototype: ArrayLike,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "K",
subok: NotImplementedType = False,
shape=None,
):
result = torch.empty_like(prototype, dtype=dtype)
if shape is not None:
result = result.reshape(shape)
return result
def full(
shape,
fill_value: ArrayLike,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "C",
*,
like: NotImplementedType = None,
):
if isinstance(shape, int):
shape = (shape,)
if dtype is None:
dtype = fill_value.dtype
if not isinstance(shape, (tuple, list)):
shape = (shape,)
return torch.full(shape, fill_value, dtype=dtype)
def full_like(
a: ArrayLike,
fill_value,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "K",
subok: NotImplementedType = False,
shape=None,
):
# XXX: fill_value broadcasts
result = torch.full_like(a, fill_value, dtype=dtype)
if shape is not None:
result = result.reshape(shape)
return result
def ones(
shape,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "C",
*,
like: NotImplementedType = None,
):
if dtype is None:
dtype = _dtypes_impl.default_dtypes().float_dtype
return torch.ones(shape, dtype=dtype)
def ones_like(
a: ArrayLike,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "K",
subok: NotImplementedType = False,
shape=None,
):
result = torch.ones_like(a, dtype=dtype)
if shape is not None:
result = result.reshape(shape)
return result
def zeros(
shape,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "C",
*,
like: NotImplementedType = None,
):
if dtype is None:
dtype = _dtypes_impl.default_dtypes().float_dtype
return torch.zeros(shape, dtype=dtype)
def zeros_like(
a: ArrayLike,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "K",
subok: NotImplementedType = False,
shape=None,
):
result = torch.zeros_like(a, dtype=dtype)
if shape is not None:
result = result.reshape(shape)
return result
# ### cov & corrcoef ###
def _xy_helper_corrcoef(x_tensor, y_tensor=None, rowvar=True):
"""Prepare inputs for cov and corrcoef."""
# https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/function_base.py#L2636
if y_tensor is not None:
# make sure x and y are at least 2D
ndim_extra = 2 - x_tensor.ndim
if ndim_extra > 0:
x_tensor = x_tensor.view((1,) * ndim_extra + x_tensor.shape)
if not rowvar and x_tensor.shape[0] != 1:
x_tensor = x_tensor.mT
x_tensor = x_tensor.clone()
ndim_extra = 2 - y_tensor.ndim
if ndim_extra > 0:
y_tensor = y_tensor.view((1,) * ndim_extra + y_tensor.shape)
if not rowvar and y_tensor.shape[0] != 1:
y_tensor = y_tensor.mT
y_tensor = y_tensor.clone()
x_tensor = _concatenate((x_tensor, y_tensor), axis=0)
return x_tensor
def corrcoef(
x: ArrayLike,
y: Optional[ArrayLike] = None,
rowvar=True,
bias=None,
ddof=None,
*,
dtype: Optional[DTypeLike] = None,
):
if bias is not None or ddof is not None:
# deprecated in NumPy
raise NotImplementedError
xy_tensor = _xy_helper_corrcoef(x, y, rowvar)
is_half = (xy_tensor.dtype == torch.float16) and xy_tensor.is_cpu
if is_half:
# work around torch's "addmm_impl_cpu_" not implemented for 'Half'"
dtype = torch.float32
xy_tensor = _util.cast_if_needed(xy_tensor, dtype)
result = torch.corrcoef(xy_tensor)
if is_half:
result = result.to(torch.float16)
return result
def cov(
m: ArrayLike,
y: Optional[ArrayLike] = None,
rowvar=True,
bias=False,
ddof=None,
fweights: Optional[ArrayLike] = None,
aweights: Optional[ArrayLike] = None,
*,
dtype: Optional[DTypeLike] = None,
):
m = _xy_helper_corrcoef(m, y, rowvar)
if ddof is None:
ddof = 1 if bias == 0 else 0
is_half = (m.dtype == torch.float16) and m.is_cpu
if is_half:
# work around torch's "addmm_impl_cpu_" not implemented for 'Half'"
dtype = torch.float32
m = _util.cast_if_needed(m, dtype)
result = torch.cov(m, correction=ddof, aweights=aweights, fweights=fweights)
if is_half:
result = result.to(torch.float16)
return result
def _conv_corr_impl(a, v, mode):
dt = _dtypes_impl.result_type_impl(a, v)
a = _util.cast_if_needed(a, dt)
v = _util.cast_if_needed(v, dt)
padding = v.shape[0] - 1 if mode == "full" else mode
if padding == "same" and v.shape[0] % 2 == 0:
# UserWarning: Using padding='same' with even kernel lengths and odd
# dilation may require a zero-padded copy of the input be created
# (Triggered internally at pytorch/aten/src/ATen/native/Convolution.cpp:1010.)
raise NotImplementedError("mode='same' and even-length weights")
# NumPy only accepts 1D arrays; PyTorch requires 2D inputs and 3D weights
aa = a[None, :]
vv = v[None, None, :]
result = torch.nn.functional.conv1d(aa, vv, padding=padding)
# torch returns a 2D result, numpy returns a 1D array
return result[0, :]
def convolve(a: ArrayLike, v: ArrayLike, mode="full"):
# NumPy: if v is longer than a, the arrays are swapped before computation
if a.shape[0] < v.shape[0]:
a, v = v, a
# flip the weights since numpy does and torch does not
v = torch.flip(v, (0,))
return _conv_corr_impl(a, v, mode)
def correlate(a: ArrayLike, v: ArrayLike, mode="valid"):
v = torch.conj_physical(v)
return _conv_corr_impl(a, v, mode)
# ### logic & element selection ###
def bincount(x: ArrayLike, /, weights: Optional[ArrayLike] = None, minlength=0):
if x.numel() == 0:
# edge case allowed by numpy
x = x.new_empty(0, dtype=int)
int_dtype = _dtypes_impl.default_dtypes().int_dtype
(x,) = _util.typecast_tensors((x,), int_dtype, casting="safe")
return torch.bincount(x, weights, minlength)
def where(
condition: ArrayLike,
x: Optional[ArrayLikeOrScalar] = None,
y: Optional[ArrayLikeOrScalar] = None,
/,
):
if (x is None) != (y is None):
raise ValueError("either both or neither of x and y should be given")
if condition.dtype != torch.bool:
condition = condition.to(torch.bool)
if x is None and y is None:
result = torch.where(condition)
else:
result = torch.where(condition, x, y)
return result
# ###### module-level queries of object properties
def ndim(a: ArrayLike):
return a.ndim
def shape(a: ArrayLike):
return tuple(a.shape)
def size(a: ArrayLike, axis=None):
if axis is None:
return a.numel()
else:
return a.shape[axis]
# ###### shape manipulations and indexing
def expand_dims(a: ArrayLike, axis):
shape = _util.expand_shape(a.shape, axis)
return a.view(shape) # never copies
def flip(m: ArrayLike, axis=None):
# XXX: semantic difference: np.flip returns a view, torch.flip copies
if axis is None:
axis = tuple(range(m.ndim))
else:
axis = _util.normalize_axis_tuple(axis, m.ndim)
return torch.flip(m, axis)
def flipud(m: ArrayLike):
return torch.flipud(m)
def fliplr(m: ArrayLike):
return torch.fliplr(m)
def rot90(m: ArrayLike, k=1, axes=(0, 1)):
axes = _util.normalize_axis_tuple(axes, m.ndim)
return torch.rot90(m, k, axes)
# ### broadcasting and indices ###
def broadcast_to(array: ArrayLike, shape, subok: NotImplementedType = False):
return torch.broadcast_to(array, size=shape)
# This is a function from tuples to tuples, so we just reuse it
from torch import broadcast_shapes
def broadcast_arrays(*args: ArrayLike, subok: NotImplementedType = False):
return torch.broadcast_tensors(*args)
def meshgrid(*xi: ArrayLike, copy=True, sparse=False, indexing="xy"):
ndim = len(xi)
if indexing not in ["xy", "ij"]:
raise ValueError("Valid values for `indexing` are 'xy' and 'ij'.")
s0 = (1,) * ndim
output = [x.reshape(s0[:i] + (-1,) + s0[i + 1 :]) for i, x in enumerate(xi)]
if indexing == "xy" and ndim > 1:
# switch first and second axis
output[0] = output[0].reshape((1, -1) + s0[2:])
output[1] = output[1].reshape((-1, 1) + s0[2:])
if not sparse:
# Return the full N-D matrix (not only the 1-D vector)
output = torch.broadcast_tensors(*output)
if copy:
output = [x.clone() for x in output]
return list(output) # match numpy, return a list
def indices(dimensions, dtype: Optional[DTypeLike] = int, sparse=False):
# https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numeric.py#L1691-L1791
dimensions = tuple(dimensions)
N = len(dimensions)
shape = (1,) * N
if sparse:
res = ()
else:
res = torch.empty((N,) + dimensions, dtype=dtype)
for i, dim in enumerate(dimensions):
idx = torch.arange(dim, dtype=dtype).reshape(
shape[:i] + (dim,) + shape[i + 1 :]
)
if sparse:
res = res + (idx,)
else:
res[i] = idx
return res
# ### tri*-something ###
def tril(m: ArrayLike, k=0):
return torch.tril(m, k)
def triu(m: ArrayLike, k=0):
return torch.triu(m, k)
def tril_indices(n, k=0, m=None):
if m is None:
m = n
return torch.tril_indices(n, m, offset=k)
def triu_indices(n, k=0, m=None):
if m is None:
m = n
return torch.triu_indices(n, m, offset=k)
def tril_indices_from(arr: ArrayLike, k=0):
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
# Return a tensor rather than a tuple to avoid a graphbreak
return torch.tril_indices(arr.shape[0], arr.shape[1], offset=k)
def triu_indices_from(arr: ArrayLike, k=0):
if arr.ndim != 2:
raise ValueError("input array must be 2-d")
# Return a tensor rather than a tuple to avoid a graphbreak
return torch.triu_indices(arr.shape[0], arr.shape[1], offset=k)
def tri(
N,
M=None,
k=0,
dtype: Optional[DTypeLike] = None,
*,
like: NotImplementedType = None,
):
if M is None:
M = N
tensor = torch.ones((N, M), dtype=dtype)
return torch.tril(tensor, diagonal=k)
# ### equality, equivalence, allclose ###
def isclose(a: ArrayLike, b: ArrayLike, rtol=1.0e-5, atol=1.0e-8, equal_nan=False):
dtype = _dtypes_impl.result_type_impl(a, b)
a = _util.cast_if_needed(a, dtype)
b = _util.cast_if_needed(b, dtype)
return torch.isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
def allclose(a: ArrayLike, b: ArrayLike, rtol=1e-05, atol=1e-08, equal_nan=False):
dtype = _dtypes_impl.result_type_impl(a, b)
a = _util.cast_if_needed(a, dtype)
b = _util.cast_if_needed(b, dtype)
return torch.allclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan)
def _tensor_equal(a1, a2, equal_nan=False):
# Implementation of array_equal/array_equiv.
if a1.shape != a2.shape:
return False
cond = a1 == a2
if equal_nan:
cond = cond | (torch.isnan(a1) & torch.isnan(a2))
return cond.all().item()
def array_equal(a1: ArrayLike, a2: ArrayLike, equal_nan=False):
return _tensor_equal(a1, a2, equal_nan=equal_nan)
def array_equiv(a1: ArrayLike, a2: ArrayLike):
# *almost* the same as array_equal: _equiv tries to broadcast, _equal does not
try:
a1_t, a2_t = torch.broadcast_tensors(a1, a2)
except RuntimeError:
# failed to broadcast => not equivalent
return False
return _tensor_equal(a1_t, a2_t)
def nan_to_num(
x: ArrayLike, copy: NotImplementedType = True, nan=0.0, posinf=None, neginf=None
):
# work around RuntimeError: "nan_to_num" not implemented for 'ComplexDouble'
if x.is_complex():
re = torch.nan_to_num(x.real, nan=nan, posinf=posinf, neginf=neginf)
im = torch.nan_to_num(x.imag, nan=nan, posinf=posinf, neginf=neginf)
return re + 1j * im
else:
return torch.nan_to_num(x, nan=nan, posinf=posinf, neginf=neginf)
# ### put/take_along_axis ###
def take(
a: ArrayLike,
indices: ArrayLike,
axis=None,
out: Optional[OutArray] = None,
mode: NotImplementedType = "raise",
):
(a,), axis = _util.axis_none_flatten(a, axis=axis)
axis = _util.normalize_axis_index(axis, a.ndim)
idx = (slice(None),) * axis + (indices, ...)
result = a[idx]
return result
def take_along_axis(arr: ArrayLike, indices: ArrayLike, axis):
(arr,), axis = _util.axis_none_flatten(arr, axis=axis)
axis = _util.normalize_axis_index(axis, arr.ndim)
return torch.take_along_dim(arr, indices, axis)
def put(
a: NDArray,
indices: ArrayLike,
values: ArrayLike,
mode: NotImplementedType = "raise",
):
v = values.type(a.dtype)
# If indices is larger than v, expand v to at least the size of indices. Any
# unnecessary trailing elements are then trimmed.
if indices.numel() > v.numel():
ratio = (indices.numel() + v.numel() - 1) // v.numel()
v = v.unsqueeze(0).expand((ratio,) + v.shape)
# Trim unnecessary elements, regardless if v was expanded or not. Note
# np.put() trims v to match indices by default too.
if indices.numel() < v.numel():
v = v.flatten()
v = v[: indices.numel()]
a.put_(indices, v)
return None
def put_along_axis(arr: ArrayLike, indices: ArrayLike, values: ArrayLike, axis):
(arr,), axis = _util.axis_none_flatten(arr, axis=axis)
axis = _util.normalize_axis_index(axis, arr.ndim)
indices, values = torch.broadcast_tensors(indices, values)
values = _util.cast_if_needed(values, arr.dtype)
result = torch.scatter(arr, axis, indices, values)
arr.copy_(result.reshape(arr.shape))
return None
def choose(
a: ArrayLike,
choices: Sequence[ArrayLike],
out: Optional[OutArray] = None,
mode: NotImplementedType = "raise",
):
# First, broadcast elements of `choices`
choices = torch.stack(torch.broadcast_tensors(*choices))
# Use an analog of `gather(choices, 0, a)` which broadcasts `choices` vs `a`:
# (taken from https://github.com/pytorch/pytorch/issues/9407#issuecomment-1427907939)
idx_list = [
torch.arange(dim).view((1,) * i + (dim,) + (1,) * (choices.ndim - i - 1))
for i, dim in enumerate(choices.shape)
]
idx_list[0] = a
return choices[idx_list].squeeze(0)
# ### unique et al. ###
def unique(
ar: ArrayLike,
return_index: NotImplementedType = False,
return_inverse=False,
return_counts=False,
axis=None,
*,
equal_nan: NotImplementedType = True,
):
(ar,), axis = _util.axis_none_flatten(ar, axis=axis)
axis = _util.normalize_axis_index(axis, ar.ndim)
result = torch.unique(
ar, return_inverse=return_inverse, return_counts=return_counts, dim=axis
)
return result
def nonzero(a: ArrayLike):
return torch.nonzero(a, as_tuple=True)
def argwhere(a: ArrayLike):
return torch.argwhere(a)
def flatnonzero(a: ArrayLike):
return torch.flatten(a).nonzero(as_tuple=True)[0]
def clip(
a: ArrayLike,
min: Optional[ArrayLike] = None,
max: Optional[ArrayLike] = None,
out: Optional[OutArray] = None,
):
return torch.clamp(a, min, max)
def repeat(a: ArrayLike, repeats: ArrayLikeOrScalar, axis=None):
return torch.repeat_interleave(a, repeats, axis)
def tile(A: ArrayLike, reps):
if isinstance(reps, int):
reps = (reps,)
return torch.tile(A, reps)
def resize(a: ArrayLike, new_shape=None):
# implementation vendored from
# https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/fromnumeric.py#L1420-L1497
if new_shape is None:
return a
if isinstance(new_shape, int):
new_shape = (new_shape,)
a = a.flatten()
new_size = 1
for dim_length in new_shape:
new_size *= dim_length
if dim_length < 0:
raise ValueError("all elements of `new_shape` must be non-negative")
if a.numel() == 0 or new_size == 0:
# First case must zero fill. The second would have repeats == 0.
return torch.zeros(new_shape, dtype=a.dtype)
repeats = -(-new_size // a.numel()) # ceil division
a = concatenate((a,) * repeats)[:new_size]
return reshape(a, new_shape)
# ### diag et al. ###
def diagonal(a: ArrayLike, offset=0, axis1=0, axis2=1):
axis1 = _util.normalize_axis_index(axis1, a.ndim)
axis2 = _util.normalize_axis_index(axis2, a.ndim)
return torch.diagonal(a, offset, axis1, axis2)
def trace(
a: ArrayLike,
offset=0,
axis1=0,
axis2=1,
dtype: Optional[DTypeLike] = None,
out: Optional[OutArray] = None,
):
result = torch.diagonal(a, offset, dim1=axis1, dim2=axis2).sum(-1, dtype=dtype)
return result
def eye(
N,
M=None,
k=0,
dtype: Optional[DTypeLike] = None,
order: NotImplementedType = "C",
*,
like: NotImplementedType = None,
):
if dtype is None:
dtype = _dtypes_impl.default_dtypes().float_dtype
if M is None:
M = N
z = torch.zeros(N, M, dtype=dtype)
z.diagonal(k).fill_(1)
return z
def identity(n, dtype: Optional[DTypeLike] = None, *, like: NotImplementedType = None):
return torch.eye(n, dtype=dtype)
def diag(v: ArrayLike, k=0):
return torch.diag(v, k)
def diagflat(v: ArrayLike, k=0):
return torch.diagflat(v, k)
def diag_indices(n, ndim=2):
idx = torch.arange(n)
return (idx,) * ndim
def diag_indices_from(arr: ArrayLike):
if not arr.ndim >= 2:
raise ValueError("input array must be at least 2-d")
# For more than d=2, the strided formula is only valid for arrays with
# all dimensions equal, so we check first.
s = arr.shape
if s[1:] != s[:-1]:
raise ValueError("All dimensions of input must be of equal length")
return diag_indices(s[0], arr.ndim)
def fill_diagonal(a: ArrayLike, val: ArrayLike, wrap=False):
if a.ndim < 2:
raise ValueError("array must be at least 2-d")
if val.numel() == 0 and not wrap:
a.fill_diagonal_(val)
return a
if val.ndim == 0:
val = val.unsqueeze(0)
# torch.Tensor.fill_diagonal_ only accepts scalars
# If the size of val is too large, then val is trimmed
if a.ndim == 2:
tall = a.shape[0] > a.shape[1]
# wrap does nothing for wide matrices...
if not wrap or not tall:
# Never wraps
diag = a.diagonal()
diag.copy_(val[: diag.numel()])
else:
# wraps and tall... leaving one empty line between diagonals?!
max_, min_ = a.shape
idx = torch.arange(max_ - max_ // (min_ + 1))
mod = idx % min_
div = idx // min_
a[(div * (min_ + 1) + mod, mod)] = val[: idx.numel()]
else:
idx = diag_indices_from(a)
# a.shape = (n, n, ..., n)
a[idx] = val[: a.shape[0]]
return a
def vdot(a: ArrayLike, b: ArrayLike, /):
# 1. torch only accepts 1D arrays, numpy flattens
# 2. torch requires matching dtype, while numpy casts (?)
t_a, t_b = torch.atleast_1d(a, b)
if t_a.ndim > 1:
t_a = t_a.flatten()
if t_b.ndim > 1:
t_b = t_b.flatten()
dtype = _dtypes_impl.result_type_impl(t_a, t_b)
is_half = dtype == torch.float16 and (t_a.is_cpu or t_b.is_cpu)
is_bool = dtype == torch.bool
# work around torch's "dot" not implemented for 'Half', 'Bool'
if is_half:
dtype = torch.float32
elif is_bool:
dtype = torch.uint8
t_a = _util.cast_if_needed(t_a, dtype)
t_b = _util.cast_if_needed(t_b, dtype)
result = torch.vdot(t_a, t_b)
if is_half:
result = result.to(torch.float16)
elif is_bool:
result = result.to(torch.bool)
return result
def tensordot(a: ArrayLike, b: ArrayLike, axes=2):
if isinstance(axes, (list, tuple)):
axes = [[ax] if isinstance(ax, int) else ax for ax in axes]
target_dtype = _dtypes_impl.result_type_impl(a, b)
a = _util.cast_if_needed(a, target_dtype)
b = _util.cast_if_needed(b, target_dtype)
return torch.tensordot(a, b, dims=axes)
def dot(a: ArrayLike, b: ArrayLike, out: Optional[OutArray] = None):
dtype = _dtypes_impl.result_type_impl(a, b)
is_bool = dtype == torch.bool
if is_bool:
dtype = torch.uint8
a = _util.cast_if_needed(a, dtype)
b = _util.cast_if_needed(b, dtype)
if a.ndim == 0 or b.ndim == 0:
result = a * b
else:
result = torch.matmul(a, b)
if is_bool:
result = result.to(torch.bool)
return result
def inner(a: ArrayLike, b: ArrayLike, /):
dtype = _dtypes_impl.result_type_impl(a, b)
is_half = dtype == torch.float16 and (a.is_cpu or b.is_cpu)
is_bool = dtype == torch.bool
if is_half:
# work around torch's "addmm_impl_cpu_" not implemented for 'Half'"
dtype = torch.float32
elif is_bool:
dtype = torch.uint8
a = _util.cast_if_needed(a, dtype)
b = _util.cast_if_needed(b, dtype)
result = torch.inner(a, b)
if is_half:
result = result.to(torch.float16)
elif is_bool:
result = result.to(torch.bool)
return result
def outer(a: ArrayLike, b: ArrayLike, out: Optional[OutArray] = None):
return torch.outer(a, b)
def cross(a: ArrayLike, b: ArrayLike, axisa=-1, axisb=-1, axisc=-1, axis=None):
# implementation vendored from
# https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numeric.py#L1486-L1685
if axis is not None:
axisa, axisb, axisc = (axis,) * 3
# Check axisa and axisb are within bounds
axisa = _util.normalize_axis_index(axisa, a.ndim)
axisb = _util.normalize_axis_index(axisb, b.ndim)
# Move working axis to the end of the shape
a = torch.moveaxis(a, axisa, -1)
b = torch.moveaxis(b, axisb, -1)
msg = "incompatible dimensions for cross product\n(dimension must be 2 or 3)"
if a.shape[-1] not in (2, 3) or b.shape[-1] not in (2, 3):
raise ValueError(msg)
# Create the output array
shape = broadcast_shapes(a[..., 0].shape, b[..., 0].shape)
if a.shape[-1] == 3 or b.shape[-1] == 3:
shape += (3,)
# Check axisc is within bounds
axisc = _util.normalize_axis_index(axisc, len(shape))
dtype = _dtypes_impl.result_type_impl(a, b)
cp = torch.empty(shape, dtype=dtype)
# recast arrays as dtype
a = _util.cast_if_needed(a, dtype)
b = _util.cast_if_needed(b, dtype)
# create local aliases for readability
a0 = a[..., 0]
a1 = a[..., 1]
if a.shape[-1] == 3:
a2 = a[..., 2]
b0 = b[..., 0]
b1 = b[..., 1]
if b.shape[-1] == 3:
b2 = b[..., 2]
if cp.ndim != 0 and cp.shape[-1] == 3:
cp0 = cp[..., 0]
cp1 = cp[..., 1]
cp2 = cp[..., 2]
if a.shape[-1] == 2:
if b.shape[-1] == 2:
# a0 * b1 - a1 * b0
cp[...] = a0 * b1 - a1 * b0
return cp
else:
assert b.shape[-1] == 3
# cp0 = a1 * b2 - 0 (a2 = 0)
# cp1 = 0 - a0 * b2 (a2 = 0)
# cp2 = a0 * b1 - a1 * b0
cp0[...] = a1 * b2
cp1[...] = -a0 * b2
cp2[...] = a0 * b1 - a1 * b0
else:
assert a.shape[-1] == 3
if b.shape[-1] == 3:
cp0[...] = a1 * b2 - a2 * b1
cp1[...] = a2 * b0 - a0 * b2
cp2[...] = a0 * b1 - a1 * b0
else:
assert b.shape[-1] == 2
cp0[...] = -a2 * b1
cp1[...] = a2 * b0
cp2[...] = a0 * b1 - a1 * b0
return torch.moveaxis(cp, -1, axisc)
def einsum(*operands, out=None, dtype=None, order="K", casting="safe", optimize=False):
# Have to manually normalize *operands and **kwargs, following the NumPy signature
# We have a local import to avoid poluting the global space, as it will be then
# exported in funcs.py
from ._ndarray import ndarray
from ._normalizations import (
maybe_copy_to,
normalize_array_like,
normalize_casting,
normalize_dtype,
wrap_tensors,
)
dtype = normalize_dtype(dtype)
casting = normalize_casting(casting)
if out is not None and not isinstance(out, ndarray):
raise TypeError("'out' must be an array")
if order != "K":
raise NotImplementedError("'order' parameter is not supported.")
# parse arrays and normalize them
sublist_format = not isinstance(operands[0], str)
if sublist_format:
# op, str, op, str ... [sublistout] format: normalize every other argument
# - if sublistout is not given, the length of operands is even, and we pick
# odd-numbered elements, which are arrays.
# - if sublistout is given, the length of operands is odd, we peel off
# the last one, and pick odd-numbered elements, which are arrays.
# Without [:-1], we would have picked sublistout, too.
array_operands = operands[:-1][::2]
else:
# ("ij->", arrays) format
subscripts, array_operands = operands[0], operands[1:]
tensors = [normalize_array_like(op) for op in array_operands]
target_dtype = _dtypes_impl.result_type_impl(*tensors) if dtype is None else dtype
# work around 'bmm' not implemented for 'Half' etc
is_half = target_dtype == torch.float16 and all(t.is_cpu for t in tensors)
if is_half:
target_dtype = torch.float32
is_short_int = target_dtype in [torch.uint8, torch.int8, torch.int16, torch.int32]
if is_short_int:
target_dtype = torch.int64
tensors = _util.typecast_tensors(tensors, target_dtype, casting)
from torch.backends import opt_einsum
try:
# set the global state to handle the optimize=... argument, restore on exit
if opt_einsum.is_available():
old_strategy = torch.backends.opt_einsum.strategy
old_enabled = torch.backends.opt_einsum.enabled
# torch.einsum calls opt_einsum.contract_path, which runs into
# https://github.com/dgasmith/opt_einsum/issues/219
# for strategy={True, False}
if optimize is True:
optimize = "auto"
elif optimize is False:
torch.backends.opt_einsum.enabled = False
torch.backends.opt_einsum.strategy = optimize
if sublist_format:
# recombine operands
sublists = operands[1::2]
has_sublistout = len(operands) % 2 == 1
if has_sublistout:
sublistout = operands[-1]
operands = list(itertools.chain.from_iterable(zip(tensors, sublists)))
if has_sublistout:
operands.append(sublistout)
result = torch.einsum(*operands)
else:
result = torch.einsum(subscripts, *tensors)
finally:
if opt_einsum.is_available():
torch.backends.opt_einsum.strategy = old_strategy
torch.backends.opt_einsum.enabled = old_enabled
result = maybe_copy_to(out, result)
return wrap_tensors(result)
# ### sort and partition ###
def _sort_helper(tensor, axis, kind, order):
if tensor.dtype.is_complex:
raise NotImplementedError(f"sorting {tensor.dtype} is not supported")
(tensor,), axis = _util.axis_none_flatten(tensor, axis=axis)
axis = _util.normalize_axis_index(axis, tensor.ndim)
stable = kind == "stable"
return tensor, axis, stable
def sort(a: ArrayLike, axis=-1, kind=None, order: NotImplementedType = None):
# `order` keyword arg is only relevant for structured dtypes; so not supported here.
a, axis, stable = _sort_helper(a, axis, kind, order)
result = torch.sort(a, dim=axis, stable=stable)
return result.values
def argsort(a: ArrayLike, axis=-1, kind=None, order: NotImplementedType = None):
a, axis, stable = _sort_helper(a, axis, kind, order)
return torch.argsort(a, dim=axis, stable=stable)
def searchsorted(
a: ArrayLike, v: ArrayLike, side="left", sorter: Optional[ArrayLike] = None
):
if a.dtype.is_complex:
raise NotImplementedError(f"searchsorted with dtype={a.dtype}")
return torch.searchsorted(a, v, side=side, sorter=sorter)
# ### swap/move/roll axis ###
def moveaxis(a: ArrayLike, source, destination):
source = _util.normalize_axis_tuple(source, a.ndim, "source")
destination = _util.normalize_axis_tuple(destination, a.ndim, "destination")
return torch.moveaxis(a, source, destination)
def swapaxes(a: ArrayLike, axis1, axis2):
axis1 = _util.normalize_axis_index(axis1, a.ndim)
axis2 = _util.normalize_axis_index(axis2, a.ndim)
return torch.swapaxes(a, axis1, axis2)
def rollaxis(a: ArrayLike, axis, start=0):
# Straight vendor from:
# https://github.com/numpy/numpy/blob/v1.24.0/numpy/core/numeric.py#L1259
#
# Also note this function in NumPy is mostly retained for backwards compat
# (https://stackoverflow.com/questions/29891583/reason-why-numpy-rollaxis-is-so-confusing)
# so let's not touch it unless hard pressed.
n = a.ndim
axis = _util.normalize_axis_index(axis, n)
if start < 0:
start += n
msg = "'%s' arg requires %d <= %s < %d, but %d was passed in"
if not (0 <= start < n + 1):
raise _util.AxisError(msg % ("start", -n, "start", n + 1, start))
if axis < start:
# it's been removed
start -= 1
if axis == start:
# numpy returns a view, here we try returning the tensor itself
# return tensor[...]
return a
axes = list(range(0, n))
axes.remove(axis)
axes.insert(start, axis)
return a.view(axes)
def roll(a: ArrayLike, shift, axis=None):
if axis is not None:
axis = _util.normalize_axis_tuple(axis, a.ndim, allow_duplicate=True)
if not isinstance(shift, tuple):
shift = (shift,) * len(axis)
return torch.roll(a, shift, axis)
# ### shape manipulations ###
def squeeze(a: ArrayLike, axis=None):
if axis == ():
result = a
elif axis is None:
result = a.squeeze()
else:
if isinstance(axis, tuple):
result = a
for ax in axis:
result = a.squeeze(ax)
else:
result = a.squeeze(axis)
return result
def reshape(a: ArrayLike, newshape, order: NotImplementedType = "C"):
# if sh = (1, 2, 3), numpy allows both .reshape(sh) and .reshape(*sh)
newshape = newshape[0] if len(newshape) == 1 else newshape
return a.reshape(newshape)
# NB: cannot use torch.reshape(a, newshape) above, because of
# (Pdb) torch.reshape(torch.as_tensor([1]), 1)
# *** TypeError: reshape(): argument 'shape' (position 2) must be tuple of SymInts, not int
def transpose(a: ArrayLike, axes=None):
# numpy allows both .transpose(sh) and .transpose(*sh)
# also older code uses axes being a list
if axes in [(), None, (None,)]:
axes = tuple(reversed(range(a.ndim)))
elif len(axes) == 1:
axes = axes[0]
return a.permute(axes)
def ravel(a: ArrayLike, order: NotImplementedType = "C"):
return torch.flatten(a)
def diff(
a: ArrayLike,
n=1,
axis=-1,
prepend: Optional[ArrayLike] = None,
append: Optional[ArrayLike] = None,
):
axis = _util.normalize_axis_index(axis, a.ndim)
if n < 0:
raise ValueError(f"order must be non-negative but got {n}")
if n == 0:
# match numpy and return the input immediately
return a
if prepend is not None:
shape = list(a.shape)
shape[axis] = prepend.shape[axis] if prepend.ndim > 0 else 1
prepend = torch.broadcast_to(prepend, shape)
if append is not None:
shape = list(a.shape)
shape[axis] = append.shape[axis] if append.ndim > 0 else 1
append = torch.broadcast_to(append, shape)
return torch.diff(a, n, axis=axis, prepend=prepend, append=append)
# ### math functions ###
def angle(z: ArrayLike, deg=False):
result = torch.angle(z)
if deg:
result = result * (180 / torch.pi)
return result
def sinc(x: ArrayLike):
return torch.sinc(x)
# NB: have to normalize *varargs manually
def gradient(f: ArrayLike, *varargs, axis=None, edge_order=1):
N = f.ndim # number of dimensions
varargs = _util.ndarrays_to_tensors(varargs)
if axis is None:
axes = tuple(range(N))
else:
axes = _util.normalize_axis_tuple(axis, N)
len_axes = len(axes)
n = len(varargs)
if n == 0:
# no spacing argument - use 1 in all axes
dx = [1.0] * len_axes
elif n == 1 and (_dtypes_impl.is_scalar(varargs[0]) or varargs[0].ndim == 0):
# single scalar or 0D tensor for all axes (np.ndim(varargs[0]) == 0)
dx = varargs * len_axes
elif n == len_axes:
# scalar or 1d array for each axis
dx = list(varargs)
for i, distances in enumerate(dx):
distances = torch.as_tensor(distances)
if distances.ndim == 0:
continue
elif distances.ndim != 1:
raise ValueError("distances must be either scalars or 1d")
if len(distances) != f.shape[axes[i]]:
raise ValueError(
"when 1d, distances must match "
"the length of the corresponding dimension"
)
if not (distances.dtype.is_floating_point or distances.dtype.is_complex):
distances = distances.double()
diffx = torch.diff(distances)
# if distances are constant reduce to the scalar case
# since it brings a consistent speedup
if (diffx == diffx[0]).all():
diffx = diffx[0]
dx[i] = diffx
else:
raise TypeError("invalid number of arguments")
if edge_order > 2:
raise ValueError("'edge_order' greater than 2 not supported")
# use central differences on interior and one-sided differences on the
# endpoints. This preserves second order-accuracy over the full domain.
outvals = []
# create slice objects --- initially all are [:, :, ..., :]
slice1 = [slice(None)] * N
slice2 = [slice(None)] * N
slice3 = [slice(None)] * N
slice4 = [slice(None)] * N
otype = f.dtype
if _dtypes_impl.python_type_for_torch(otype) in (int, bool):
# Convert to floating point.
# First check if f is a numpy integer type; if so, convert f to float64
# to avoid modular arithmetic when computing the changes in f.
f = f.double()
otype = torch.float64
for axis, ax_dx in zip(axes, dx):
if f.shape[axis] < edge_order + 1:
raise ValueError(
"Shape of array too small to calculate a numerical gradient, "
"at least (edge_order + 1) elements are required."
)
# result allocation
out = torch.empty_like(f, dtype=otype)
# spacing for the current axis (NB: np.ndim(ax_dx) == 0)
uniform_spacing = _dtypes_impl.is_scalar(ax_dx) or ax_dx.ndim == 0
# Numerical differentiation: 2nd order interior
slice1[axis] = slice(1, -1)
slice2[axis] = slice(None, -2)
slice3[axis] = slice(1, -1)
slice4[axis] = slice(2, None)
if uniform_spacing:
out[tuple(slice1)] = (f[tuple(slice4)] - f[tuple(slice2)]) / (2.0 * ax_dx)
else:
dx1 = ax_dx[0:-1]
dx2 = ax_dx[1:]
a = -(dx2) / (dx1 * (dx1 + dx2))
b = (dx2 - dx1) / (dx1 * dx2)
c = dx1 / (dx2 * (dx1 + dx2))
# fix the shape for broadcasting
shape = [1] * N
shape[axis] = -1
a = a.reshape(shape)
b = b.reshape(shape)
c = c.reshape(shape)
# 1D equivalent -- out[1:-1] = a * f[:-2] + b * f[1:-1] + c * f[2:]
out[tuple(slice1)] = (
a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)]
)
# Numerical differentiation: 1st order edges
if edge_order == 1:
slice1[axis] = 0
slice2[axis] = 1
slice3[axis] = 0
dx_0 = ax_dx if uniform_spacing else ax_dx[0]
# 1D equivalent -- out[0] = (f[1] - f[0]) / (x[1] - x[0])
out[tuple(slice1)] = (f[tuple(slice2)] - f[tuple(slice3)]) / dx_0
slice1[axis] = -1
slice2[axis] = -1
slice3[axis] = -2
dx_n = ax_dx if uniform_spacing else ax_dx[-1]
# 1D equivalent -- out[-1] = (f[-1] - f[-2]) / (x[-1] - x[-2])
out[tuple(slice1)] = (f[tuple(slice2)] - f[tuple(slice3)]) / dx_n
# Numerical differentiation: 2nd order edges
else:
slice1[axis] = 0
slice2[axis] = 0
slice3[axis] = 1
slice4[axis] = 2
if uniform_spacing:
a = -1.5 / ax_dx
b = 2.0 / ax_dx
c = -0.5 / ax_dx
else:
dx1 = ax_dx[0]
dx2 = ax_dx[1]
a = -(2.0 * dx1 + dx2) / (dx1 * (dx1 + dx2))
b = (dx1 + dx2) / (dx1 * dx2)
c = -dx1 / (dx2 * (dx1 + dx2))
# 1D equivalent -- out[0] = a * f[0] + b * f[1] + c * f[2]
out[tuple(slice1)] = (
a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)]
)
slice1[axis] = -1
slice2[axis] = -3
slice3[axis] = -2
slice4[axis] = -1
if uniform_spacing:
a = 0.5 / ax_dx
b = -2.0 / ax_dx
c = 1.5 / ax_dx
else:
dx1 = ax_dx[-2]
dx2 = ax_dx[-1]
a = (dx2) / (dx1 * (dx1 + dx2))
b = -(dx2 + dx1) / (dx1 * dx2)
c = (2.0 * dx2 + dx1) / (dx2 * (dx1 + dx2))
# 1D equivalent -- out[-1] = a * f[-3] + b * f[-2] + c * f[-1]
out[tuple(slice1)] = (
a * f[tuple(slice2)] + b * f[tuple(slice3)] + c * f[tuple(slice4)]
)
outvals.append(out)
# reset the slice object in this dimension to ":"
slice1[axis] = slice(None)
slice2[axis] = slice(None)
slice3[axis] = slice(None)
slice4[axis] = slice(None)
if len_axes == 1:
return outvals[0]
else:
return outvals
# ### Type/shape etc queries ###
def round(a: ArrayLike, decimals=0, out: Optional[OutArray] = None):
if a.is_floating_point():
result = torch.round(a, decimals=decimals)
elif a.is_complex():
# RuntimeError: "round_cpu" not implemented for 'ComplexFloat'
result = torch.complex(
torch.round(a.real, decimals=decimals),
torch.round(a.imag, decimals=decimals),
)
else:
# RuntimeError: "round_cpu" not implemented for 'int'
result = a
return result
around = round
round_ = round
def real_if_close(a: ArrayLike, tol=100):
if not torch.is_complex(a):
return a
if tol > 1:
# Undocumented in numpy: if tol < 1, it's an absolute tolerance!
# Otherwise, tol > 1 is relative tolerance, in units of the dtype epsilon
# https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/type_check.py#L577
tol = tol * torch.finfo(a.dtype).eps
mask = torch.abs(a.imag) < tol
return a.real if mask.all() else a
def real(a: ArrayLike):
return torch.real(a)
def imag(a: ArrayLike):
if a.is_complex():
return a.imag
return torch.zeros_like(a)
def iscomplex(x: ArrayLike):
if torch.is_complex(x):
return x.imag != 0
return torch.zeros_like(x, dtype=torch.bool)
def isreal(x: ArrayLike):
if torch.is_complex(x):
return x.imag == 0
return torch.ones_like(x, dtype=torch.bool)
def iscomplexobj(x: ArrayLike):
return torch.is_complex(x)
def isrealobj(x: ArrayLike):
return not torch.is_complex(x)
def isneginf(x: ArrayLike, out: Optional[OutArray] = None):
return torch.isneginf(x)
def isposinf(x: ArrayLike, out: Optional[OutArray] = None):
return torch.isposinf(x)
def i0(x: ArrayLike):
return torch.special.i0(x)
def isscalar(a):
# We need to use normalize_array_like, but we don't want to export it in funcs.py
from ._normalizations import normalize_array_like
try:
t = normalize_array_like(a)
return t.numel() == 1
except Exception:
return False
# ### Filter windows ###
def hamming(M):
dtype = _dtypes_impl.default_dtypes().float_dtype
return torch.hamming_window(M, periodic=False, dtype=dtype)
def hanning(M):
dtype = _dtypes_impl.default_dtypes().float_dtype
return torch.hann_window(M, periodic=False, dtype=dtype)
def kaiser(M, beta):
dtype = _dtypes_impl.default_dtypes().float_dtype
return torch.kaiser_window(M, beta=beta, periodic=False, dtype=dtype)
def blackman(M):
dtype = _dtypes_impl.default_dtypes().float_dtype
return torch.blackman_window(M, periodic=False, dtype=dtype)
def bartlett(M):
dtype = _dtypes_impl.default_dtypes().float_dtype
return torch.bartlett_window(M, periodic=False, dtype=dtype)
# ### Dtype routines ###
# vendored from https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/type_check.py#L666
array_type = [
[torch.float16, torch.float32, torch.float64],
[None, torch.complex64, torch.complex128],
]
array_precision = {
torch.float16: 0,
torch.float32: 1,
torch.float64: 2,
torch.complex64: 1,
torch.complex128: 2,
}
def common_type(*tensors: ArrayLike):
is_complex = False
precision = 0
for a in tensors:
t = a.dtype
if iscomplexobj(a):
is_complex = True
if not (t.is_floating_point or t.is_complex):
p = 2 # array_precision[_nx.double]
else:
p = array_precision.get(t, None)
if p is None:
raise TypeError("can't get common type for non-numeric array")
precision = builtins.max(precision, p)
if is_complex:
return array_type[1][precision]
else:
return array_type[0][precision]
# ### histograms ###
def histogram(
a: ArrayLike,
bins: ArrayLike = 10,
range=None,
normed=None,
weights: Optional[ArrayLike] = None,
density=None,
):
if normed is not None:
raise ValueError("normed argument is deprecated, use density= instead")
if weights is not None and weights.dtype.is_complex:
raise NotImplementedError("complex weights histogram.")
is_a_int = not (a.dtype.is_floating_point or a.dtype.is_complex)
is_w_int = weights is None or not weights.dtype.is_floating_point
if is_a_int:
a = a.double()
if weights is not None:
weights = _util.cast_if_needed(weights, a.dtype)
if isinstance(bins, torch.Tensor):
if bins.ndim == 0:
# bins was a single int
bins = operator.index(bins)
else:
bins = _util.cast_if_needed(bins, a.dtype)
if range is None:
h, b = torch.histogram(a, bins, weight=weights, density=bool(density))
else:
h, b = torch.histogram(
a, bins, range=range, weight=weights, density=bool(density)
)
if not density and is_w_int:
h = h.long()
if is_a_int:
b = b.long()
return h, b
def histogram2d(
x,
y,
bins=10,
range: Optional[ArrayLike] = None,
normed=None,
weights: Optional[ArrayLike] = None,
density=None,
):
# vendored from https://github.com/numpy/numpy/blob/v1.24.0/numpy/lib/twodim_base.py#L655-L821
if len(x) != len(y):
raise ValueError("x and y must have the same length.")
try:
N = len(bins)
except TypeError:
N = 1
if N != 1 and N != 2:
bins = [bins, bins]
h, e = histogramdd((x, y), bins, range, normed, weights, density)
return h, e[0], e[1]
def histogramdd(
sample,
bins=10,
range: Optional[ArrayLike] = None,
normed=None,
weights: Optional[ArrayLike] = None,
density=None,
):
# have to normalize manually because `sample` interpretation differs
# for a list of lists and a 2D array
if normed is not None:
raise ValueError("normed argument is deprecated, use density= instead")
from ._normalizations import normalize_array_like, normalize_seq_array_like
if isinstance(sample, (list, tuple)):
sample = normalize_array_like(sample).T
else:
sample = normalize_array_like(sample)
sample = torch.atleast_2d(sample)
if not (sample.dtype.is_floating_point or sample.dtype.is_complex):
sample = sample.double()
# bins is either an int, or a sequence of ints or a sequence of arrays
bins_is_array = not (
isinstance(bins, int) or builtins.all(isinstance(b, int) for b in bins)
)
if bins_is_array:
bins = normalize_seq_array_like(bins)
bins_dtypes = [b.dtype for b in bins]
bins = [_util.cast_if_needed(b, sample.dtype) for b in bins]
if range is not None:
range = range.flatten().tolist()
if weights is not None:
# range=... is required : interleave min and max values per dimension
mm = sample.aminmax(dim=0)
range = torch.cat(mm).reshape(2, -1).T.flatten()
range = tuple(range.tolist())
weights = _util.cast_if_needed(weights, sample.dtype)
w_kwd = {"weight": weights}
else:
w_kwd = {}
h, b = torch.histogramdd(sample, bins, range, density=bool(density), **w_kwd)
if bins_is_array:
b = [_util.cast_if_needed(bb, dtyp) for bb, dtyp in zip(b, bins_dtypes)]
return h, b
# ### odds and ends
def min_scalar_type(a: ArrayLike, /):
# https://github.com/numpy/numpy/blob/maintenance/1.24.x/numpy/core/src/multiarray/convert_datatype.c#L1288
from ._dtypes import DType
if a.numel() > 1:
# numpy docs: "For non-scalar array a, returns the vector's dtype unmodified."
return DType(a.dtype)
if a.dtype == torch.bool:
dtype = torch.bool
elif a.dtype.is_complex:
fi = torch.finfo(torch.float32)
fits_in_single = a.dtype == torch.complex64 or (
fi.min <= a.real <= fi.max and fi.min <= a.imag <= fi.max
)
dtype = torch.complex64 if fits_in_single else torch.complex128
elif a.dtype.is_floating_point:
for dt in [torch.float16, torch.float32, torch.float64]:
fi = torch.finfo(dt)
if fi.min <= a <= fi.max:
dtype = dt
break
else:
# must be integer
for dt in [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]:
# Prefer unsigned int where possible, as numpy does.
ii = torch.iinfo(dt)
if ii.min <= a <= ii.max:
dtype = dt
break
return DType(dtype)
def pad(array: ArrayLike, pad_width: ArrayLike, mode="constant", **kwargs):
if mode != "constant":
raise NotImplementedError
value = kwargs.get("constant_values", 0)
# `value` must be a python scalar for torch.nn.functional.pad
typ = _dtypes_impl.python_type_for_torch(array.dtype)
value = typ(value)
pad_width = torch.broadcast_to(pad_width, (array.ndim, 2))
pad_width = torch.flip(pad_width, (0,)).flatten()
return torch.nn.functional.pad(array, tuple(pad_width), value=value)
|