/usr/lib/python2.7/dist-packages/tables/tests/test_tablesMD.py is in python-tables 3.4.2-4.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import
import sys
import numpy as np
from numpy import rec as records
import tables
from tables import (
Col, StringCol, IntCol, FloatCol, Int16Col, UInt16Col, Float32Col,
)
from tables.tests import common
from tables.tests.common import allequal
from tables.tests.common import unittest
from tables.tests.common import PyTablesTestCase as TestCase
from tables.description import descr_from_dtype
from six.moves import range
# It is important that columns are ordered according to their names
# to ease the comparison with structured arrays.
# Test Record class
class Record(tables.IsDescription):
var0 = StringCol(itemsize=4, dflt=b"", shape=2) # 4-character string array
var1 = StringCol(itemsize=4, dflt=[b"abcd", b"efgh"], shape=(2, 2))
var1_ = IntCol(dflt=((1, 1),), shape=2) # integer array
var2 = IntCol(dflt=((1, 1), (1, 1)), shape=(2, 2)) # integer array
var3 = Int16Col(dflt=2) # short integer
var4 = FloatCol(dflt=3.1) # double (double-precision)
var5 = Float32Col(dflt=4.2) # float (single-precision)
var6 = UInt16Col(dflt=5) # unsigned short integer
var7 = StringCol(itemsize=1, dflt=b"e") # 1-character String
# Dictionary definition
RecordDescriptionDict = {
'var0': StringCol(itemsize=4, dflt=b"", shape=2), # 4-character string
# array
'var1': StringCol(itemsize=4, dflt=[b"abcd", b"efgh"], shape=(2, 2)),
#'var0': StringCol(itemsize=4, shape=2), # 4-character String
#'var1': StringCol(itemsize=4, shape=(2,2)), # 4-character String
'var1_': IntCol(shape=2), # integer array
'var2': IntCol(shape=(2, 2)), # integer array
'var3': Int16Col(), # short integer
'var4': FloatCol(), # double (double-precision)
'var5': Float32Col(), # float (single-precision)
'var6': Int16Col(), # unsigned short integer
'var7': StringCol(itemsize=1), # 1-character String
}
# Record class with numpy dtypes (mixed shapes is checked here)
class RecordDT(tables.IsDescription):
var0 = Col.from_dtype(np.dtype("2S4"), dflt=b"") # shape in dtype
var1 = Col.from_dtype(np.dtype(("S4", (
2, 2))), dflt=[b"abcd", b"efgh"]) # shape is a mix
var1_ = Col.from_dtype(np.dtype("2i4"), dflt=((1, 1),)) # shape in dtype
var2 = Col.from_sctype("i4", shape=(
2, 2), dflt=((1, 1), (1, 1))) # shape is a mix
var3 = Col.from_dtype(np.dtype("i2"), dflt=2)
var4 = Col.from_dtype(np.dtype("2f8"), dflt=3.1)
var5 = Col.from_dtype(np.dtype("f4"), dflt=4.2)
var6 = Col.from_dtype(np.dtype("()u2"), dflt=5)
var7 = Col.from_dtype(np.dtype("1S1"), dflt=b"e") # no shape
class BasicTestCase(common.TempFileMixin, TestCase):
# file = "test.h5"
open_mode = "w"
title = "This is the table title"
expectedrows = 100
appendrows = 20
compress = 0
complib = "zlib" # Default compression library
record = Record
recarrayinit = 0
maxshort = 1 << 15
def setUp(self):
super(BasicTestCase, self).setUp()
# Create an instance of an HDF5 Table
self.rootgroup = self.h5file.root
self.populateFile()
self.h5file.close()
def initRecArray(self):
record = self.recordtemplate
row = record[0]
buflist = []
# Fill the recarray
for i in range(self.expectedrows + 1):
tmplist = []
# Both forms (list or chararray) works
var0 = ['%04d' % (self.expectedrows - i)] * 2
tmplist.append(var0)
var1 = [['%04d' % (self.expectedrows - i)] * 2] * 2
tmplist.append(var1)
var1_ = (i, 1)
tmplist.append(var1_)
var2 = ((i, 1), (1, 1)) # *-*
tmplist.append(var2)
var3 = i % self.maxshort
tmplist.append(var3)
if isinstance(row['var4'], np.ndarray):
tmplist.append([float(i), float(i * i)])
else:
tmplist.append(float(i))
if isinstance(row['var5'], np.ndarray):
tmplist.append(np.array((float(i),)*4))
else:
tmplist.append(float(i))
# var6 will be like var3 but byteswaped
tmplist.append(((var3 >> 8) & 0xff) + ((var3 << 8) & 0xff00))
var7 = var1[0][0][-1]
tmplist.append(var7)
buflist.append(tmplist)
self.record = np.rec.array(buflist, dtype=record.dtype,
shape=self.expectedrows)
def populateFile(self):
group = self.rootgroup
if self.recarrayinit:
# Initialize an starting buffer, if any
self.initRecArray()
for j in range(3):
# Create a table
filters = tables.Filters(complevel=self.compress,
complib=self.complib)
if j < 2:
byteorder = sys.byteorder
else:
# table2 will be byteswapped
byteorder = {"little": "big", "big": "little"}[sys.byteorder]
table = self.h5file.create_table(group, 'table'+str(j),
self.record,
title=self.title,
filters=filters,
expectedrows=self.expectedrows,
byteorder=byteorder)
if not self.recarrayinit:
# Get the row object associated with the new table
row = table.row
# Fill the table
for i in range(self.expectedrows):
s = '%04d' % (self.expectedrows - i)
row['var0'] = s.encode('ascii')
row['var1'] = s.encode('ascii')
row['var7'] = s[-1].encode('ascii')
row['var1_'] = (i, 1)
row['var2'] = ((i, 1), (1, 1)) # *-*
row['var3'] = i % self.maxshort
if isinstance(row['var4'], np.ndarray):
row['var4'] = [float(i), float(i * i)]
else:
row['var4'] = float(i)
if isinstance(row['var5'], np.ndarray):
row['var5'] = np.array((float(i),)*4)
else:
row['var5'] = float(i)
# var6 will be like var3 but byteswaped
row['var6'] = (((row['var3'] >> 8) & 0xff) +
((row['var3'] << 8) & 0xff00))
row.append()
# Flush the buffer for this table
table.flush()
# Create a new group (descendant of group)
group2 = self.h5file.create_group(group, 'group'+str(j))
# Iterate over this new group (group2)
group = group2
def test00_description(self):
"""Checking table description and descriptive fields."""
self.h5file = tables.open_file(self.h5fname)
tbl = self.h5file.get_node('/table0')
desc = tbl.description
if isinstance(self.record, dict):
columns = self.record
elif isinstance(self.record, np.ndarray):
descr, _ = descr_from_dtype(self.record.dtype)
columns = descr._v_colobjects
elif isinstance(self.record, np.dtype):
descr, _ = descr_from_dtype(self.record)
columns = descr._v_colobjects
else:
# This is an ordinary description.
columns = self.record.columns
# Check table and description attributes at the same time.
# These checks are only valid for non-nested tables.
# Column names.
expectedNames = ['var0', 'var1', 'var1_', 'var2', 'var3', 'var4',
'var5', 'var6', 'var7']
self.assertEqual(expectedNames, list(tbl.colnames))
self.assertEqual(expectedNames, list(desc._v_names))
# Column types.
expectedTypes = [columns[colname].dtype
for colname in expectedNames]
self.assertEqual(expectedTypes,
[tbl.coldtypes[v] for v in expectedNames])
self.assertEqual(expectedTypes,
[desc._v_dtypes[v] for v in expectedNames])
# Column string types.
expectedTypes = [columns[colname].type
for colname in expectedNames]
self.assertEqual(expectedTypes,
[tbl.coltypes[v] for v in expectedNames])
self.assertEqual(expectedTypes,
[desc._v_types[v] for v in expectedNames])
# Column defaults.
for v in expectedNames:
if common.verbose:
print("dflt-->", columns[v].dflt)
print("coldflts-->", tbl.coldflts[v])
print("desc.dflts-->", desc._v_dflts[v])
self.assertTrue(common.areArraysEqual(tbl.coldflts[v],
columns[v].dflt))
self.assertTrue(common.areArraysEqual(desc._v_dflts[v],
columns[v].dflt))
# Column path names.
self.assertEqual(expectedNames, list(desc._v_pathnames))
# Column objects.
for colName in expectedNames:
expectedCol = columns[colName]
col = desc._v_colobjects[colName]
self.assertEqual(expectedCol.dtype, col.dtype)
self.assertEqual(expectedCol.type, col.type)
def test01_readTable(self):
"""Checking table read and cuts."""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test01_readTable..." % self.__class__.__name__)
# Create an instance of an HDF5 Table
self.h5file = tables.open_file(self.h5fname, "r")
table = self.h5file.get_node("/table0")
# Choose a small value for buffer size
table.nrowsinbuf = 3
# Read the records and select those with "var2" file less than 20
result = [r['var2'][0][0] for r in table.iterrows()
if r['var2'][0][0] < 20]
if common.verbose:
print("Table:", repr(table))
print("Nrows in", table._v_pathname, ":", table.nrows)
print("Last record in table ==>", r)
print("Total selected records in table ==> ", len(result))
nrows = self.expectedrows - 1
r = [r for r in table.iterrows() if r['var2'][0][0] < 20][-1]
self.assertEqual((
r['var0'][0],
r['var1'][0][0],
r['var1_'][0],
r['var2'][0][0],
r['var7']
), (b"0001", b"0001", nrows, nrows, b"1"))
if isinstance(r['var5'], np.ndarray):
self.assertTrue(allequal(r['var5'],
np.array((nrows,)*4, np.float32)))
else:
self.assertEqual(r['var5'], float(nrows))
self.assertEqual(len(result), 20)
def test01b_readTable(self):
"""Checking table read and cuts (multidimensional columns case)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test01b_readTable..." % self.__class__.__name__)
# Create an instance of an HDF5 Table
self.h5file = tables.open_file(self.h5fname, "r")
table = self.h5file.get_node("/table0")
# Choose a small value for buffer size
table.nrowsinbuf = 3
# Read the records and select those with "var2" file less than 20
result1 = [r['var5'] for r in table.iterrows() if r['var2'][0][0] < 20]
if common.verbose:
print("Nrows in", table._v_pathname, ":", table.nrows)
print("Last record in table ==>", r)
print("Total selected records in table ==> ", len(result1))
nrows = table.nrows
result2 = [r for r in table.iterrows() if r['var2'][0][0] < 20][-1]
if isinstance(result2['var5'], np.ndarray):
self.assertTrue(allequal(result1[0],
np.array((float(0),)*4, np.float32)))
self.assertTrue(allequal(result1[1],
np.array((float(1),)*4, np.float32)))
self.assertTrue(allequal(result1[2],
np.array((float(2),)*4, np.float32)))
self.assertTrue(allequal(result1[3],
np.array((float(3),)*4, np.float32)))
self.assertTrue(allequal(result1[10],
np.array((float(10),)*4, np.float32)))
self.assertTrue(allequal(result2['var5'],
np.array((float(nrows-1),)*4,
np.float32)))
else:
self.assertEqual(result2['var5'], float(nrows-1))
self.assertEqual(len(result1), 20)
# Read the records and select those with "var2" file less than 20
result1 = [r['var1'] for r in table.iterrows() if r['var2'][0][0] < 20]
result2 = [r for r in table.iterrows() if r['var2'][0][0] < 20][-1]
if result2['var1'].dtype.char == "S":
a = np.array([['%04d' % (self.expectedrows - 0)]*2]*2, 'S')
self.assertTrue(allequal(result1[0], a))
a = np.array([['%04d' % (self.expectedrows - 1)]*2]*2, 'S')
self.assertTrue(allequal(result1[1], a))
a = np.array([['%04d' % (self.expectedrows - 2)]*2]*2, 'S')
self.assertTrue(allequal(result1[2], a))
a = np.array([['%04d' % (self.expectedrows - 3)]*2]*2, 'S')
self.assertTrue(allequal(result1[3], a))
a = np.array([['%04d' % (self.expectedrows - 10)]*2]*2, 'S')
self.assertTrue(allequal(result1[10], a))
a = np.array([['%04d' % (1)]*2]*2, 'S')
self.assertTrue(allequal(result2['var1'], a))
else:
self.assertEqual(result1['var1'], "0001")
self.assertEqual(len(result1), 20)
def test01c_readTable(self):
"""Checking shape of multidimensional columns."""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test01c_readTable..." % self.__class__.__name__)
# Create an instance of an HDF5 Table
self.h5file = tables.open_file(self.h5fname, "r")
table = self.h5file.get_node("/table0")
if common.verbose:
print("var2 col shape:", table.cols.var2.shape)
print("Should be:", table.cols.var2[:].shape)
self.assertEqual(table.cols.var2.shape, table.cols.var2[:].shape)
def test02_AppendRows(self):
"""Checking whether appending record rows works or not."""
# Now, open it, but in "append" mode
self.h5file = tables.open_file(self.h5fname, mode="a")
self.rootgroup = self.h5file.root
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test02_AppendRows..." % self.__class__.__name__)
# Get a table
table = self.h5file.get_node("/group0/table1")
# Get their row object
row = table.row
if common.verbose:
print("Nrows in old", table._v_pathname, ":", table.nrows)
print("Record Format ==>", table.description._v_nested_formats)
print("Record Size ==>", table.rowsize)
# Append some rows
for i in range(self.appendrows):
s = '%04d' % (self.appendrows - i)
row['var0'] = s.encode('ascii')
row['var1'] = s.encode('ascii')
row['var7'] = s[-1].encode('ascii')
row['var1_'] = (i, 1)
row['var2'] = ((i, 1), (1, 1)) # *-*
row['var3'] = i % self.maxshort
if isinstance(row['var4'], np.ndarray):
row['var4'] = [float(i), float(i * i)]
else:
row['var4'] = float(i)
if isinstance(row['var5'], np.ndarray):
row['var5'] = np.array((float(i),)*4)
else:
row['var5'] = float(i)
row.append()
# Flush the buffer for this table and read it
table.flush()
result = [r['var2'][0][0] for r in table.iterrows()
if r['var2'][0][0] < 20]
row = [r for r in table.iterrows() if r['var2'][0][0] < 20][-1]
nrows = self.appendrows - 1
self.assertEqual((
row['var0'][0],
row['var1'][0][0],
row['var1_'][0],
row['var2'][0][0],
row['var7']),
(b"0001", b"0001", nrows, nrows, b"1"))
if isinstance(row['var5'], np.ndarray):
self.assertTrue(allequal(row['var5'],
np.array((float(nrows),)*4, np.float32)))
else:
self.assertEqual(row['var5'], float(nrows))
if self.appendrows <= 20:
add = self.appendrows
else:
add = 20
self.assertEqual(len(result), 20 + add) # because we appended new rows
# del table
# CAVEAT: The next test only works for tables with rows < 2**15
def test03_endianess(self):
"""Checking if table is endianess aware."""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test03_endianess..." % self.__class__.__name__)
# Create an instance of an HDF5 Table
self.h5file = tables.open_file(self.h5fname, "r")
table = self.h5file.get_node("/group0/group1/table2")
# Read the records and select the ones with "var3" column less than 20
result = [r['var2'] for r in table.iterrows() if r['var3'] < 20]
if common.verbose:
print("Nrows in", table._v_pathname, ":", table.nrows)
print("On-disk byteorder ==>", table.byteorder)
print("Last record in table ==>", r)
print("Total selected records in table ==>", len(result))
nrows = self.expectedrows - 1
r = list(table.iterrows())[-1]
self.assertEqual((r['var1'][0][0], r['var3']), (b"0001", nrows))
self.assertEqual(len(result), 20)
class BasicWriteTestCase(BasicTestCase):
title = "BasicWrite"
class DictWriteTestCase(BasicTestCase):
# This checks also unidimensional arrays as columns
title = "DictWrite"
record = RecordDescriptionDict
nrows = 21
nrowsinbuf = 3 # Choose a small value for the buffer size
start = 0
stop = 10
step = 3
class RecordDTWriteTestCase(BasicTestCase):
title = "RecordDTWriteTestCase"
record = RecordDT
# Pure NumPy dtype
class NumPyDTWriteTestCase(BasicTestCase):
title = "NumPyDTWriteTestCase"
record = np.dtype("(2,)S4,(2,2)S4,(2,)i4,(2,2)i4,i2,2f8,f4,i2,S1")
record.names = 'var0,var1,var1_,var2,var3,var4,var5,var6,var7'.split(',')
class RecArrayOneWriteTestCase(BasicTestCase):
title = "RecArrayOneWrite"
record = np.rec.array(
None,
formats="(2,)S4,(2,2)S4,(2,)i4,(2,2)i4,i2,2f8,f4,i2,S1",
names='var0,var1,var1_,var2,var3,var4,var5,var6,var7',
shape=0)
class RecArrayTwoWriteTestCase(BasicTestCase):
title = "RecArrayTwoWrite"
expectedrows = 100
recarrayinit = 1
recordtemplate = np.rec.array(
None,
formats="(2,)a4,(2,2)a4,(2,)i4,(2,2)i4,i2,f8,f4,i2,a1",
names='var0,var1,var1_,var2,var3,var4,var5,var6,var7',
shape=1)
class RecArrayThreeWriteTestCase(BasicTestCase):
title = "RecArrayThreeWrite"
expectedrows = 100
recarrayinit = 1
recordtemplate = np.rec.array(
None,
formats="(2,)a4,(2,2)a4,(2,)i4,(2,2)i4,i2,2f8,4f4,i2,a1",
names='var0,var1,var1_,var2,var3,var4,var5,var6,var7',
shape=1)
@unittest.skipIf(not common.blosc_avail,
'BLOSC compression library not available')
class CompressBloscTablesTestCase(BasicTestCase):
title = "CompressBloscTables"
compress = 1
complib = "blosc"
@unittest.skipIf(not common.lzo_avail, 'LZO compression library not available')
class CompressLZOTablesTestCase(BasicTestCase):
title = "CompressLZOTables"
compress = 1
complib = "lzo"
@unittest.skipIf(not common.bzip2_avail,
'BZIP2 compression library not available')
class CompressBzip2TablesTestCase(BasicTestCase):
title = "CompressBzip2Tables"
compress = 1
complib = "bzip2"
class CompressZLIBTablesTestCase(BasicTestCase):
title = "CompressOneTables"
compress = 1
complib = "zlib"
class CompressTwoTablesTestCase(BasicTestCase):
title = "CompressTwoTables"
compress = 1
# This checks also unidimensional arrays as columns
record = RecordDescriptionDict
class BigTablesTestCase(BasicTestCase):
title = "BigTables"
# 10000 rows takes much more time than we can afford for tests
# reducing to 1000 would be more than enough
# F. Alted 2004-01-19
#expectedrows = 10000
#appendrows = 1000
expectedrows = 1000
appendrows = 100
class BasicRangeTestCase(common.TempFileMixin, TestCase):
# file = "test.h5"
open_mode = "w"
title = "This is the table title"
record = Record
maxshort = 1 << 15
expectedrows = 100
compress = 0
# Default values
nrows = 20
nrowsinbuf = 3 # Choose a small value for the buffer size
start = 1
stop = nrows
checkrecarray = 0
checkgetCol = 0
def setUp(self):
super(BasicRangeTestCase, self).setUp()
# Create an instance of an HDF5 Table
self.rootgroup = self.h5file.root
self.populateFile()
self.h5file.close()
def populateFile(self):
group = self.rootgroup
for j in range(3):
# Create a table
table = self.h5file.create_table(
group, 'table'+str(j), self.record, title=self.title,
filters=tables.Filters(self.compress),
expectedrows=self.expectedrows)
# Get the row object associated with the new table
row = table.row
# Fill the table
for i in range(self.expectedrows):
row['var1'] = '%04d' % (self.expectedrows - i)
row['var7'] = row['var1'][0][0][-1]
row['var2'] = i
row['var3'] = i % self.maxshort
if isinstance(row['var4'], np.ndarray):
row['var4'] = [float(i), float(i * i)]
else:
row['var4'] = float(i)
if isinstance(row['var5'], np.ndarray):
row['var5'] = np.array((float(i),)*4)
else:
row['var5'] = float(i)
# var6 will be like var3 but byteswaped
row['var6'] = (((row['var3'] >> 8) & 0xff) +
((row['var3'] << 8) & 0xff00))
row.append()
# Flush the buffer for this table
table.flush()
# Create a new group (descendant of group)
group2 = self.h5file.create_group(group, 'group'+str(j))
# Iterate over this new group (group2)
group = group2
def check_range(self):
# Create an instance of an HDF5 Table
self.h5file = tables.open_file(self.h5fname, "r")
table = self.h5file.get_node("/table0")
table.nrowsinbuf = self.nrowsinbuf
resrange = slice(self.start, self.stop, self.step).indices(table.nrows)
reslength = len(list(range(*resrange)))
if self.checkrecarray:
recarray = table.read(self.start, self.stop, self.step)
result = []
for nrec in range(len(recarray)):
if recarray['var2'][nrec][0][0] < self.nrows and 0 < self.step:
result.append(recarray['var2'][nrec][0][0])
elif (recarray['var2'][nrec][0][0] > self.nrows and
0 > self.step):
result.append(recarray['var2'][nrec][0][0])
elif self.checkgetCol:
column = table.read(self.start, self.stop, self.step, 'var2')
result = []
for nrec in range(len(column)):
if column[nrec][0][0] < self.nrows and 0 < self.step: # *-*
result.append(column[nrec][0][0]) # *-*
elif column[nrec][0][0] > self.nrows and 0 > self.step: # *-*
result.append(column[nrec][0][0]) # *-*
else:
if 0 < self.step:
result = [
r['var2'][0][0] for r in table.iterrows(self.start,
self.stop,
self.step)
if r['var2'][0][0] < self.nrows
]
elif 0 > self.step:
result = [
r['var2'][0][0] for r in table.iterrows(self.start,
self.stop,
self.step)
if r['var2'][0][0] > self.nrows
]
if self.start < 0:
startr = self.expectedrows + self.start
else:
startr = self.start
if self.stop is None:
if self.checkrecarray or self.checkgetCol:
# data read using the read method
stopr = startr + 1
else:
# data read using the iterrows method
stopr = self.nrows
elif self.stop < 0:
stopr = self.expectedrows + self.stop
else:
stopr = self.stop
if self.nrows < stopr:
stopr = self.nrows
if common.verbose:
print("Nrows in", table._v_pathname, ":", table.nrows)
if reslength:
if self.checkrecarray:
print("Last record *read* in recarray ==>", recarray[-1])
elif self.checkgetCol:
print("Last value *read* in getCol ==>", column[-1])
else:
print("Last record *read* in table range ==>", r)
print("Total number of selected records ==>", len(result))
print("Selected records:\n", result)
print("Selected records should look like:\n",
list(range(startr, stopr, self.step)))
print("start, stop, step ==>", startr, stopr, self.step)
self.assertEqual(result, list(range(startr, stopr, self.step)))
if not (self.checkrecarray or self.checkgetCol):
if startr < stopr and 0 < self.step:
r = [r['var2'] for r in table.iterrows(self.start, self.stop,
self.step)
if r['var2'][0][0] < self.nrows][-1]
if self.nrows > self.expectedrows:
self.assertEqual(
r[0][0],
list(range(self.start, self.stop, self.step))[-1])
else:
self.assertEqual(r[0][0],
list(range(startr, stopr, self.step))[-1])
elif startr > stopr and 0 > self.step:
r = [r['var2'] for r in table.iterrows(self.start, self.stop,
self.step)
if r['var2'][0][0] > self.nrows][0]
if self.nrows < self.expectedrows:
self.assertEqual(
r[0][0],
list(range(self.start, self.stop or -1, self.step))[0])
else:
self.assertEqual(
r[0][0],
list(range(startr, stopr or -1, self.step))[0])
# Close the file
self.h5file.close()
def test01_range(self):
"""Checking ranges in table iterators (case1)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test01_range..." % self.__class__.__name__)
# Case where step < nrowsinbuf < 2 * step
self.nrows = 21
self.nrowsinbuf = 3
self.start = 0
self.stop = self.expectedrows
self.step = 2
self.check_range()
def test01a_range(self):
"""Checking ranges in table iterators (case1)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test01_range..." % self.__class__.__name__)
# Case where step < nrowsinbuf < 2 * step
self.nrows = 21
self.nrowsinbuf = 3
self.start = self.expectedrows - 1
self.stop = None
self.step = -2
self.check_range()
def test02_range(self):
"""Checking ranges in table iterators (case2)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test02_range..." % self.__class__.__name__)
# Case where step < nrowsinbuf < 10 * step
self.nrows = 21
self.nrowsinbuf = 31
self.start = 11
self.stop = self.expectedrows
self.step = 3
self.check_range()
def test03_range(self):
"""Checking ranges in table iterators (case3)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test03_range..." % self.__class__.__name__)
# Case where step < nrowsinbuf < 1.1 * step
self.nrows = self.expectedrows
self.nrowsinbuf = 11 # Choose a small value for the buffer size
self.start = 0
self.stop = self.expectedrows
self.step = 10
self.check_range()
def test04_range(self):
"""Checking ranges in table iterators (case4)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test04_range..." % self.__class__.__name__)
# Case where step == nrowsinbuf
self.nrows = self.expectedrows
self.nrowsinbuf = 11 # Choose a small value for the buffer size
self.start = 1
self.stop = self.expectedrows
self.step = 11
self.check_range()
def test05_range(self):
"""Checking ranges in table iterators (case5)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test05_range..." % self.__class__.__name__)
# Case where step > 1.1 * nrowsinbuf
self.nrows = 21
self.nrowsinbuf = 10 # Choose a small value for the buffer size
self.start = 1
self.stop = self.expectedrows
self.step = 11
self.check_range()
def test06_range(self):
"""Checking ranges in table iterators (case6)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test06_range..." % self.__class__.__name__)
# Case where step > 3 * nrowsinbuf
self.nrows = 3
self.nrowsinbuf = 3 # Choose a small value for the buffer size
self.start = 2
self.stop = self.expectedrows
self.step = 10
self.check_range()
def test07_range(self):
"""Checking ranges in table iterators (case7)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test07_range..." % self.__class__.__name__)
# Case where start == stop
self.nrows = 2
self.nrowsinbuf = 3 # Choose a small value for the buffer size
self.start = self.nrows
self.stop = self.nrows
self.step = 10
self.check_range()
def test08_range(self):
"""Checking ranges in table iterators (case8)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test08_range..." % self.__class__.__name__)
# Case where start > stop
self.nrows = 2
self.nrowsinbuf = 3 # Choose a small value for the buffer size
self.start = self.nrows + 1
self.stop = self.nrows
self.step = 1
self.check_range()
def test09_range(self):
"""Checking ranges in table iterators (case9)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test09_range..." % self.__class__.__name__)
# Case where stop = None
self.nrows = 100
self.nrowsinbuf = 3 # Choose a small value for the buffer size
self.start = 1
self.stop = 2
self.step = 1
self.check_range()
def test10_range(self):
"""Checking ranges in table iterators (case10)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test10_range..." % self.__class__.__name__)
# Case where start < 0 and stop = 0
self.nrows = self.expectedrows
self.nrowsinbuf = 5 # Choose a small value for the buffer size
self.start = -6
self.startr = self.expectedrows + self.start
self.stop = 0
self.stopr = self.expectedrows + self.stop
self.step = 2
self.check_range()
def test11_range(self):
"""Checking ranges in table iterators (case11)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test11_range..." % self.__class__.__name__)
# Case where start < 0 and stop < 0
self.nrows = self.expectedrows
self.nrowsinbuf = 5 # Choose a small value for the buffer size
self.start = -6
self.startr = self.expectedrows + self.start
self.stop = -2
self.stopr = self.expectedrows + self.stop
self.step = 1
self.check_range()
def test12_range(self):
"""Checking ranges in table iterators (case12)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test12_range..." % self.__class__.__name__)
# Case where start < 0 and stop < 0 and start > stop
self.nrows = self.expectedrows
self.nrowsinbuf = 5 # Choose a small value for the buffer size
self.start = -1
self.startr = self.expectedrows + self.start
self.stop = -2
self.stopr = self.expectedrows + self.stop
self.step = 1
self.check_range()
def test13_range(self):
"""Checking ranges in table iterators (case13)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test13_range..." % self.__class__.__name__)
# Case where step < 0
self.step = -11
try:
self.check_range()
except ValueError:
if common.verbose:
(type, value, traceback) = sys.exc_info()
print("\nGreat!, the next ValueError was catched!")
self.h5file.close()
#else:
# self.fail("expected a ValueError")
# Case where step == 0
self.step = 0
try:
self.check_range()
except ValueError:
if common.verbose:
(type, value, traceback) = sys.exc_info()
print("\nGreat!, the next ValueError was catched!")
self.h5file.close()
#else:
# self.fail("expected a ValueError")
class IterRangeTestCase(BasicRangeTestCase):
pass
class RecArrayRangeTestCase(BasicRangeTestCase):
checkrecarray = 1
class GetColRangeTestCase(BasicRangeTestCase):
checkgetCol = 1
def test01_nonexistentField(self):
"""Checking non-existing Field in getCol method """
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test01_nonexistentField..." %
self.__class__.__name__)
# Create an instance of an HDF5 Table
self.h5file = tables.open_file(self.h5fname, "r")
self.root = self.h5file.root
table = self.h5file.get_node("/table0")
with self.assertRaises(KeyError):
table.read(field='non-existent-column')
class Rec(tables.IsDescription):
col1 = IntCol(pos=1, shape=(2,))
col2 = StringCol(itemsize=3, pos=2, shape=(3,))
col3 = FloatCol(pos=3, shape=(3, 2))
class RecArrayIO(common.TempFileMixin, TestCase):
def test00(self):
"""Checking saving a normal recarray"""
# Create a recarray
intlist1 = [[456, 23]*3]*2
intlist2 = np.array([[2, 2]*3]*2, dtype=int)
arrlist1 = [['dbe']*2]*3
arrlist2 = [['de']*2]*3
floatlist1 = [[1.2, 2.3]*3]*4
floatlist2 = np.array([[4.5, 2.4]*3]*4)
b = [[intlist1, arrlist1, floatlist1], [
intlist2, arrlist2, floatlist2]]
r = np.rec.array(b, formats='(2,6)i4,(3,2)a3,(4,6)f8',
names='col1,col2,col3')
# Save it in a table:
self.h5file.create_table(self.h5file.root, 'recarray', r)
# Read it again
r2 = self.h5file.root.recarray.read()
self.assertEqual(r.tostring(), r2.tostring())
def test01(self):
"""Checking saving a recarray with an offset in its buffer"""
# Create a recarray
intlist1 = [[456, 23]*3]*2
intlist2 = np.array([[2, 2]*3]*2, dtype=int)
arrlist1 = [['dbe']*2]*3
arrlist2 = [['de']*2]*3
floatlist1 = [[1.2, 2.3]*3]*4
floatlist2 = np.array([[4.5, 2.4]*3]*4)
b = [[intlist1, arrlist1, floatlist1], [
intlist2, arrlist2, floatlist2]]
r = np.rec.array(b, formats='(2,6)i4,(3,2)a3,(4,6)f8',
names='col1,col2,col3')
# Get a view of the recarray
r1 = r[1:]
# Save it in a table:
self.h5file.create_table(self.h5file.root, 'recarray', r1)
# Read it again
r2 = self.h5file.root.recarray.read()
self.assertEqual(r1.tostring(), r2.tostring())
def test02(self):
"""Checking saving a slice of a large recarray"""
# Create a recarray
intlist1 = [[[23, 24, 35]*6]*6]
intlist2 = np.array([[[2, 3, 4]*6]*6], dtype=int)
arrlist1 = [['dbe']*2]*3
arrlist2 = [['de']*2]*3
floatlist1 = [[1.2, 2.3]*3]*4
floatlist2 = np.array([[4.5, 2.4]*3]*4)
b = [[intlist1, arrlist1, floatlist1], [
intlist2, arrlist2, floatlist2]]
r = np.rec.array(b * 300, formats='(1,6,18)i4,(3,2)a3,(4,6)f8',
names='col1,col2,col3')
# Get an slice of recarray
r1 = r[290:292]
# Save it in a table:
self.h5file.create_table(self.h5file.root, 'recarray', r1)
# Read it again
r2 = self.h5file.root.recarray.read()
self.assertEqual(r1.tostring(), r2.tostring())
def test03(self):
"""Checking saving a slice of an strided recarray"""
# Create a recarray
intlist1 = [[[23, 24, 35]*6]*6]
intlist2 = np.array([[[2, 3, 4]*6]*6], dtype=int)
arrlist1 = [['dbe']*2]*3
arrlist2 = [['de']*2]*3
floatlist1 = [[1.2, 2.3]*3]*4
floatlist2 = np.array([[4.5, 2.4]*3]*4)
b = [[intlist1, arrlist1, floatlist1], [
intlist2, arrlist2, floatlist2]]
r = np.rec.array(b * 300, formats='(1,6,18)i4,(3,2)a3,(4,6)f8',
names='col1,col2,col3', shape=300)
# Get an strided recarray
r2 = r[::2]
# Get a slice
r1 = r2[148:]
# Save it in a table:
self.h5file.create_table(self.h5file.root, 'recarray', r1)
# Read it again
r2 = self.h5file.root.recarray.read()
self.assertEqual(r1.tostring(), r2.tostring())
def test08a(self):
"""Checking modifying one column (single column version, list)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test08a..." % self.__class__.__name__)
# Create a new table:
table = self.h5file.create_table(self.h5file.root, 'recarray', Rec)
# Append new rows
s0, s1, s2, s3 = ['dbe']*3, ['ded']*3, ['db1']*3, ['de1']*3
f0, f1, f2, f3 = [[1.2]*2]*3, [[1.3]*2]*3, [[1.4]*2]*3, [[1.5]*2]*3
r = records.array([[[456, 457], s0, f0], [[2, 3], s1, f1]],
formats="(2,)i4,(3,)a3,(3,2)f8")
table.append(r)
table.append([[[457, 458], s2, f2], [[5, 6], s3, f3]])
# Modify just one existing column
table.cols.col1[1:] = [[[2, 3], [3, 4], [4, 5]]]
# Create the modified recarray
r1 = records.array([[[456, 457], s0, f0], [[2, 3], s1, f1],
[[3, 4], s2, f2], [[4, 5], s3, f3]],
formats="(2,)i4,(3,)a3,(3,2)f8",
names="col1,col2,col3")
# Read the modified table
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test08b(self):
"""Checking modifying one column (single column version, recarray)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test08b..." % self.__class__.__name__)
# Create a new table:
table = self.h5file.create_table(self.h5file.root, 'recarray', Rec)
# Append new rows
s0, s1, s2, s3 = ['dbe']*3, ['ded']*3, ['db1']*3, ['de1']*3
f0, f1, f2, f3 = [[1.2]*2]*3, [[1.3]*2]*3, [[1.4]*2]*3, [[1.5]*2]*3
r = records.array([[[456, 457], s0, f0], [[2, 3], s1, f1]],
formats="(2,)i4,(3,)a3,(3,2)f8")
table.append(r)
table.append([[[457, 458], s2, f2], [[5, 6], s3, f3]])
# Modify just one existing column
columns = records.fromarrays(
np.array([[[2, 3], [3, 4], [4, 5]]]), formats="i4")
table.modify_columns(start=1, columns=columns, names=["col1"])
# Create the modified recarray
r1 = records.array([[[456, 457], s0, f0], [[2, 3], s1, f1],
[[3, 4], s2, f2], [[4, 5], s3, f3]],
formats="(2,)i4,(3,)a3,(3,2)f8",
names="col1,col2,col3")
# Read the modified table
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test08b2(self):
"""Checking modifying one column (single column version, recarray,
modify_column)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test08b2..." % self.__class__.__name__)
# Create a new table:
table = self.h5file.create_table(self.h5file.root, 'recarray', Rec)
# Append new rows
s0, s1, s2, s3 = ['dbe']*3, ['ded']*3, ['db1']*3, ['de1']*3
f0, f1, f2, f3 = [[1.2]*2]*3, [[1.3]*2]*3, [[1.4]*2]*3, [[1.5]*2]*3
r = records.array([[[456, 457], s0, f0], [[2, 3], s1, f1]],
formats="(2,)i4,(3,)a3,(3,2)f8")
table.append(r)
table.append([[[457, 458], s2, f2], [[5, 6], s3, f3]])
# Modify just one existing column
columns = records.fromarrays(
np.array([[[2, 3], [3, 4], [4, 5]]]), formats="i4")
table.modify_column(start=1, column=columns, colname="col1")
# Create the modified recarray
r1 = records.array([[[456, 457], s0, f0], [[2, 3], s1, f1],
[[3, 4], s2, f2], [[4, 5], s3, f3]],
formats="(2,)i4,(3,)a3,(3,2)f8",
names="col1,col2,col3")
# Read the modified table
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
class DefaultValues(common.TempFileMixin, TestCase):
def test00(self):
"""Checking saving a Table MD with default values"""
# Create a table
table = self.h5file.create_table(self.h5file.root, 'table', Record)
# Take a number of records a bit large
# nrows = int(table.nrowsinbuf * 1.1)
nrows = 5 # for test
# Fill the table with nrows records
for i in range(nrows):
if i == 3 or i == 4:
table.row['var2'] = ((2, 2), (2, 2)) # *-*
# This injects the row values.
table.row.append()
# We need to flush the buffers in table in order to get an
# accurate number of records on it.
table.flush()
# Create a recarray with the same default values
buffer = [[
["\x00"]*2, # just "" does not initialize the buffer properly
[["abcd", "efgh"]]*2,
(1, 1),
((1, 1), (1, 1)),
2, 3.1, 4.2, 5, "e"]]
r = np.rec.array(
buffer * nrows,
formats='(2,)a4,(2,2)a4,(2,)i4,(2,2)i4,i2,f8,f4,u2,a1',
names=['var0', 'var1', 'var1_', 'var2', 'var3', 'var4', 'var5',
'var6', 'var7']) # *-*
# Assign the value exceptions
r["var2"][3] = ((2, 2), (2, 2)) # *-*
r["var2"][4] = ((2, 2), (2, 2)) # *-*
# Read the table in another recarray
r2 = table.read()
# This generates too much output. Activate only when
# self.nrowsinbuf is very small (<10)
if common.verbose and 1:
print("Table values:")
print(r2)
print("Record values:")
print(r)
# Both checks do work, however, tostring() seems more stringent.
self.assertEqual(r.tostring(), r2.tostring())
# self.assertTrue(common.areArraysEqual(r,r2))
class RecordT(tables.IsDescription):
var0 = IntCol(dflt=1, shape=()) # native int
var1 = IntCol(dflt=[1], shape=(1,)) # 1-D int (one element)
var2_s = IntCol(dflt=[1, 1], shape=2) # 1-D int (two elements)
var2 = IntCol(dflt=[1, 1], shape=(2,)) # 1-D int (two elements)
var3 = IntCol(dflt=[[0, 0], [1, 1]], shape=(2, 2)) # 2-D int
class ShapeTestCase(common.TempFileMixin, TestCase):
def setUp(self):
super(ShapeTestCase, self).setUp()
self.populateFile()
def populateFile(self):
table = self.h5file.create_table(self.h5file.root, 'table', RecordT)
row = table.row
# Fill the table with some rows with default values
for i in range(1):
row.append()
# Flush the buffer for this table
table.flush()
def test00(self):
"""Checking scalar shapes"""
if self.reopen:
self._reopen()
table = self.h5file.root.table
if common.verbose:
print("The values look like:", table.cols.var0[:])
print("They should look like:", [1])
# The real check
self.assertEqual(table.cols.var0[:].tolist(), [1])
def test01(self):
"""Checking undimensional (one element) shapes"""
if self.reopen:
self._reopen()
table = self.h5file.root.table
if common.verbose:
print("The values look like:", table.cols.var1[:])
print("They should look like:", [[1]])
# The real check
self.assertEqual(table.cols.var1[:].tolist(), [[1]])
def test02(self):
"""Checking undimensional (two elements) shapes"""
if self.reopen:
self._reopen()
table = self.h5file.root.table
if common.verbose:
print("The values look like:", table.cols.var2[:])
print("They should look like:", [[1, 1]])
# The real check
self.assertEqual(table.cols.var2[:].tolist(), [[1, 1]])
self.assertEqual(table.cols.var2_s[:].tolist(), [[1, 1]])
def test03(self):
"""Checking bidimensional shapes"""
if self.reopen:
self._reopen()
table = self.h5file.root.table
if common.verbose:
print("The values look like:", table.cols.var3[:])
print("They should look like:", [[[0, 0], [1, 1]]])
# The real check
self.assertEqual(table.cols.var3[:].tolist(), [[[0, 0], [1, 1]]])
class ShapeTestCase1(ShapeTestCase):
reopen = 0
class ShapeTestCase2(ShapeTestCase):
reopen = 1
class SetItemTestCase(common.TempFileMixin, TestCase):
def setUp(self):
super(SetItemTestCase, self).setUp()
# Create a new table:
self.table = self.h5file.create_table(self.h5file.root,
'recarray', Rec)
self.table.nrowsinbuf = self.buffersize # set buffer value
def test01(self):
"""Checking modifying one table row with __setitem__"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify just one existing row
table[2] = (456, 'db2', 1.2)
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [2, 'ded', 1.3],
[456, 'db2', 1.2], [5, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test01b(self):
"""Checking modifying one table row with __setitem__ (long index)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify just one existing row
table[2] = (456, 'db2', 1.2)
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [2, 'ded', 1.3],
[456, 'db2', 1.2], [5, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test02(self):
"""Modifying one row, with a step (__setitem__)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify two existing rows
rows = records.array([[457, 'db1', 1.2]],
formats=formats)
table[1:3:2] = rows
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [457, 'db1', 1.2],
[457, 'db1', 1.2], [5, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test03(self):
"""Checking modifying several rows at once (__setitem__)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify two existing rows
rows = records.array([[457, 'db1', 1.2], [5, 'de1', 1.3]],
formats=formats)
# table.modify_rows(start=1, rows=rows)
table[1:3] = rows
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [457, 'db1', 1.2],
[5, 'de1', 1.3], [5, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test04(self):
"""Modifying several rows at once, with a step (__setitem__)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify two existing rows
rows = records.array([[457, 'db1', 1.2], [6, 'de2', 1.3]],
formats=formats)
# table[1:4:2] = rows
table[1::2] = rows
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [457, 'db1', 1.2],
[457, 'db1', 1.2], [6, 'de2', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test05(self):
"""Checking modifying one column (single element, __setitem__)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify just one existing column
table.cols.col1[1] = -1
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [-1, 'ded', 1.3],
[457, 'db1', 1.2], [5, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test06a(self):
"""Checking modifying one column (several elements, __setitem__)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify just one existing column
table.cols.col1[1:4] = [(2, 2), (3, 3), (4, 4)]
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [2, 'ded', 1.3],
[3, 'db1', 1.2], [4, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test06b(self):
"""Checking modifying one column (iterator, __setitem__)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify just one existing column
with self.assertRaises(NotImplementedError):
for row in table.iterrows():
row['col1'] = row.nrow + 1
row.append()
table.flush()
def test07(self):
"""Modifying one column (several elements, __setitem__, step)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
1, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify just one existing column
table.cols.col1[1:4:2] = [(2, 2), (3, 3)]
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [2, 'ded', 1.3],
[457, 'db1', 1.2], [3, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test08(self):
"""Modifying one column (one element, __setitem__, step)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify just one existing column
table.cols.col1[1:4:3] = [(2, 2)]
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [2, 'ded', 1.3],
[457, 'db1', 1.2], [5, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test09(self):
"""Modifying beyond the table extend (__setitem__, step)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Try to modify beyond the extend
# This will silently exclude the non-fitting rows
rows = records.array([[457, 'db1', 1.2], [6, 'de2', 1.3]],
formats=formats)
table[1::2] = rows
# How it should look like
r1 = records.array([[456, 'dbe', 1.2], [457, 'db1', 1.2],
[457, 'db1', 1.2], [6, 'de2', 1.3]],
formats=formats)
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
class SetItemTestCase1(SetItemTestCase):
reopen = 0
buffersize = 1
class SetItemTestCase2(SetItemTestCase):
reopen = 1
buffersize = 2
class SetItemTestCase3(SetItemTestCase):
reopen = 0
buffersize = 1000
class SetItemTestCase4(SetItemTestCase):
reopen = 1
buffersize = 1000
class UpdateRowTestCase(common.TempFileMixin, TestCase):
def setUp(self):
super(UpdateRowTestCase, self).setUp()
# Create a new table:
self.table = self.h5file.create_table(self.h5file.root,
'recarray', Rec)
self.table.nrowsinbuf = self.buffersize # set buffer value
def test01(self):
"""Checking modifying one table row with Row.update"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [2, 'ded', 1.3]],
formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify just one existing row
for row in table.iterrows(2, 3):
(row['col1'], row['col2'], row['col3']) = [456, 'db2', 1.2]
row.update()
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [2, 'ded', 1.3],
[456, 'db2', 1.2], [5, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test02(self):
"""Modifying one row, with a step (Row.update)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify two existing rows
for row in table.iterrows(1, 3, 2):
if row.nrow == 1:
(row['col1'], row['col2'], row['col3']) = [457, 'db1', 1.2]
elif row.nrow == 3:
(row['col1'], row['col2'], row['col3']) = [6, 'de2', 1.3]
row.update()
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [457, 'db1', 1.2],
[457, 'db1', 1.2], [5, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test03(self):
"""Checking modifying several rows at once (Row.update)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify two existing rows
for row in table.iterrows(1, 3):
if row.nrow == 1:
(row['col1'], row['col2'], row['col3']) = [457, 'db1', 1.2]
elif row.nrow == 2:
(row['col1'], row['col2'], row['col3']) = [5, 'de1', 1.3]
row.update()
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [457, 'db1', 1.2],
[5, 'de1', 1.3], [5, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test04(self):
"""Modifying several rows at once, with a step (Row.update)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify two existing rows
for row in table.iterrows(1, stop=4, step=2):
if row.nrow == 1:
(row['col1'], row['col2'], row['col3']) = [457, 'db1', 1.2]
elif row.nrow == 3:
(row['col1'], row['col2'], row['col3']) = [6, 'de2', 1.3]
row.update()
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [457, 'db1', 1.2],
[457, 'db1', 1.2], [6, 'de2', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertTrue(table.nrows, 4)
def test05(self):
"""Checking modifying one column (single element, Row.update)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify just one existing column
for row in table.iterrows(1, 2):
row['col1'] = -1
row.update()
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [-1, 'ded', 1.3],
[457, 'db1', 1.2], [5, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test06(self):
"""Checking modifying one column (several elements, Row.update)"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
2, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify just one existing column
for row in table.iterrows(1, 4):
row['col1'] = row.nrow + 1
row.update()
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [2, 'ded', 1.3],
[3, 'db1', 1.2], [4, 'de1', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test07(self):
"""Modifying values from a selection"""
table = self.table
formats = table.description._v_nested_formats
# append new rows
r = records.array([[456, 'dbe', 1.2], [
1, 'ded', 1.3]], formats=formats)
table.append(r)
table.append([[457, 'db1', 1.2], [5, 'de1', 1.3]])
# Modify just rows with col1 < 456
for row in table.iterrows():
if row['col1'][0] < 456:
row['col1'] = 2
row['col2'] = 'ada'
row.update()
# Create the modified recarray
r1 = records.array([[456, 'dbe', 1.2], [2, 'ada', 1.3],
[457, 'db1', 1.2], [2, 'ada', 1.3]],
formats=formats,
names="col1,col2,col3")
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, 4)
def test08(self):
"""Modifying a large table (Row.update)"""
table = self.table
formats = table.description._v_nested_formats
nrows = 100
# append new rows
row = table.row
for i in range(nrows):
row['col1'] = i-1
row['col2'] = 'a'+str(i-1)
row['col3'] = -1.0
row.append()
table.flush()
# Modify all the rows
for row in table.iterrows():
row['col1'] = row.nrow
row['col2'] = 'b'+str(row.nrow)
row['col3'] = 0.0
row.update()
# Create the modified recarray
r1 = records.array(None, shape=nrows,
formats=formats,
names="col1,col2,col3")
for i in range(nrows):
r1['col1'][i] = i
r1['col2'][i] = 'b'+str(i)
r1['col3'][i] = 0.0
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, nrows)
def test08b(self):
"""Setting values on a large table without calling Row.update"""
table = self.table
formats = table.description._v_nested_formats
nrows = 100
# append new rows
row = table.row
for i in range(nrows):
row['col1'] = i-1
row['col2'] = 'a'+str(i-1)
row['col3'] = -1.0
row.append()
table.flush()
# Modify all the rows (actually don't)
for row in table.iterrows():
row['col1'] = row.nrow
row['col2'] = 'b'+str(row.nrow)
row['col3'] = 0.0
# row.update()
# Create the modified recarray
r1 = records.array(None, shape=nrows,
formats=formats,
names="col1,col2,col3")
for i in range(nrows):
r1['col1'][i] = i-1
r1['col2'][i] = 'a'+str(i-1)
r1['col3'][i] = -1.0
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, nrows)
def test09(self):
"""Modifying selected values on a large table"""
table = self.table
formats = table.description._v_nested_formats
nrows = 100
# append new rows
row = table.row
for i in range(nrows):
row['col1'] = i-1
row['col2'] = 'a'+str(i-1)
row['col3'] = -1.0
row.append()
table.flush()
# Modify selected rows
for row in table.iterrows():
if row['col1'][0] > nrows-3:
row['col1'] = row.nrow
row['col2'] = 'b'+str(row.nrow)
row['col3'] = 0.0
row.update()
# Create the modified recarray
r1 = records.array(None, shape=nrows,
formats=formats,
names="col1,col2,col3")
for i in range(nrows):
r1['col1'][i] = i-1
r1['col2'][i] = 'a'+str(i-1)
r1['col3'][i] = -1.0
# modify just the last line
r1['col1'][i] = i
r1['col2'][i] = 'b'+str(i)
r1['col3'][i] = 0.0
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, nrows)
def test09b(self):
"""Modifying selected values on a large table (alternate values)"""
table = self.table
formats = table.description._v_nested_formats
nrows = 100
# append new rows
row = table.row
for i in range(nrows):
row['col1'] = i-1
row['col2'] = 'a'+str(i-1)
row['col3'] = -1.0
row.append()
table.flush()
# Modify selected rows
for row in table.iterrows(step=10):
row['col1'] = row.nrow
row['col2'] = 'b'+str(row.nrow)
row['col3'] = 0.0
row.update()
# Create the modified recarray
r1 = records.array(None, shape=nrows,
formats=formats,
names="col1,col2,col3")
for i in range(nrows):
if i % 10 > 0:
r1['col1'][i] = i-1
r1['col2'][i] = 'a'+str(i-1)
r1['col3'][i] = -1.0
else:
r1['col1'][i] = i
r1['col2'][i] = 'b'+str(i)
r1['col3'][i] = 0.0
# Read the modified table
if self.reopen:
self._reopen()
table = self.h5file.root.recarray
table.nrowsinbuf = self.buffersize # set buffer value
r2 = table.read()
if common.verbose:
print("Original table-->", repr(r2))
print("Should look like-->", repr(r1))
self.assertEqual(r1.tostring(), r2.tostring())
self.assertEqual(table.nrows, nrows)
class UpdateRowTestCase1(UpdateRowTestCase):
reopen = 0
buffersize = 1
class UpdateRowTestCase2(UpdateRowTestCase):
reopen = 1
buffersize = 2
class UpdateRowTestCase3(UpdateRowTestCase):
reopen = 0
buffersize = 1000
class UpdateRowTestCase4(UpdateRowTestCase):
reopen = 1
buffersize = 1000
def suite():
theSuite = unittest.TestSuite()
niter = 1
# common.heavy = 1 # Uncomment this only for testing purposes
for n in range(niter):
theSuite.addTest(unittest.makeSuite(BasicWriteTestCase))
theSuite.addTest(unittest.makeSuite(DictWriteTestCase))
theSuite.addTest(unittest.makeSuite(RecordDTWriteTestCase))
theSuite.addTest(unittest.makeSuite(NumPyDTWriteTestCase))
theSuite.addTest(unittest.makeSuite(RecArrayOneWriteTestCase))
theSuite.addTest(unittest.makeSuite(RecArrayTwoWriteTestCase))
theSuite.addTest(unittest.makeSuite(RecArrayThreeWriteTestCase))
theSuite.addTest(unittest.makeSuite(CompressZLIBTablesTestCase))
theSuite.addTest(unittest.makeSuite(CompressTwoTablesTestCase))
theSuite.addTest(unittest.makeSuite(IterRangeTestCase))
theSuite.addTest(unittest.makeSuite(RecArrayRangeTestCase))
theSuite.addTest(unittest.makeSuite(GetColRangeTestCase))
theSuite.addTest(unittest.makeSuite(DefaultValues))
theSuite.addTest(unittest.makeSuite(RecArrayIO))
theSuite.addTest(unittest.makeSuite(ShapeTestCase1))
theSuite.addTest(unittest.makeSuite(ShapeTestCase2))
theSuite.addTest(unittest.makeSuite(SetItemTestCase1))
theSuite.addTest(unittest.makeSuite(SetItemTestCase2))
theSuite.addTest(unittest.makeSuite(SetItemTestCase3))
theSuite.addTest(unittest.makeSuite(SetItemTestCase4))
theSuite.addTest(unittest.makeSuite(UpdateRowTestCase1))
theSuite.addTest(unittest.makeSuite(UpdateRowTestCase2))
theSuite.addTest(unittest.makeSuite(UpdateRowTestCase3))
theSuite.addTest(unittest.makeSuite(UpdateRowTestCase4))
theSuite.addTest(unittest.makeSuite(CompressBloscTablesTestCase))
theSuite.addTest(unittest.makeSuite(CompressLZOTablesTestCase))
if common.heavy:
theSuite.addTest(unittest.makeSuite(CompressBzip2TablesTestCase))
theSuite.addTest(unittest.makeSuite(BigTablesTestCase))
return theSuite
if __name__ == '__main__':
common.parse_argv(sys.argv)
common.print_versions()
unittest.main(defaultTest='suite')
|